Example usage for java.lang.reflect Field setFloat

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public void setFloat(Object obj, float f) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

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

Usage

From source file:android.reflect.ClazzLoader.java

/**
 * ????/*  www.  j a v  a  2 s.c  om*/
 */
public static <O, V> void setFieldValue(O o, Field field, V v) {
    if (field != null) {
        try {
            field.setAccessible(true);

            if (v == null) {
                field.set(o, null);
            } else {
                Class<?> vType = v.getClass();
                if (vType == Integer.TYPE) {
                    field.setInt(o, (Integer) v);
                } else if (vType == Long.TYPE) {
                    field.setLong(o, (Long) v);
                } else if (vType == Boolean.TYPE) {
                    field.setBoolean(o, (Boolean) v);
                } else if (vType == Float.TYPE) {
                    field.setFloat(o, (Float) v);
                } else if (vType == Short.TYPE) {
                    field.setShort(o, (Short) v);
                } else if (vType == Byte.TYPE) {
                    field.setByte(o, (Byte) v);
                } else if (vType == Double.TYPE) {
                    field.setDouble(o, (Double) v);
                } else if (vType == Character.TYPE) {
                    field.setChar(o, (Character) v);
                } else {
                    field.set(o, v);
                }
            }
        } catch (Throwable t) {
            Log.e(TAG, t);
        }
    }
}

From source file:me.henrytao.observableorm.orm.ObservableModel.java

public T deserialize(Map<String, Object> map) throws IllegalAccessException {
    Field[] fields = getDeclaredFields();
    for (Field f : fields) {
        if (!f.isAnnotationPresent(Column.class)) {
            continue;
        }/*from www. ja v a2  s  .  c  om*/
        Column column = f.getAnnotation(Column.class);
        if (!column.deserialize()) {
            continue;
        }
        f.setAccessible(true);
        String name = column.name();
        Object value = map.get(name);
        Class type = f.getType();
        Deserializer deserializer = deserializerMap.get(type);
        if (deserializer != null) {
            f.set(this, deserializer.deserialize(value));
        } else if (boolean.class.isAssignableFrom(type)) {
            f.setBoolean(this, value == null ? false : (Boolean) value);
        } else if (double.class.isAssignableFrom(type)) {
            f.setDouble(this, value == null ? 0.0 : (Double) value);
        } else if (float.class.isAssignableFrom(type)) {
            f.setFloat(this, value == null ? 0f : (Float) value);
        } else if (int.class.isAssignableFrom(type)) {
            f.setInt(this, value == null ? 0 : (int) value);
        } else if (short.class.isAssignableFrom(type)) {
            f.setShort(this, value == null ? 0 : (short) value);
        } else if (byte.class.isAssignableFrom(type)) {
            f.setByte(this, value == null ? 0 : (byte) value);
        } else if (String.class.isAssignableFrom(type)) {
            f.set(this, value);
        } else if (JSONObject.class.isAssignableFrom(type)) {
            // todo: nested object should be another model
        }
    }
    return (T) this;
}

From source file:cern.c2mon.shared.common.datatag.address.impl.HardwareAddressImpl.java

/**
 * Create a HardwareAddress object from its XML representation.
 *
 * @param pElement DOM element containing the XML representation of a HardwareAddress object, as created by the
 *                 toConfigXML() method.
 * @throws RuntimeException if unable to instantiate the Hardware address
 * @see cern.c2mon.shared.common.datatag.address.HardwareAddress#toConfigXML()
 *///from ww w.  j av a2s. c  o m
public final synchronized HardwareAddress fromConfigXML(Element pElement) {
    Class hwAddressClass = null;
    HardwareAddressImpl hwAddress = null;

    try {
        hwAddressClass = Class.forName(pElement.getAttribute("class"));
        hwAddress = (HardwareAddressImpl) hwAddressClass.newInstance();
    } catch (ClassNotFoundException cnfe) {
        cnfe.printStackTrace();
        throw new RuntimeException("Exception caught when instantiating a hardware address from XML", cnfe);
    } catch (IllegalAccessException iae) {
        iae.printStackTrace();
        throw new RuntimeException("Exception caught when instantiating a hardware address from XML", iae);
    } catch (InstantiationException ie) {
        ie.printStackTrace();
        throw new RuntimeException("Exception caught when instantiating a hardware address from XML", ie);
    }

    NodeList fields = pElement.getChildNodes();
    Node fieldNode = null;
    int fieldsCount = fields.getLength();
    String fieldName;
    String fieldValueString;
    String fieldTypeName = "";

    for (int i = 0; i < fieldsCount; i++) {
        fieldNode = fields.item(i);
        if (fieldNode.getNodeType() == Node.ELEMENT_NODE) {
            fieldName = fieldNode.getNodeName();

            if (fieldNode.getFirstChild() != null) {
                fieldValueString = fieldNode.getFirstChild().getNodeValue();
            } else {
                fieldValueString = "";
            }
            try {
                Field field = hwAddressClass.getDeclaredField(decodeFieldName(fieldName));
                fieldTypeName = field.getType().getName();

                if (fieldTypeName.equals("short")) {
                    field.setShort(hwAddress, Short.parseShort(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Short")) {
                    field.set(hwAddress, new Integer(Integer.parseInt(fieldValueString)));
                } else if (fieldTypeName.equals("int")) {
                    field.setInt(hwAddress, Integer.parseInt(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Integer")) {
                    field.set(hwAddress, new Integer(Integer.parseInt(fieldValueString)));
                } else if (fieldTypeName.equals("float")) {
                    field.setFloat(hwAddress, Float.parseFloat(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Float")) {
                    field.set(hwAddress, new Float(Float.parseFloat(fieldValueString)));
                } else if (fieldTypeName.equals("double")) {
                    field.setDouble(hwAddress, Double.parseDouble(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Double")) {
                    field.set(hwAddress, new Double(Double.parseDouble(fieldValueString)));
                } else if (fieldTypeName.equals("long")) {
                    field.setLong(hwAddress, Long.parseLong(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Long")) {
                    field.set(hwAddress, new Long(Long.parseLong(fieldValueString)));
                } else if (fieldTypeName.equals("byte")) {
                    field.setByte(hwAddress, Byte.parseByte(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Byte")) {
                    field.set(hwAddress, new Byte(Byte.parseByte(fieldValueString)));
                } else if (fieldTypeName.equals("char")) {
                    field.setChar(hwAddress, fieldValueString.charAt(0));
                } else if (fieldTypeName.equals("java.lang.Character")) {
                    field.set(hwAddress, new Character(fieldValueString.charAt(0)));
                } else if (fieldTypeName.equals("boolean")) {
                    field.setBoolean(hwAddress, Boolean.getBoolean(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Boolean")) {
                    field.set(hwAddress, new Boolean(Boolean.getBoolean(fieldValueString)));
                } else if (fieldTypeName.equals("java.util.HashMap")) {
                    field.set(hwAddress, SimpleXMLParser.domNodeToMap(fieldNode));
                } else if (field.getType().isEnum()) {
                    Object[] enumConstants = field.getType().getEnumConstants();
                    for (Object enumConstant : enumConstants) {
                        if (enumConstant.toString().equals(fieldValueString)) {
                            field.set(hwAddress, enumConstant);
                        }
                    }
                } else {
                    field.set(hwAddress, fieldValueString);
                }
            } catch (NoSuchFieldException nsfe) {
                String errorMsg = "fromConfigXML(...) - Error occured while parsing XML <HardwareAddress> tag. "
                        + "The following variable does not exist in " + hwAddressClass.toString() + ": \""
                        + decodeFieldName(fieldName) + "\"";
                log.error(errorMsg);
                throw new IllegalArgumentException(errorMsg);
            } catch (IllegalAccessException iae) {
                iae.printStackTrace();
                throw new RuntimeException(iae);
            } catch (NumberFormatException npe) {
                String errorMsg = "fromConfigXML(...) - Error occured while parsing XML <HardwareAddress> tag. Field \""
                        + fieldName + "\" shall not be empty since we expect a \"" + fieldTypeName
                        + "\" value. Please correct the XML configuration for " + hwAddressClass.toString();
                log.error(errorMsg);
                throw new IllegalArgumentException(errorMsg);
            }
        }
    }
    return hwAddress;
}

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

protected void setField(Field field, String val) {
    try {//w  w w  . j  a  v  a2s .  com
        // deal with IllegalAccessException
        field.setAccessible(true);
        if (field.getType() == String.class) {
            field.set(this, val);
        } else {
            Method setter = null;
            try {
                setter = this.getClass().getMethod("set" + StringUtil.getTitleCase(field.getName()),
                        String.class);
            } catch (Exception e) {

            }
            if (null != setter) {
                setter.setAccessible(true);
                setter.invoke(this, val);
            } else if (field.getType() == Integer.TYPE) {
                field.setInt(this, Integer.parseInt(val));
            } else if (field.getType() == Float.TYPE) {
                field.setFloat(this, Float.parseFloat(val));

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

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

            } else if (field.getType() == Boolean.TYPE) {
                Boolean bval = StringUtils.isBlank(val) ? null
                        : NumberUtils.isNumber(val) ? (Integer.parseInt(val) != 0)
                                : Boolean.parseBoolean(val) || val.equalsIgnoreCase("T")
                                        || val.equalsIgnoreCase("Y") || val.equalsIgnoreCase("YES");

                field.setBoolean(this, bval);

            } else if (field.getType() == Short.TYPE) {
                field.setShort(this, Short.parseShort(val));
            } else if (field.getType() == Date.class) {
                Date dVal = null;
                try {
                    dVal =

                            StringUtils.isBlank(val) ? null
                                    : NumberUtils.isNumber(val) ? DateUtil.getDate(Integer.parseInt(val))
                                            : DateUtil.parseDate(val, "MM/dd/yyyy");
                } catch (ParseException e) {
                    logger.error("Expected date in MM/dd/yyyy format.", e);
                }
                field.set(this, dVal);
            }
        }
    } 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 invoke setter for " + field.getName(), e);
    }

}

From source file:com.sikulix.core.SX.java

private static void setOptions(PropertiesConfiguration someOptions) {
    if (isNull(someOptions) || someOptions.size() == 0) {
        return;/* w  w  w.  j  a v  a2s . c om*/
    }
    Iterator<String> allKeys = someOptions.getKeys();
    List<String> sxSettings = new ArrayList<>();
    while (allKeys.hasNext()) {
        String key = allKeys.next();
        if (key.startsWith("Settings.")) {
            sxSettings.add(key);
            continue;
        }
        trace("!setOptions: %s = %s", key, someOptions.getProperty(key));
    }
    if (sxSettings.size() > 0) {
        Class cClass = null;
        try {
            cClass = Class.forName("org.sikuli.basics.Settings");
        } catch (ClassNotFoundException e) {
            error("!setOptions: %s", cClass);
        }
        if (!isNull(cClass)) {
            for (String sKey : sxSettings) {
                String sAttr = sKey.substring("Settings.".length());
                Field cField = null;
                Class ccField = null;
                try {
                    cField = cClass.getField(sAttr);
                    ccField = cField.getType();
                    if (ccField.getName() == "boolean") {
                        cField.setBoolean(null, someOptions.getBoolean(sKey));
                    } else if (ccField.getName() == "int") {
                        cField.setInt(null, someOptions.getInt(sKey));
                    } else if (ccField.getName() == "float") {
                        cField.setFloat(null, someOptions.getFloat(sKey));
                    } else if (ccField.getName() == "double") {
                        cField.setDouble(null, someOptions.getDouble(sKey));
                    } else if (ccField.getName() == "String") {
                        cField.set(null, someOptions.getString(sKey));
                    }
                    trace("!setOptions: %s = %s", sAttr, someOptions.getProperty(sKey));
                    someOptions.clearProperty(sKey);
                } catch (Exception ex) {
                    error("!setOptions: %s = %s", sKey, sxOptions.getProperty(sKey));
                }
            }
        }
    }
}

From source file:com.nonninz.robomodel.RoboModel.java

private void loadField(Field field, Cursor query) throws DatabaseNotUpToDateException {
    final Class<?> type = field.getType();
    final boolean wasAccessible = field.isAccessible();
    final int columnIndex = query.getColumnIndex(field.getName());
    field.setAccessible(true);//from  www  .jav  a  2 s. co  m

    /*
     * TODO: There is the potential of a problem here:
     * What happens if the developer changes the type of a field between releases?
     *
     * If he saves first, then the column type will be changed (In the future).
     * If he loads first, we don't know if an Exception will be thrown if the
     * types are incompatible, because it's undocumented in the Cursor documentation.
     */

    try {
        if (type == String.class) {
            field.set(this, query.getString(columnIndex));
        } else if (type == Boolean.TYPE) {
            final boolean value = query.getInt(columnIndex) == 1 ? true : false;
            field.setBoolean(this, value);
        } else if (type == Byte.TYPE) {
            field.setByte(this, (byte) query.getShort(columnIndex));
        } else if (type == Double.TYPE) {
            field.setDouble(this, query.getDouble(columnIndex));
        } else if (type == Float.TYPE) {
            field.setFloat(this, query.getFloat(columnIndex));
        } else if (type == Integer.TYPE) {
            field.setInt(this, query.getInt(columnIndex));
        } else if (type == Long.TYPE) {
            field.setLong(this, query.getLong(columnIndex));
        } else if (type == Short.TYPE) {
            field.setShort(this, query.getShort(columnIndex));
        } else if (type.isEnum()) {
            final String string = query.getString(columnIndex);
            if (string != null && string.length() > 0) {
                final Object[] constants = type.getEnumConstants();
                final Method method = type.getMethod("valueOf", Class.class, String.class);
                final Object value = method.invoke(constants[0], type, string);
                field.set(this, value);
            }
        } else {
            // Try to de-json it (db column must be of type text)
            try {
                final Object value = mMapper.readValue(query.getString(columnIndex), field.getType());
                field.set(this, value);
            } catch (final Exception e) {
                final String msg = String.format("Type %s is not supported for field %s", type,
                        field.getName());
                Ln.w(e, msg);
                throw new IllegalArgumentException(msg);
            }
        }
    } catch (final IllegalAccessException e) {
        final String msg = String.format("Field %s is not accessible", type, field.getName());
        throw new IllegalArgumentException(msg);
    } catch (final NoSuchMethodException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (final InvocationTargetException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        // This is when there is no column in db, but there is in the model
        throw new DatabaseNotUpToDateException(e);
    } finally {
        field.setAccessible(wasAccessible);
    }
}

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

/**
 * set the field value of an object/*  www  . j a v  a  2 s .co  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:cn.edu.zafu.corepage.base.BaseActivity.java

/**
 * ???// www.  j a  v  a2s.com
 *
 * @param savedInstanceState Bundle
 */
private void loadActivitySavedData(Bundle savedInstanceState) {
    Field[] fields = this.getClass().getDeclaredFields();
    Field.setAccessible(fields, true);
    Annotation[] ans;
    for (Field f : fields) {
        ans = f.getDeclaredAnnotations();
        for (Annotation an : ans) {
            if (an instanceof SaveWithActivity) {
                try {
                    String fieldName = f.getName();
                    @SuppressWarnings("rawtypes")
                    Class cls = f.getType();
                    if (cls == int.class || cls == Integer.class) {
                        f.setInt(this, savedInstanceState.getInt(fieldName));
                    } else if (String.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getString(fieldName));
                    } else if (Serializable.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getSerializable(fieldName));
                    } else if (cls == long.class || cls == Long.class) {
                        f.setLong(this, savedInstanceState.getLong(fieldName));
                    } else if (cls == short.class || cls == Short.class) {
                        f.setShort(this, savedInstanceState.getShort(fieldName));
                    } else if (cls == boolean.class || cls == Boolean.class) {
                        f.setBoolean(this, savedInstanceState.getBoolean(fieldName));
                    } else if (cls == byte.class || cls == Byte.class) {
                        f.setByte(this, savedInstanceState.getByte(fieldName));
                    } else if (cls == char.class || cls == Character.class) {
                        f.setChar(this, savedInstanceState.getChar(fieldName));
                    } else if (CharSequence.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getCharSequence(fieldName));
                    } else if (cls == float.class || cls == Float.class) {
                        f.setFloat(this, savedInstanceState.getFloat(fieldName));
                    } else if (cls == double.class || cls == Double.class) {
                        f.setDouble(this, savedInstanceState.getDouble(fieldName));
                    } else if (String[].class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getStringArray(fieldName));
                    } else if (Parcelable.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getParcelable(fieldName));
                    } else if (Bundle.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getBundle(fieldName));
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:com.dngames.mobilewebcam.PhotoSettings.java

@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    if (key == "cam_refresh") {
        int new_refresh = getEditInt(mContext, prefs, "cam_refresh", 60);
        String msg = "Camera refresh set to " + new_refresh + " seconds!";
        if (MobileWebCam.gIsRunning) {
            if (!mNoToasts && new_refresh != mRefreshDuration) {
                try {
                    Toast.makeText(mContext.getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                } catch (RuntimeException e) {
                    e.printStackTrace();
                }/*from  ww w.j  a  va  2 s . c  o m*/
            }
        } else if (new_refresh != mRefreshDuration) {
            MobileWebCam.LogI(msg);
        }
    }

    // get all preferences
    for (Field f : getClass().getFields()) {
        {
            BooleanPref bp = f.getAnnotation(BooleanPref.class);
            if (bp != null) {
                try {
                    f.setBoolean(this, prefs.getBoolean(bp.key(), bp.val()));
                } catch (Exception e) {
                    Log.e("MobileWebCam", "Exception: " + bp.key() + " <- " + bp.val());
                    e.printStackTrace();
                }
            }
        }
        {
            EditIntPref ip = f.getAnnotation(EditIntPref.class);
            if (ip != null) {
                try {
                    int eval = getEditInt(mContext, prefs, ip.key(), ip.val()) * ip.factor();
                    if (ip.max() != Integer.MAX_VALUE)
                        eval = Math.min(eval, ip.max());
                    if (ip.min() != Integer.MIN_VALUE)
                        eval = Math.max(eval, ip.min());
                    f.setInt(this, eval);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        {
            IntPref ip = f.getAnnotation(IntPref.class);
            if (ip != null) {
                try {
                    int eval = prefs.getInt(ip.key(), ip.val()) * ip.factor();
                    if (ip.max() != Integer.MAX_VALUE)
                        eval = Math.min(eval, ip.max());
                    if (ip.min() != Integer.MIN_VALUE)
                        eval = Math.max(eval, ip.min());
                    f.setInt(this, eval);
                } catch (Exception e) {
                    // handle wrong set class
                    e.printStackTrace();
                    Editor edit = prefs.edit();
                    edit.remove(ip.key());
                    edit.putInt(ip.key(), ip.val());
                    edit.commit();
                    try {
                        f.setInt(this, ip.val());
                    } catch (IllegalArgumentException e1) {
                        e1.printStackTrace();
                    } catch (IllegalAccessException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
        {
            EditFloatPref fp = f.getAnnotation(EditFloatPref.class);
            if (fp != null) {
                try {
                    float eval = getEditFloat(mContext, prefs, fp.key(), fp.val());
                    if (fp.max() != Float.MAX_VALUE)
                        eval = Math.min(eval, fp.max());
                    if (fp.min() != Float.MIN_VALUE)
                        eval = Math.max(eval, fp.min());
                    f.setFloat(this, eval);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        {
            StringPref sp = f.getAnnotation(StringPref.class);
            if (sp != null) {
                try {
                    f.set(this, prefs.getString(sp.key(), getDefaultString(mContext, sp)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    mCustomImageScale = Enum.valueOf(ImageScaleMode.class, prefs.getString("custompicscale", "CROP"));

    mAutoStart = prefs.getBoolean("autostart", false);
    mCameraStartupEnabled = prefs.getBoolean("cam_autostart", true);
    mShutterSound = prefs.getBoolean("shutter", true);
    mDateTimeColor = GetPrefColor(prefs, "datetime_color", "#FFFFFFFF", Color.WHITE);
    mDateTimeShadowColor = GetPrefColor(prefs, "datetime_shadowcolor", "#FF000000", Color.BLACK);
    mDateTimeBackgroundColor = GetPrefColor(prefs, "datetime_backcolor", "#80FF0000",
            Color.argb(0x80, 0xFF, 0x00, 0x00));
    mDateTimeBackgroundLine = prefs.getBoolean("datetime_fillline", true);
    mDateTimeX = prefs.getInt("datetime_x", 98);
    mDateTimeY = prefs.getInt("datetime_y", 98);
    mDateTimeAlign = Paint.Align.valueOf(prefs.getString("datetime_imprintalign", "RIGHT"));

    mDateTimeFontScale = (float) prefs.getInt("datetime_fontsize", 6);

    mTextColor = GetPrefColor(prefs, "text_color", "#FFFFFFFF", Color.WHITE);
    mTextShadowColor = GetPrefColor(prefs, "text_shadowcolor", "#FF000000", Color.BLACK);
    mTextBackgroundColor = GetPrefColor(prefs, "text_backcolor", "#80FF0000",
            Color.argb(0x80, 0xFF, 0x00, 0x00));
    mTextBackgroundLine = prefs.getBoolean("text_fillline", true);
    mTextX = prefs.getInt("text_x", 2);
    mTextY = prefs.getInt("text_y", 2);
    mTextAlign = Paint.Align.valueOf(prefs.getString("text_imprintalign", "LEFT"));
    mTextFontScale = (float) prefs.getInt("infotext_fontsize", 6);
    mTextFontname = prefs.getString("infotext_fonttypeface", "");

    mStatusInfoColor = GetPrefColor(prefs, "statusinfo_color", "#FFFFFFFF", Color.WHITE);
    mStatusInfoShadowColor = GetPrefColor(prefs, "statusinfo_shadowcolor", "#FF000000", Color.BLACK);
    mStatusInfoX = prefs.getInt("statusinfo_x", 2);
    mStatusInfoY = prefs.getInt("statusinfo_y", 98);
    mStatusInfoAlign = Paint.Align.valueOf(prefs.getString("statusinfo_imprintalign", "LEFT"));
    mStatusInfoBackgroundColor = GetPrefColor(prefs, "statusinfo_backcolor", "#00000000", Color.TRANSPARENT);
    mStatusInfoFontScale = (float) prefs.getInt("statusinfo_fontsize", 6);
    mStatusInfoBackgroundLine = prefs.getBoolean("statusinfo_fillline", false);

    mGPSColor = GetPrefColor(prefs, "gps_color", "#FFFFFFFF", Color.WHITE);
    mGPSShadowColor = GetPrefColor(prefs, "gps_shadowcolor", "#FF000000", Color.BLACK);
    mGPSX = prefs.getInt("gps_x", 98);
    mGPSY = prefs.getInt("gps_y", 2);
    mGPSAlign = Paint.Align.valueOf(prefs.getString("gps_imprintalign", "RIGHT"));
    mGPSBackgroundColor = GetPrefColor(prefs, "gps_backcolor", "#00000000", Color.TRANSPARENT);
    mGPSFontScale = (float) prefs.getInt("gps_fontsize", 6);
    mGPSBackgroundLine = prefs.getBoolean("gps_fillline", false);

    mImprintPictureX = prefs.getInt("imprint_picture_x", 0);
    mImprintPictureY = prefs.getInt("imprint_picture_y", 0);

    mNightAutoConfigEnabled = prefs.getBoolean("night_auto_enabled", false);

    mSetNightConfiguration = prefs.getBoolean("cam_nightconfiguration", false);
    // override night camera parameters (read again with postfix)
    getCurrentNightSettings();

    mFilterPicture = false; //***prefs.getBoolean("filter_picture", false);
    mFilterType = getEditInt(mContext, prefs, "filter_sel", 0);

    if (mImprintPicture) {
        if (mImprintPictureURL.length() == 0) {
            // sdcard image
            File path = new File(Environment.getExternalStorageDirectory() + "/MobileWebCam/");
            if (path.exists()) {
                synchronized (gImprintBitmapLock) {
                    if (gImprintBitmap != null)
                        gImprintBitmap.recycle();
                    gImprintBitmap = null;

                    File file = new File(path, "imprint.png");
                    try {
                        FileInputStream in = new FileInputStream(file);
                        gImprintBitmap = BitmapFactory.decodeStream(in);
                        in.close();
                    } catch (IOException e) {
                        Toast.makeText(mContext, "Error: unable to read imprint bitmap " + file.getName() + "!",
                                Toast.LENGTH_SHORT).show();
                        gImprintBitmap = null;
                    } catch (OutOfMemoryError e) {
                        Toast.makeText(mContext, "Error: imprint bitmap " + file.getName() + " too large!",
                                Toast.LENGTH_LONG).show();
                        gImprintBitmap = null;
                    }
                }
            }
        } else {
            DownloadImprintBitmap();
        }

        synchronized (gImprintBitmapLock) {
            if (gImprintBitmap == null) {
                // last resort: resource default
                try {
                    gImprintBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.imprint);
                } catch (OutOfMemoryError e) {
                    Toast.makeText(mContext, "Error: default imprint bitmap too large!", Toast.LENGTH_LONG)
                            .show();
                    gImprintBitmap = null;
                }
            }
        }
    }

    mNoToasts = prefs.getBoolean("no_messages", false);
    mFullWakeLock = prefs.getBoolean("full_wakelock", true);

    switch (getEditInt(mContext, prefs, "camera_mode", 1)) {
    case 0:
        mMode = Mode.MANUAL;
        break;
    case 2:
        mMode = Mode.HIDDEN;
        break;
    case 3:
        mMode = Mode.BACKGROUND;
        break;
    case 1:
    default:
        mMode = Mode.NORMAL;
        break;
    }
}

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.
 * //  w  w  w  . ja  v a  2s. c  om
 * @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);

            }
        }

    }

}