Example usage for org.apache.commons.lang3 ClassUtils primitiveToWrapper

List of usage examples for org.apache.commons.lang3 ClassUtils primitiveToWrapper

Introduction

In this page you can find the example usage for org.apache.commons.lang3 ClassUtils primitiveToWrapper.

Prototype

public static Class<?> primitiveToWrapper(final Class<?> cls) 

Source Link

Document

Converts the specified primitive Class object to its corresponding wrapper Class object.

NOTE: From v2.2, this method handles Void.TYPE , returning Void.TYPE .

Usage

From source file:com.datatorrent.contrib.enrichment.POJOEnrichmentOperator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Setter generateSettersForField(Class<?> klass, String outputFieldName)
        throws NoSuchFieldException, SecurityException {
    Field f = outputClass.getDeclaredField(outputFieldName);
    Class c = ClassUtils.primitiveToWrapper(f.getType());
    Setter classSetter = PojoUtils.createSetter(klass, outputFieldName, c);
    return classSetter;
}

From source file:hu.bme.mit.sette.tools.catg.CatgGenerator.java

private static String createCatgRead(Class<?> javaClass) {
    if (javaClass.isPrimitive()) {
        javaClass = ClassUtils.primitiveToWrapper(javaClass);
    }//from w w w . j  ava 2 s  . c  om

    if (javaClass.equals(Byte.class)) {
        return "CATG.readByte((byte) 1)";
    } else if (javaClass.equals(Short.class)) {
        return "CATG.readShort((short) 1)";
    } else if (javaClass.equals(Integer.class)) {
        return "CATG.readInt(1)";
    } else if (javaClass.equals(Long.class)) {
        return "CATG.readLong(1L)";
    } else if (javaClass.equals(Boolean.class)) {
        return "CATG.readBool(false)";
    } else if (javaClass.equals(Character.class)) {
        return "CATG.readChar(' ')";
    } else if (javaClass.equals(String.class)) {
        return "CATG.readString(\"\")";
    } else {
        return null;
    }
}

From source file:com.datatorrent.contrib.enrichment.POJOEnrichmentOperator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Getter generateGettersForField(Class<?> klass, String inputFieldName)
        throws NoSuchFieldException, SecurityException {
    Field f = klass.getDeclaredField(inputFieldName);
    Class c = ClassUtils.primitiveToWrapper(f.getType());
    Getter classGetter = PojoUtils.createGetter(klass, inputFieldName, c);
    return classGetter;
}

From source file:com.datatorrent.contrib.parser.FixedWidthParser.java

/**
 * Function to add a setter for a field and add it
 * to the List of setters/*from  w  ww.  j  ava 2 s.c  o m*/
 *
 * @param fieldName name of the field for which setter is to be added
 */
private void addSetter(String fieldName) {
    try {
        Field f = clazz.getDeclaredField(fieldName);
        FixedWidthParser.TypeInfo t = new FixedWidthParser.TypeInfo(f.getName(),
                ClassUtils.primitiveToWrapper(f.getType()));
        t.setter = PojoUtils.createSetter(clazz, t.name, t.type);
        setters.add(t);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException("Field " + fieldName + " not found in class " + clazz, e);
    } catch (Exception e) {
        throw new RuntimeException("Exception while adding a setter" + e.getMessage(), e);
    }
}

From source file:com.datatorrent.contrib.parquet.ParquetFilePOJOReader.java

/**
 * Use reflection to generate field info values if the user has not provided
 * the inputs mapping.//w w  w .  j  a va 2  s.c o  m
 *
 * @return String representing the Parquet field name to POJO field name
 *         mapping
 */
private String generateFieldInfoInputs() {
    java.lang.reflect.Field[] fields = pojoClass.getDeclaredFields();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < fields.length; i++) {
        java.lang.reflect.Field f = fields[i];
        Class<?> c = ClassUtils.primitiveToWrapper(f.getType());
        sb.append(f.getName() + FIELD_SEPARATOR + f.getName() + FIELD_SEPARATOR
                + c.getSimpleName().toUpperCase() + RECORD_SEPARATOR);
    }
    return sb.substring(0, sb.length() - 1);
}

From source file:io.wcm.caconfig.editor.impl.ConfigDataServlet.java

@SuppressWarnings("null")
private JSONObject toJson(ConfigurationData config, Boolean inherited, String fullConfigName)
        throws JSONException {
    JSONObject result = new JSONObject();

    result.putOpt("configName", config.getConfigName());
    result.putOpt("collectionItemName", config.getCollectionItemName());
    result.putOpt("overridden", config.isOverridden());
    if (inherited != null) {
        result.put("inherited", inherited.booleanValue());
    }/*w ww.  ja  va 2s .co  m*/

    JSONArray props = new JSONArray();
    for (String propertyName : config.getPropertyNames()) {
        ValueInfo<?> item = config.getValueInfo(propertyName);
        PropertyMetadata<?> itemMetadata = item.getPropertyMetadata();

        JSONObject prop = new JSONObject();
        prop.putOpt("name", item.getName());

        // special handling for nested configs and nested config collections
        if (itemMetadata != null && itemMetadata.isNestedConfiguration()) {
            JSONObject metadata = new JSONObject();
            metadata.putOpt("label", itemMetadata.getLabel());
            metadata.putOpt("description", itemMetadata.getDescription());
            metadata.putOpt("properties", toJson(itemMetadata.getProperties()));
            prop.put("metadata", metadata);

            if (itemMetadata.getType().isArray()) {
                ConfigurationData[] configDatas = (ConfigurationData[]) item.getValue();
                if (configDatas != null) {
                    JSONObject nestedConfigCollection = new JSONObject();
                    StringBuilder collectionConfigName = new StringBuilder();
                    if (config.getCollectionItemName() != null) {
                        collectionConfigName
                                .append(configurationPersistenceStrategy.getCollectionItemConfigName(
                                        fullConfigName + "/" + config.getCollectionItemName(),
                                        config.getResourcePath()));
                    } else {
                        collectionConfigName.append(configurationPersistenceStrategy
                                .getConfigName(fullConfigName, config.getResourcePath()));
                    }
                    collectionConfigName.append("/").append(itemMetadata.getConfigurationMetadata().getName());
                    nestedConfigCollection.put("configName", collectionConfigName.toString());
                    JSONArray items = new JSONArray();
                    for (ConfigurationData configData : configDatas) {
                        items.put(toJson(configData, false, collectionConfigName.toString()));
                    }
                    nestedConfigCollection.put("items", items);
                    prop.put("nestedConfigCollection", nestedConfigCollection);
                }
            } else {
                ConfigurationData configData = (ConfigurationData) item.getValue();
                if (configData != null) {
                    prop.put("nestedConfig", toJson(configData, null,
                            fullConfigName + "/" + itemMetadata.getConfigurationMetadata().getName()));
                }
            }
        }

        // property data and metadata
        else {
            prop.putOpt("value", toJsonValue(item.getValue()));
            prop.putOpt("effectiveValue", toJsonValue(item.getEffectiveValue()));
            prop.putOpt("configSourcePath", item.getConfigSourcePath());
            prop.putOpt("default", item.isDefault());
            prop.putOpt("inherited", item.isInherited());
            prop.putOpt("overridden", item.isOverridden());

            if (itemMetadata != null) {
                JSONObject metadata = new JSONObject();
                if (itemMetadata.getType().isArray()) {
                    metadata.put("type", ClassUtils
                            .primitiveToWrapper(itemMetadata.getType().getComponentType()).getSimpleName());
                    metadata.put("multivalue", true);
                } else {
                    metadata.put("type", ClassUtils.primitiveToWrapper(itemMetadata.getType()).getSimpleName());
                }
                metadata.putOpt("defaultValue", toJsonValue(itemMetadata.getDefaultValue()));
                metadata.putOpt("label", itemMetadata.getLabel());
                metadata.putOpt("description", itemMetadata.getDescription());
                metadata.putOpt("properties", toJson(itemMetadata.getProperties()));
                prop.put("metadata", metadata);
            }
        }
        props.put(prop);
    }
    result.put("properties", props);

    return result;
}

From source file:com.link_intersystems.lang.Conversions.java

/**
 * Boxing conversion converts values of primitive type to corresponding
 * values of reference type. Specifically, the following 8 conversion are
 * called the boxing conversions://  w  w  w . j  av a2s  . co  m
 * <ul>
 * <li>From type boolean to type Boolean</li>
 * <li>From type byte to type Byte</li>
 * <li>From type char to type Character</li>
 * <li>From type short to type Short</li>
 * <li>From type int to type Integer</li>
 * <li>From type long to type Long</li>
 * <li>From type float to type Float</li>
 * <li>From type double to type Double</li>
 * </ul>
 *
 * @param primitive
 * @return the wrapper type for the primitive or null if primitive is not a
 *         primitive type.
 * @since 1.0.0.0
 */
public static Class<?> getBoxingConversion(Class<?> primitive) {
    Class<?> wrapper = ClassUtils.primitiveToWrapper(primitive);
    boolean wrapperEqualsPrimitive = ObjectUtils.equals(wrapper, primitive);

    Class<?> autoBoxedClass = null;

    if (!wrapperEqualsPrimitive) {
        autoBoxedClass = wrapper;
    }

    return autoBoxedClass;
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#add(java.lang.Object, java.lang.Number)}.
 *///w w  w.jav a2  s  .c  om
@SuppressWarnings("unchecked")
@Test
public void testAddObjectT() {
    assertEquals("null", null, add((Object) null, null));
    assertEquals("null", null, add("123.456", null));
    assertEquals("null", (Object) 10, add("", 10));
    assertEquals("null", (Object) 10, add((Object) null, 10));
    assertEquals("null", (Object) 123, add("123.456", 0));
    assertEquals("null", (Object) 123.456f, add("123.456d", 0f));
    assertEquals("123 + .456: Float", (Object) 123.456f, add("123", .456f));
    assertEquals("123 + .456: Float", (Object) Float.class, add("123d", .456f).getClass());
    assertEquals("123 + .456: Float", (Object) Float.class,
            add((Object) BigDecimal.valueOf(123d), .456f).getClass());
    for (Class<?> type : NUMBERS) {
        try {
            Object o = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                o = wrapper.getMethod("valueOf", String.class).invoke(null, "123");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                o = c.newInstance("123");
            }
            assertEquals("123.456: " + type.getSimpleName(), add(".456", (Number) o, typeOfN),
                    add(".456", (Number) o));
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:jp.furplag.util.time.DateTimeUtils.java

/**
 * Constructs an instance from an Object that represents a datetime.
 * <p>/*from  w w w .j  a  va  2s .c o  m*/
 * {@code initializer} specifiable
 * <ul>
 * <li>{@code DateTime} means {@code initializer.withMillis(new DateTime(instant).getMillis())}.</li>
 * <li>{@code DateTimeZone} and {@code TimeZone} means {@code new DateTime(instant, jp.furplag.util.Localizer.newDateTimeZone(initializer))}.</li>
 * <li>{@code String} means time zone ID or offset time ( {@code new DateTime(instant, jp.furplag.util.Localizer.newDateTimeZone(initializer))} ).</li>
 * <li>{@code Chronology} means {@code new DateTime(instant, initializer)}.</li>
 * <li>{@code long} means the milliseconds of offset to UTC ( {@code new DateTime(instant, DateTimeZone.forOffsetMillis(initializer.getMillisOfDay()))} ).</li>
 * <li>{@code LocalTime} means the time of offset to UTC ( {@code new DateTime(instant, DateTimeZone.forOffsetMillis(initializer.getMillisOfDay()))} ).</li>
 * </ul>
 * </p>
 *
 * @param instant the datetime object. If {@code strictly} is false, null means current date-time.
 * @param initializer structure for {@code instant}.
 * @param strictly if true, throw exceptions when the instant is invalid. And if false, returns null when the instant is invalid.
 * @return an instance from an Object that represents a datetime.
 * @throws IllegalArgumentException if the instant is invalid.
 */
public static DateTime toDT(final Object instant, final Object initializer, final boolean strictly) {
    if (strictly && instant == null)
        return null;
    if (initializer == null)
        return getDateTime(instant, DateTimeZone.UTC, strictly);
    if (initializer instanceof DateTime)
        return getDateTime(instant, ((DateTime) initializer), strictly);
    if (initializer instanceof DateTimeZone)
        return getDateTime(instant, ((DateTimeZone) initializer), strictly);
    if (initializer instanceof Chronology)
        return getDateTime(instant, ((Chronology) initializer), strictly);
    if (initializer instanceof TimeZone)
        return getDateTime(instant, Localizer.getDateTimeZone(initializer), strictly);
    if (initializer instanceof String)
        return getDateTime(instant, Localizer.getDateTimeZone(initializer), strictly);
    if (initializer instanceof LocalTime)
        return getDateTime(instant, DateTimeZone.forOffsetMillis(((LocalTime) initializer).getMillisOfDay()),
                strictly);
    if (Number.class.isAssignableFrom(ClassUtils.primitiveToWrapper(initializer.getClass()))) {
        if (NumberUtils.compareTo(valueOf(initializer), MILLIS_OF_DAY) < 0)
            return getDateTime(instant, DateTimeZone.forOffsetMillis(valueOf(initializer, int.class)),
                    strictly);
    }

    return getDateTime(instant, DateTimeZone.UTC, strictly);
}

From source file:com.strider.datadefender.DatabaseAnonymizer.java

/**
 * Calls the anonymization function for the given Column, and returns its
 * anonymized value.// w  w w  .  j  a  va2 s. com
 * 
 * @param dbConn
 * @param row
 * @param column
 * @return
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws InvocationTargetException 
 */
private Object callAnonymizingFunctionWithParameters(final Connection dbConn, final ResultSet row,
        final Column column, final String vendor) throws SQLException, NoSuchMethodException, SecurityException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    final String function = column.getFunction();
    if (function == null || function.equals("")) {
        log.warn("Function is not defined for column [" + column + "]. Moving to the next column.");
        return "";
    }

    try {
        final String className = Utils.getClassName(function);
        final String methodName = Utils.getMethodName(function);
        final Class<?> clazz = Class.forName(className);

        final CoreFunctions instance = (CoreFunctions) Class.forName(className).newInstance();
        instance.setDatabaseConnection(dbConn);
        instance.setVendor(vendor);

        final List<Parameter> parms = column.getParameters();
        final Map<String, Object> paramValues = new HashMap<>(parms.size());
        final String columnValue = row.getString(column.getName());

        for (final Parameter param : parms) {
            if (param.getValue().equals("@@value@@")) {
                paramValues.put(param.getName(), columnValue);
            } else if (param.getValue().equals("@@row@@") && param.getType().equals("java.sql.ResultSet")) {
                paramValues.put(param.getName(), row);
            } else {
                paramValues.put(param.getName(), param.getTypeValue());
            }
        }

        final List<Object> fnArguments = new ArrayList<>(parms.size());
        final Method[] methods = clazz.getMethods();
        Method selectedMethod = null;

        methodLoop: for (final Method m : methods) {
            if (m.getName().equals(methodName) && m.getReturnType() == String.class) {

                log.debug("  Found method: " + m.getName());
                log.debug("  Match w/: " + paramValues);

                final java.lang.reflect.Parameter[] mParams = m.getParameters();
                fnArguments.clear();
                for (final java.lang.reflect.Parameter par : mParams) {
                    //log.debug("    Name present? " + par.isNamePresent());
                    // Note: requires -parameter compiler flag
                    log.debug("    Real param: " + par.getName());
                    if (!paramValues.containsKey(par.getName())) {
                        continue methodLoop;
                    }

                    final Object value = paramValues.get(par.getName());
                    Class<?> fnParamType = par.getType();
                    final Class<?> confParamType = (value == null) ? fnParamType : value.getClass();

                    if (fnParamType.isPrimitive() && value == null) {
                        continue methodLoop;
                    }
                    if (ClassUtils.isPrimitiveWrapper(confParamType)) {
                        if (!ClassUtils.isPrimitiveOrWrapper(fnParamType)) {
                            continue methodLoop;
                        }
                        fnParamType = ClassUtils.primitiveToWrapper(fnParamType);
                    }
                    if (!fnParamType.equals(confParamType)) {
                        continue methodLoop;
                    }
                    fnArguments.add(value);
                }

                // actual parameters check less than xml defined parameters size, because values could be auto-assigned (like 'values' and 'row' params)
                if (fnArguments.size() != mParams.length || fnArguments.size() < paramValues.size()) {
                    continue;
                }

                selectedMethod = m;
                break;
            }
        }

        if (selectedMethod == null) {
            final StringBuilder s = new StringBuilder("Anonymization method: ");
            s.append(methodName).append(" with parameters matching (");
            String comma = "";
            for (final Parameter p : parms) {
                s.append(comma).append(p.getType()).append(' ').append(p.getName());
                comma = ", ";
            }
            s.append(") was not found in class ").append(className);
            throw new NoSuchMethodException(s.toString());
        }

        log.debug("Anonymizing function: " + methodName + " with parameters: "
                + Arrays.toString(fnArguments.toArray()));
        final Object anonymizedValue = selectedMethod.invoke(instance, fnArguments.toArray());
        if (anonymizedValue == null) {
            return null;
        }
        return anonymizedValue.toString();

    } catch (InstantiationException | ClassNotFoundException ex) {
        log.error(ex.toString());
    }

    return "";
}