Example usage for java.lang.reflect Field setLong

List of usage examples for java.lang.reflect Field setLong

Introduction

In this page you can find the example usage for java.lang.reflect Field setLong.

Prototype

@CallerSensitive
@ForceInline 
public void setLong(Object obj, long l) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the value of a field as a long on the specified object.

Usage

From source file:com.cloudera.sqoop.SqoopOptions.java

@SuppressWarnings("unchecked")
/**//from   www .  j  a  v  a 2 s. co  m
 * Given a set of properties, load this into the current SqoopOptions
 * instance.
 */
public void loadProperties(Properties props) {

    try {
        Field[] fields = getClass().getDeclaredFields();
        for (Field f : fields) {
            if (f.isAnnotationPresent(StoredAsProperty.class)) {
                Class typ = f.getType();
                StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class);
                String propName = storedAs.value();

                if (typ.equals(int.class)) {
                    f.setInt(this, getIntProperty(props, propName, f.getInt(this)));
                } else if (typ.equals(boolean.class)) {
                    f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this)));
                } else if (typ.equals(long.class)) {
                    f.setLong(this, getLongProperty(props, propName, f.getLong(this)));
                } else if (typ.equals(String.class)) {
                    f.set(this, props.getProperty(propName, (String) f.get(this)));
                } else if (typ.equals(Integer.class)) {
                    String value = props.getProperty(propName,
                            f.get(this) == null ? "null" : f.get(this).toString());
                    f.set(this, value.equals("null") ? null : new Integer(value));
                } else if (typ.isEnum()) {
                    f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString())));
                } else {
                    throw new RuntimeException("Could not retrieve property " + propName + " for type: " + typ);
                }
            }
        }
    } catch (IllegalAccessException iae) {
        throw new RuntimeException("Illegal access to field in property setter", iae);
    }

    // Now load properties that were stored with special types, or require
    // additional logic to set.

    if (getBooleanProperty(props, "db.require.password", false)) {
        // The user's password was stripped out from the metastore.
        // Require that the user enter it now.
        setPasswordFromConsole();
    } else {
        this.password = props.getProperty("db.password", this.password);
    }

    if (this.jarDirIsAuto) {
        // We memoized a user-specific nonce dir for compilation to the data
        // store.  Disregard that setting and create a new nonce dir.
        String localUsername = System.getProperty("user.name", "unknown");
        this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile");
    }

    String colListStr = props.getProperty("db.column.list", null);
    if (null != colListStr) {
        this.columns = listToArray(colListStr);
    }

    this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters);
    this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters);

    this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs);

    // Delimiters were previously memoized; don't let the tool override
    // them with defaults.
    this.areDelimsManuallySet = true;
}

From source file:alice.tuprolog.lib.OOLibrary.java

/**
 * set the field value of an object/*from  w  w  w. j a  v  a2  s  . c o m*/
 */
private boolean java_set(PTerm objId, PTerm fieldTerm, PTerm what) {
    what = what.getTerm();
    if (!fieldTerm.isAtom() || what instanceof Var)
        return false;
    String fieldName = ((Struct) fieldTerm).getName();
    Object obj = null;
    try {
        Class<?> cl = null;
        if (objId.isCompound() && ((Struct) objId).getName().equals("class")) {
            String clName = null;
            // Case: class(className)
            if (((Struct) objId).getArity() == 1)
                clName = alice.util.Tools.removeApices(((Struct) objId).getArg(0).toString());
            if (clName != null) {
                try {
                    cl = Class.forName(clName, true, dynamicLoader);
                } catch (ClassNotFoundException ex) {
                    getEngine().logger.warn("Java class not found: " + clName);
                    return false;
                } catch (Exception ex) {
                    getEngine().logger.warn("Static field " + fieldName + " not found in class "
                            + alice.util.Tools.removeApices(((Struct) objId).getArg(0).toString()));
                    return false;
                }
            }
        } else {
            String objName = alice.util.Tools.removeApices(objId.toString());
            obj = currentObjects.get(objName);
            if (obj != null) {
                cl = obj.getClass();
            } else {
                return false;
            }
        }

        // first check for primitive data field
        Field field = cl.getField(fieldName);
        if (what instanceof Number) {
            Number wn = (Number) what;
            if (wn instanceof Int) {
                field.setInt(obj, wn.intValue());
            } else if (wn instanceof alice.tuprolog.Double) {
                field.setDouble(obj, wn.doubleValue());
            } else if (wn instanceof alice.tuprolog.Long) {
                field.setLong(obj, wn.longValue());
            } else if (wn instanceof alice.tuprolog.Float) {
                field.setFloat(obj, wn.floatValue());
            } else {
                return false;
            }
        } else {
            String what_name = alice.util.Tools.removeApices(what.toString());
            Object obj2 = currentObjects.get(what_name);
            if (obj2 != null) {
                field.set(obj, obj2);
            } else {
                // consider value as a simple string
                field.set(obj, what_name);
            }
        }
        return true;
    } catch (NoSuchFieldException ex) {
        getEngine().logger.warn("Field " + fieldName + " not found in class " + objId);
        return false;
    } catch (Exception ex) {
        return false;
    }
}

From source file:org.apache.sqoop.SqoopOptions.java

@SuppressWarnings("unchecked")
/**/* w  w w .j  av  a 2s.co m*/
 * Given a set of properties, load this into the current SqoopOptions
 * instance.
 */
public void loadProperties(Properties props) {

    try {
        Field[] fields = SqoopOptions.class.getDeclaredFields();
        for (Field f : fields) {
            if (f.isAnnotationPresent(StoredAsProperty.class)) {
                Class typ = f.getType();
                StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class);
                String propName = storedAs.value();

                if (typ.equals(int.class)) {
                    f.setInt(this, getIntProperty(props, propName, f.getInt(this)));
                } else if (typ.equals(boolean.class)) {
                    f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this)));
                } else if (typ.equals(long.class)) {
                    f.setLong(this, getLongProperty(props, propName, f.getLong(this)));
                } else if (typ.equals(String.class)) {
                    f.set(this, props.getProperty(propName, (String) f.get(this)));
                } else if (typ.equals(Integer.class)) {
                    String value = props.getProperty(propName,
                            f.get(this) == null ? "null" : f.get(this).toString());
                    f.set(this, value.equals("null") ? null : new Integer(value));
                } else if (typ.isEnum()) {
                    f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString())));
                } else {
                    throw new RuntimeException("Could not retrieve property " + propName + " for type: " + typ);
                }
            }
        }
    } catch (IllegalAccessException iae) {
        throw new RuntimeException("Illegal access to field in property setter", iae);
    }

    // Now load properties that were stored with special types, or require
    // additional logic to set.

    if (getBooleanProperty(props, "db.require.password", false)) {
        // The user's password was stripped out from the metastore.
        // Require that the user enter it now.
        setPasswordFromConsole();
    } else {
        this.password = props.getProperty("db.password", this.password);
    }

    if (this.jarDirIsAuto) {
        // We memoized a user-specific nonce dir for compilation to the data
        // store.  Disregard that setting and create a new nonce dir.
        String localUsername = System.getProperty("user.name", "unknown");
        this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile");
    }

    String colListStr = props.getProperty("db.column.list", null);
    if (null != colListStr) {
        this.columns = listToArray(colListStr);
    }

    this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters);
    this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters);

    this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs);

    this.connectionParams = getPropertiesAsNetstedProperties(props, "db.connect.params");

    // Loading user mapping
    this.mapColumnHive = getPropertiesAsNetstedProperties(props, "map.column.hive");
    this.mapColumnJava = getPropertiesAsNetstedProperties(props, "map.column.java");

    // Delimiters were previously memoized; don't let the tool override
    // them with defaults.
    this.areDelimsManuallySet = true;

    // If we loaded true verbose flag, we need to apply it
    if (this.verbose) {
        LoggingUtils.setDebugLevel();
    }

    // Custom configuration options
    this.invalidIdentifierPrefix = props.getProperty("invalid.identifier.prefix", "_");
}

From source file:org.rzo.yajsw.os.ms.win.w32.WindowsXPProcess.java

/**
 * Writefd.//from  www. j  a  va 2s  .  c  o  m
 * 
 * @param fd
 *            the fd
 * @param pointer
 *            the pointer
 */
private void writefd(FileDescriptor fd, Pointer pointer) {
    try {
        // Field[] fields = FileDescriptor.class.getDeclaredFields();
        // System.out.println("fields");
        // for (Field field : fields){
        // System.out.println(field.getName());
        // }
        // System.out.println("writefd");
        Field handleField = FileDescriptor.class.getDeclaredField("handle");
        handleField.setAccessible(true);
        Field peerField = Pointer.class.getDeclaredField("peer");
        peerField.setAccessible(true);
        long value = peerField.getLong(pointer);
        // System.out.println(value);
        // System.out.flush();
        handleField.setLong(fd, value);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.soyatec.windowsazure.table.internal.CloudTableRest.java

/**
 * Deserial the xml to object accord to the give model class.
 *
 * @param partitionKey//from  w  w  w.j  a  va2  s  .c o  m
 * @param rowKey
 * @param eTag
 * @param timestamp
 * @param values
 * @return Instance of the given model class.
 */
private ITableServiceEntity createObjectByModelClass(String partitionKey, String rowKey, String eTag,
        String timestamp, List<ICloudTableColumn> values) {
    ITableServiceEntity newInstance = instanceModel(partitionKey, rowKey, eTag, timestamp, values);
    if (newInstance == null) {
        return null;
    }
    // Copy Field
    if (values != null && !values.isEmpty()) {
        for (ICloudTableColumn column : values) {
            Field field = null;
            try {
                field = newInstance.getClass().getDeclaredField(column.getName());
            } catch (NoSuchFieldException e) {
                continue;
            }

            if (field == null) {
                continue;
            }
            int modifier = field.getModifiers();
            if (Modifier.isPrivate(modifier) && Modifier.isFinal(modifier) && Modifier.isStatic(modifier)) {
                if (getModelClass() != null) {
                    Logger.debug(MessageFormat.format(
                            "{0} class {1} is a static final field. Can not set data to it.",
                            getModelClass().getClass(), field.getName()));
                }
                continue;
            }

            boolean accessible = field.isAccessible();
            if (!accessible) {
                field.setAccessible(true);
            }
            ETableColumnType type = column.getType();
            String value = column.getValue();
            if (value == null) {
                continue;
            } else {
                try {
                    if (type == null) {
                        setStringOrObjectField(newInstance, column, field, value);
                    } else if (type.equals(ETableColumnType.TYPE_BINARY)) {
                        field.set(newInstance, Base64.decode(value));
                    } else if (type.equals(ETableColumnType.TYPE_BOOL)) {
                        field.setBoolean(newInstance, Boolean.parseBoolean(value));
                    } else if (type.equals(ETableColumnType.TYPE_DATE_TIME)) {
                        field.set(newInstance, Utilities.tryGetDateTimeFromTableEntry(value));
                    } else if (type.equals(ETableColumnType.TYPE_DOUBLE)) {
                        field.setDouble(newInstance, Double.parseDouble(value));
                    } else if (type.equals(ETableColumnType.TYPE_GUID)) {
                        Guid guid = new Guid();
                        try {
                            Field valueField = guid.getClass().getDeclaredField("value");
                            boolean accessiable = valueField.isAccessible();
                            if (!accessible) {
                                valueField.setAccessible(true);
                            }
                            valueField.set(guid, value);
                            valueField.setAccessible(accessiable);
                            field.set(newInstance, guid);
                        } catch (NoSuchFieldException e) {
                            Logger.error(e.getMessage(), e);
                        }
                    } else if (type.equals(ETableColumnType.TYPE_INT)) {
                        try {
                            field.setInt(newInstance, Integer.parseInt(value));
                        } catch (Exception e) {
                            field.setByte(newInstance, Byte.parseByte(value));
                        }
                    } else if (type.equals(ETableColumnType.TYPE_LONG)) {
                        field.setLong(newInstance, Long.parseLong(value));
                    } else if (type.equals(ETableColumnType.TYPE_STRING)) {
                        setStringOrObjectField(newInstance, column, field, value);
                    }
                } catch (Exception e) {
                    Logger.error(
                            MessageFormat.format("{0} class filed {1} set failed.", getModelClass(), value), e);
                }
            }
            // revert aaccessible
            field.setAccessible(accessible);
        }
    }
    return newInstance;
}

From source file:com.qmetry.qaf.automation.data.BaseDataBean.java

/**
 * This will fill random data except those properties which has skip=true in
 * {@link Randomizer} annotation. Use {@link Randomizer} annotation to
 * specify data value to be generated for specific property.
 * /*from  w w  w. jav a2  s .  c o m*/
 * @see Randomizer
 */
public void fillRandomData() {
    Field[] fields = getFields();
    for (Field field : fields) {
        logger.debug("NAME :: " + field.getName());
        if (!(Modifier.isFinal(field.getModifiers()))) {
            RandomizerTypes type = RandomizerTypes.MIXED;
            int len = 10;
            long min = 0, max = 0;
            String prefix = "", suffix = "";
            String format = "";
            String[] list = {};

            Randomizer randomizer = field.getAnnotation(Randomizer.class);

            if (randomizer != null) {
                if (randomizer.skip()) {
                    continue;
                }
                type = field.getType() == Date.class ? RandomizerTypes.DIGITS_ONLY : randomizer.type();
                len = randomizer.length();
                prefix = randomizer.prefix();
                suffix = randomizer.suffix();
                min = randomizer.minval();
                max = min > randomizer.maxval() ? min : randomizer.maxval();
                format = randomizer.format();
                list = randomizer.dataset();
            } else {
                // @Since 2.1.2 randomizer annotation is must for random
                // value
                // generation
                continue;
            }

            String str = "";
            if ((list == null) || (list.length == 0)) {
                str = StringUtil.isBlank(format)
                        ? RandomStringUtils.random(len, !type.equals(RandomizerTypes.DIGITS_ONLY),
                                !type.equals(RandomizerTypes.LETTERS_ONLY))
                        : StringUtil.getRandomString(format);
            } else {
                str = getRandomValue(list);
            }

            try {
                // deal with IllegalAccessException
                field.setAccessible(true);
                Method setter = null;
                try {
                    setter = this.getClass().getMethod("set" + StringUtil.getTitleCase(field.getName()),
                            String.class);
                } catch (Exception e) {

                }

                if ((field.getType() == String.class) || (null != setter)) {
                    if ((list == null) || (list.length == 0)) {
                        if ((min == max) && (min == 0)) {
                            str = StringUtil.isBlank(format)
                                    ? RandomStringUtils.random(len, !type.equals(RandomizerTypes.DIGITS_ONLY),
                                            !type.equals(RandomizerTypes.LETTERS_ONLY))
                                    : StringUtil.getRandomString(format);

                        } else {
                            str = String.valueOf((int) (Math.random() * ((max - min) + 1)) + min);

                        }
                    }
                    String rStr = prefix + str + suffix;
                    if (null != setter) {
                        setter.setAccessible(true);
                        setter.invoke(this, rStr);
                    } else {
                        field.set(this, rStr);
                    }
                } else {
                    String rStr = "";
                    if ((min == max) && (min == 0)) {
                        rStr = RandomStringUtils.random(len, false, true);
                    } else {
                        rStr = String.valueOf((int) (Math.random() * ((max - min) + 1)) + min);

                    }

                    if (field.getType() == Integer.TYPE) {
                        field.setInt(this, Integer.parseInt(rStr));
                    } else if (field.getType() == Float.TYPE) {
                        field.setFloat(this, Float.parseFloat(rStr));

                    } else if (field.getType() == Double.TYPE) {
                        field.setDouble(this, Double.parseDouble(rStr));

                    } else if (field.getType() == Long.TYPE) {
                        field.setLong(this, Long.parseLong(rStr));

                    } else if (field.getType() == Short.TYPE) {
                        field.setShort(this, Short.parseShort(rStr));
                    } else if (field.getType() == Date.class) {
                        logger.info("filling date " + rStr);
                        int days = Integer.parseInt(rStr);
                        field.set(this, DateUtil.getDate(days));
                    } else if (field.getType() == Boolean.TYPE) {
                        field.setBoolean(this, RandomUtils.nextBoolean());

                    }
                }
            } catch (IllegalArgumentException e) {

                logger.error("Unable to fill random data in field " + field.getName(), e);
            } catch (IllegalAccessException e) {
                logger.error("Unable to Access " + field.getName(), e);
            } catch (InvocationTargetException e) {
                logger.error("Unable to Access setter for " + field.getName(), e);

            }
        }

    }

}

From source file:au.com.addstar.cellblock.configuration.AutoConfig.java

@SuppressWarnings("unchecked")
public boolean load() {
    FileConfiguration yml = new YamlConfiguration();
    try {//from   www . ja  v  a 2  s. c  o m
        if (mFile.getParentFile().exists() || mFile.getParentFile().mkdirs()) {// Make sure the file exists
            if (mFile.exists() || mFile.createNewFile()) {
                // Parse the config
                yml.load(mFile);
                for (Field field : getClass().getDeclaredFields()) {
                    ConfigField configField = field.getAnnotation(ConfigField.class);
                    if (configField == null)
                        continue;

                    String optionName = configField.name();
                    if (optionName.isEmpty())
                        optionName = field.getName();

                    field.setAccessible(true);

                    String path = (configField.category().isEmpty() ? "" : configField.category() + ".") //$NON-NLS-2$
                            + optionName;
                    if (!yml.contains(path)) {
                        if (field.get(this) == null)
                            throw new InvalidConfigurationException(
                                    path + " is required to be set! Info:\n" + configField.comment());
                    } else {
                        // Parse the value

                        if (field.getType().isArray()) {
                            // Integer
                            if (field.getType().getComponentType().equals(Integer.TYPE))
                                field.set(this, yml.getIntegerList(path).toArray(new Integer[0]));

                            // Float
                            else if (field.getType().getComponentType().equals(Float.TYPE))
                                field.set(this, yml.getFloatList(path).toArray(new Float[0]));

                            // Double
                            else if (field.getType().getComponentType().equals(Double.TYPE))
                                field.set(this, yml.getDoubleList(path).toArray(new Double[0]));

                            // Long
                            else if (field.getType().getComponentType().equals(Long.TYPE))
                                field.set(this, yml.getLongList(path).toArray(new Long[0]));

                            // Short
                            else if (field.getType().getComponentType().equals(Short.TYPE))
                                field.set(this, yml.getShortList(path).toArray(new Short[0]));

                            // Boolean
                            else if (field.getType().getComponentType().equals(Boolean.TYPE))
                                field.set(this, yml.getBooleanList(path).toArray(new Boolean[0]));

                            // String
                            else if (field.getType().getComponentType().equals(String.class)) {
                                field.set(this, yml.getStringList(path).toArray(new String[0]));
                            } else
                                throw new IllegalArgumentException("Cannot use type "
                                        + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-1$
                        } else if (List.class.isAssignableFrom(field.getType())) {
                            if (field.getGenericType() == null)
                                throw new IllegalArgumentException(
                                        "Cannot use type List without specifying generic type for AutoConfiguration");

                            Type type = ((ParameterizedType) field.getGenericType())
                                    .getActualTypeArguments()[0];

                            if (type.equals(Integer.class))
                                field.set(this, newList((Class<? extends List<Integer>>) field.getType(),
                                        yml.getIntegerList(path)));
                            else if (type.equals(Float.class))
                                field.set(this, newList((Class<? extends List<Float>>) field.getType(),
                                        yml.getFloatList(path)));
                            else if (type.equals(Double.class))
                                field.set(this, newList((Class<? extends List<Double>>) field.getType(),
                                        yml.getDoubleList(path)));
                            else if (type.equals(Long.class))
                                field.set(this, newList((Class<? extends List<Long>>) field.getType(),
                                        yml.getLongList(path)));
                            else if (type.equals(Short.class))
                                field.set(this, newList((Class<? extends List<Short>>) field.getType(),
                                        yml.getShortList(path)));
                            else if (type.equals(Boolean.class))
                                field.set(this, newList((Class<? extends List<Boolean>>) field.getType(),
                                        yml.getBooleanList(path)));
                            else if (type.equals(String.class))
                                field.set(this, newList((Class<? extends List<String>>) field.getType(),
                                        yml.getStringList(path)));
                            else
                                throw new IllegalArgumentException(
                                        "Cannot use type " + field.getType().getSimpleName() + "<" //$NON-NLS-2$
                                                + type.toString() + "> for AutoConfiguration");
                        } else if (Set.class.isAssignableFrom(field.getType())) {
                            if (field.getGenericType() == null)
                                throw new IllegalArgumentException(
                                        "Cannot use type set without specifying generic type for AytoConfiguration");

                            Type type = ((ParameterizedType) field.getGenericType())
                                    .getActualTypeArguments()[0];

                            if (type.equals(Integer.class))
                                field.set(this, newSet((Class<? extends Set<Integer>>) field.getType(),
                                        yml.getIntegerList(path)));
                            else if (type.equals(Float.class))
                                field.set(this, newSet((Class<? extends Set<Float>>) field.getType(),
                                        yml.getFloatList(path)));
                            else if (type.equals(Double.class))
                                field.set(this, newSet((Class<? extends Set<Double>>) field.getType(),
                                        yml.getDoubleList(path)));
                            else if (type.equals(Long.class))
                                field.set(this, newSet((Class<? extends Set<Long>>) field.getType(),
                                        yml.getLongList(path)));
                            else if (type.equals(Short.class))
                                field.set(this, newSet((Class<? extends Set<Short>>) field.getType(),
                                        yml.getShortList(path)));
                            else if (type.equals(Boolean.class))
                                field.set(this, newSet((Class<? extends Set<Boolean>>) field.getType(),
                                        yml.getBooleanList(path)));
                            else if (type.equals(String.class))
                                field.set(this, newSet((Class<? extends Set<String>>) field.getType(),
                                        yml.getStringList(path)));
                            else
                                throw new IllegalArgumentException(
                                        "Cannot use type " + field.getType().getSimpleName() + "<" //$NON-NLS-2$
                                                + type.toString() + "> for AutoConfiguration");
                        } else {
                            // Integer
                            if (field.getType().equals(Integer.TYPE))
                                field.setInt(this, yml.getInt(path));

                            // Float
                            else if (field.getType().equals(Float.TYPE))
                                field.setFloat(this, (float) yml.getDouble(path));

                            // Double
                            else if (field.getType().equals(Double.TYPE))
                                field.setDouble(this, yml.getDouble(path));

                            // Long
                            else if (field.getType().equals(Long.TYPE))
                                field.setLong(this, yml.getLong(path));

                            // Short
                            else if (field.getType().equals(Short.TYPE))
                                field.setShort(this, (short) yml.getInt(path));

                            // Boolean
                            else if (field.getType().equals(Boolean.TYPE))
                                field.setBoolean(this, yml.getBoolean(path));

                            // ItemStack
                            else if (field.getType().equals(ItemStack.class))
                                field.set(this, yml.getItemStack(path));

                            // String
                            else if (field.getType().equals(String.class))
                                field.set(this, yml.getString(path));
                            else
                                throw new IllegalArgumentException("Cannot use type "
                                        + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-1$
                        }
                    }
                }

                onPostLoad();
            } else {
                Bukkit.getLogger().log(Level.INFO, "Unable to create file: " + mFile.toString());
            }
        } else {
            Bukkit.getLogger().log(Level.INFO, "Unable to create file: " + mFile.getParentFile().toString());
        }
        return true;
    } catch (IOException | InvalidConfigurationException | IllegalAccessException
            | IllegalArgumentException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.j2free.admin.ReflectionMarshaller.java

/**
 * //from w  ww.  j  av  a 2s.c om
 * @param entity
 * @param parameterMap
 * @param controller
 * @return
 * @throws MarshallingException
 */
public Object marshallIn(Object entity, Map<String, String[]> parameterMap, Controller controller)
        throws MarshallingException {
    Field field;
    Converter converter;
    Method setter;
    String[] newValues;

    log.debug("Marshalling in instance of " + entity.getClass().getSimpleName());

    boolean error = false, success = false, isEntity = false, isCollection = false;

    Class collectionType;
    Class fieldType;

    for (Map.Entry<Field, Converter> ent : instructions.entrySet()) {

        // reset flags
        error = success = isEntity = isCollection = false;

        field = ent.getKey();
        converter = ent.getValue();

        if (converter.isReadOnly()) {
            log.debug("Skipping read-only field " + field.getName());
            continue;
        }

        newValues = parameterMap.get(field.getName());

        if (newValues == null || newValues.length == 0) {
            log.debug("Skipping field " + field.getName() + ", no new value set.");
            continue;
        }

        isEntity = converter.isEntity();
        isCollection = converter.isCollection();

        fieldType = field.getType();
        collectionType = isCollection ? converter.getType() : null;

        log.debug("Marshalling in field " + field.getName());

        // try to get the original value
        try {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            if (field.isAccessible()) {
                log.debug(field.getName() + " is accessible");
                if (!isEntity && !isCollection) {

                    log.debug("!isEntity && !isCollection");

                    // if it's an array, it needs special treatment
                    if (fieldType.isArray()) {
                        log.debug(field.getName() + " is an Array");

                        Class arrayType = fieldType.getComponentType();

                        // If we can, just convert with a cast()
                        if (arrayType.isAssignableFrom(String.class)) {
                            log.debug(arrayType.getName() + " is assignable from String.class");

                            Object[] newArray = new Object[newValues.length];
                            for (int i = 0; i < newValues.length; i++) {
                                newArray[i] = arrayType.cast(newValues[i]);
                            }
                            field.set(entity, newArray);

                        } else {

                            if (isInteger(fieldType)) {

                                Integer[] newArray = new Integer[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Integer.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isFloat(fieldType)) {

                                Float[] newArray = new Float[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Float.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isDouble(fieldType)) {

                                Double[] newArray = new Double[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Double.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isShort(fieldType)) {

                                Short[] newArray = new Short[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Short.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isChar(fieldType)) {

                                field.set(entity, ServletUtils.join(newValues, "").toCharArray());

                            } else if (isLong(fieldType)) {

                                Long[] newArray = new Long[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Long.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isBoolean(fieldType)) {

                                Boolean[] newArray = new Boolean[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Boolean.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isByte(fieldType)) {

                                Byte[] newArray = new Byte[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Byte.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else {
                                throw new MarshallingException(
                                        "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = "
                                                + field.getName());
                            }
                        }

                    } else {

                        // Check out if it's assignable via a straight cast,
                        // that could save time
                        if (fieldType.isAssignableFrom(String.class)) {
                            log.debug(fieldType.getName() + " is assignable from String.class");
                            // this might throw an exception, but we're going
                            // to ignore it because there are other ways of
                            // setting the value if this doesn't work.
                            try {
                                field.set(entity, fieldType.cast(newValues[0]));
                                log.debug("Assigned via cast");
                            } catch (Exception e) {
                                log.debug("Error setting field by cast", e);
                            }
                            success = true;
                        }

                        // if it wasn't assignable via a straight cast, try
                        // working around it.
                        if (!success) {
                            if (isInteger(fieldType) && !newValues[0].equals("")) {
                                field.setInt(entity, Integer.valueOf(newValues[0]));
                            } else if (isFloat(fieldType) && !newValues[0].equals("")) {
                                field.setFloat(entity, Float.valueOf(newValues[0]));
                            } else if (isDouble(fieldType) && !newValues[0].equals("")) {
                                field.setDouble(entity, Double.valueOf(newValues[0]));
                            } else if (isShort(fieldType) && !newValues[0].equals("")) {
                                field.setShort(entity, Short.valueOf(newValues[0]));
                            } else if (isChar(fieldType)) {
                                field.setChar(entity, newValues[0].charAt(0));
                            } else if (isLong(fieldType) && !newValues[0].equals("")) {
                                field.setLong(entity, Long.valueOf(newValues[0]));
                            } else if (isBoolean(fieldType) && !newValues[0].equals("")) {
                                field.setBoolean(entity, Boolean.valueOf(newValues[0]));
                            } else if (isByte(fieldType) && !newValues[0].equals("")) {
                                field.setByte(entity, Byte.valueOf(newValues[0]));
                            } else if (isDate(fieldType)) {
                                if (newValues[0].equals("")) {
                                    field.set(entity, null);
                                } else {
                                    try {
                                        field.set(entity, asDate(newValues[0]));
                                    } catch (ParseException pe) {
                                        log.warn("Error parsing date: " + newValues[0], pe);
                                    }
                                }
                            } else if (!newValues[0].equals("")) {
                                log.debug("Not sure how to set " + field.getName() + " of type "
                                        + fieldType.getName() + ", attemping cast.");
                                field.set(entity, fieldType.cast(newValues[0]));
                            } else if (newValues[0].equals("")) {
                                log.debug("Skipping field " + field.getName()
                                        + ", empty string value passed in.");
                            }
                        }
                    }

                } else if (isEntity && !isCollection) {

                    log.debug("isEntity && !isCollection");

                    ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType);
                    field.set(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0])));

                } else if (!isEntity && isCollection) {

                    log.debug("!isEntity && isCollection");

                    throw new MarshallingException("Error, collections of non-entities are not yet supported.");

                } else if (isEntity && isCollection) {

                    log.debug("isEntity && isCollection");

                    // for now, this is going to expect the parameter to be a
                    // comma-delimited string of entity ids
                    String[] idsString = newValues[0].toString().split(",");
                    Collection collection = (Collection) field.get(entity);

                    log.debug("newValues.length = " + newValues.length);
                    log.debug("newValues[0] = " + newValues[0]);
                    log.debug("idsString.length = " + idsString.length);

                    if (collection == null)
                        collection = new LinkedList();

                    collection.clear();

                    if (idsString.length > 0) {

                        ReflectionMarshaller collectionMarshaller = ReflectionMarshaller
                                .getForClass(collectionType);

                        log.debug("CollectionType = " + collectionType.getName());

                        for (String idString : idsString) {
                            if (idString.equals("")) {
                                log.debug("Skipping empty idString");
                                continue;
                            }
                            collection.add(
                                    controller.proxy(collectionType, collectionMarshaller.asIdType(idString)));
                        }

                    }

                    field.set(entity, collection);
                }
            } else {
                error = true;
            }
        } catch (IllegalAccessException iae) {
            log.error("Unable to set " + field.getName() + " directly.", iae);
            error = true;
        } catch (ClassCastException cce) {
            log.error("Error setting " + field.getName() + ".", cce);
            error = true;
        }

        // if we hit an error getting it directly, try via the getter
        if (error) {
            error = false;
            try {
                setter = converter.getSetter();
                if (setter != null) {
                    if (!setter.isAccessible()) {
                        setter.setAccessible(true);
                    }
                    if (setter.isAccessible()) {
                        if (!isEntity && !isCollection) {

                            // if it's an array, it needs special treatment
                            if (fieldType.isArray()) {
                                log.debug(field.getName() + " is an Array");

                                Class arrayType = fieldType.getComponentType();

                                // If we can, just convert with a cast()
                                if (arrayType.isAssignableFrom(String.class)) {
                                    log.debug(arrayType.getName() + " is assignable from String.class");

                                    Object[] newArray = new Object[newValues.length];
                                    for (int i = 0; i < newValues.length; i++) {
                                        newArray[i] = arrayType.cast(newValues[i]);
                                    }
                                    setter.invoke(entity, newArray);

                                } else {

                                    if (isInteger(fieldType)) {

                                        Integer[] newArray = new Integer[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Integer.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isFloat(fieldType)) {

                                        Float[] newArray = new Float[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Float.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isDouble(fieldType)) {

                                        Double[] newArray = new Double[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Double.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isShort(fieldType)) {

                                        Short[] newArray = new Short[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Short.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isChar(fieldType)) {

                                        setter.invoke(entity, ServletUtils.join(newValues, "").toCharArray());

                                    } else if (isLong(fieldType)) {

                                        Long[] newArray = new Long[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Long.valueOf(newValues[i]);
                                        }
                                        field.set(entity, (Object[]) newArray);

                                    } else if (isBoolean(fieldType)) {

                                        Boolean[] newArray = new Boolean[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Boolean.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isByte(fieldType)) {

                                        Byte[] newArray = new Byte[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Byte.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else {
                                        throw new MarshallingException(
                                                "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = "
                                                        + field.getName());
                                    }
                                }

                            } else {
                                // Check out if it's assignable via a straight cast,
                                // that could save time
                                if (fieldType.isAssignableFrom(String.class)) {
                                    log.debug(fieldType.getName() + " is assignable from String.class");
                                    // this might throw an exception, but we're going
                                    // to ignore it because there are other ways of
                                    // setting the value if this doesn't work.
                                    try {
                                        setter.invoke(entity, fieldType.cast(newValues[0]));
                                    } catch (Exception e) {
                                        log.debug("Error setting field by cast", e);
                                    }
                                    success = true;
                                }

                                // if it wasn't assignable via a straight cast, try
                                // working around it.
                                if (!success) {
                                    if (isInteger(fieldType)) {
                                        setter.invoke(entity, Integer.valueOf(newValues[0]));
                                    } else if (isFloat(fieldType)) {
                                        setter.invoke(entity, Float.valueOf(newValues[0]));
                                    } else if (isDouble(fieldType)) {
                                        setter.invoke(entity, Double.valueOf(newValues[0]));
                                    } else if (isShort(fieldType)) {
                                        setter.invoke(entity, Short.valueOf(newValues[0]));
                                    } else if (isChar(fieldType)) {
                                        setter.invoke(entity, newValues[0].charAt(0));
                                    } else if (isLong(fieldType)) {
                                        setter.invoke(entity, Long.valueOf(newValues[0]));
                                    } else if (isBoolean(fieldType)) {
                                        setter.invoke(entity, Boolean.valueOf(newValues[0]));
                                    } else if (isByte(fieldType)) {
                                        setter.invoke(entity, Byte.valueOf(newValues[0]));
                                    } else if (isDate(fieldType)) {
                                        if (newValues[0].equals("")) {
                                            field.set(entity, null);
                                        } else {
                                            try {
                                                setter.invoke(entity, asDate(newValues[0]));
                                            } catch (ParseException pe) {
                                                log.warn("Error parsing date: " + newValues[0], pe);
                                            }
                                        }
                                    } else {
                                        log.debug("Not sure how to set " + field.getName() + " of type "
                                                + fieldType.getName() + ", attemping cast.");
                                        setter.invoke(entity, fieldType.cast(newValues[0]));
                                    }
                                }
                            }

                        } else if (isEntity && !isCollection) {

                            ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType);
                            setter.invoke(entity,
                                    controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0])));

                        } else if (!isEntity && isCollection) {

                            throw new MarshallingException(
                                    "Error, collections of non-entities are not yet supported.");

                        } else if (isEntity && isCollection) {
                            // for now, this is going to expect the parameter to be a
                            // comma-delimited string of entity ids
                            String[] idsString = newValues[0].toString().split(",");
                            Collection collection = (Collection) field.get(entity);

                            if (collection == null)
                                collection = new LinkedList();

                            if (idsString.length == 0 && collection.isEmpty())
                                continue;

                            collection.clear();

                            if (idsString.length > 0) {

                                ReflectionMarshaller collectionMarshaller = ReflectionMarshaller
                                        .getForClass(collectionType);

                                for (String idString : idsString) {
                                    if (idString.equals("")) {
                                        log.debug("Skipping empty idString");
                                        continue;
                                    }
                                    collection.add(controller.proxy(collectionType,
                                            collectionMarshaller.asIdType(idString)));
                                }
                            }

                            setter.invoke(entity, collection);
                        }
                    } else {
                        error = true;
                    }
                } else {
                    error = true;
                }
            } catch (IllegalAccessException iae) {
                log.error("Error accessing setter", iae);
                error = true;
            } catch (InvocationTargetException ite) {
                log.error("Error invoking setter", ite);
                error = true;
            }
        }

        if (error) {
            throw new MarshallingException("Unable to marshall in field " + field.getName() + ".");
        }
    }
    return entity;
}