Example usage for java.lang.reflect Field setShort

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public void setShort(Object obj, short s) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

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

Usage

From source file:com.vk.sdkweb.api.model.ParseUtils.java

/**
 * Parses object with follow rules:/*from  w w  w.  ja v a  2s  .  c  om*/
 *
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java

/**
 * ???????/*w  w  w.  jav  a 2s.c  o  m*/
 * @param klass   ???klass?Class
 * @param filepath   ?
 * @param sizeThreshold   ??
 * @param isFileNameBaseTime   ????
 * @return bean
 */
public static <T> Object upload(HttpServletRequest request, Class<T> klass, String filepath, int sizeThreshold,
        boolean isFileNameBaseTime) throws Exception {
    FileItemFactory fileItemFactory = null;
    if (sizeThreshold > 0) {
        File repository = new File(filepath);
        fileItemFactory = new DiskFileItemFactory(sizeThreshold, repository);
    } else {
        fileItemFactory = new DiskFileItemFactory();
    }
    ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
    ServletRequestContext requestContext = new ServletRequestContext(request);
    T bean = null;
    if (klass != null) {
        bean = klass.newInstance();
    }
    // 
    if (ServletFileUpload.isMultipartContent(requestContext)) {
        File parentDir = new File(filepath);

        List<FileItem> fileItemList = upload.parseRequest(requestContext);
        for (int i = 0; i < fileItemList.size(); i++) {
            FileItem item = fileItemList.get(i);
            // ??
            if (item.isFormField()) {
                String paramName = item.getFieldName();
                String paramValue = item.getString("UTF-8");
                log.info("?" + paramName + "=" + paramValue);
                request.setAttribute(paramName, paramValue);
                // ?bean
                if (klass != null) {
                    Field field = null;
                    try {
                        field = klass.getDeclaredField(paramName);

                        if (field != null) {
                            field.setAccessible(true);
                            Class type = field.getType();
                            if (type == Integer.TYPE) {
                                field.setInt(bean, Integer.valueOf(paramValue));
                            } else if (type == Double.TYPE) {
                                field.setDouble(bean, Double.valueOf(paramValue));
                            } else if (type == Float.TYPE) {
                                field.setFloat(bean, Float.valueOf(paramValue));
                            } else if (type == Boolean.TYPE) {
                                field.setBoolean(bean, Boolean.valueOf(paramValue));
                            } else if (type == Character.TYPE) {
                                field.setChar(bean, paramValue.charAt(0));
                            } else if (type == Long.TYPE) {
                                field.setLong(bean, Long.valueOf(paramValue));
                            } else if (type == Short.TYPE) {
                                field.setShort(bean, Short.valueOf(paramValue));
                            } else {
                                field.set(bean, paramValue);
                            }
                        }
                    } catch (NoSuchFieldException e) {
                        log.info("" + klass.getName() + "?" + paramName);
                    }
                }
            }
            // 
            else {
                // <input type='file' name='xxx'> xxx
                String paramName = item.getFieldName();
                log.info("?" + item.getSize());

                if (sizeThreshold > 0) {
                    if (item.getSize() > sizeThreshold)
                        continue;
                }
                String clientFileName = item.getName();
                int index = -1;
                // ?IE?
                if ((index = clientFileName.lastIndexOf("\\")) != -1) {
                    clientFileName = clientFileName.substring(index + 1);
                }
                if (clientFileName == null || "".equals(clientFileName))
                    continue;

                String filename = null;
                log.info("" + paramName + "\t??" + clientFileName);
                if (isFileNameBaseTime) {
                    filename = buildFileName(clientFileName);
                } else
                    filename = clientFileName;

                request.setAttribute(paramName, filename);

                // ?bean
                if (klass != null) {
                    Field field = null;
                    try {
                        field = klass.getDeclaredField(paramName);
                        if (field != null) {
                            field.setAccessible(true);
                            field.set(bean, filename);
                        }
                    } catch (NoSuchFieldException e) {
                        log.info("" + klass.getName() + "?  " + paramName);
                        continue;
                    }
                }

                if (!parentDir.exists()) {
                    parentDir.mkdirs();
                }

                File newfile = new File(parentDir, filename);
                item.write(newfile);
                String serverPath = newfile.getPath();
                log.info("?" + serverPath);
            }
        }
    }
    return bean;
}

From source file:org.sonar.api.checks.AnnotationCheckFactory.java

private void configureField(Object check, Field field, String value) {
    try {/* w ww. j  av  a 2s .  c om*/
        field.setAccessible(true);

        if (field.getType().equals(String.class)) {
            field.set(check, value);

        } else if ("int".equals(field.getType().getSimpleName())) {
            field.setInt(check, Integer.parseInt(value));

        } else if ("short".equals(field.getType().getSimpleName())) {
            field.setShort(check, Short.parseShort(value));

        } else if ("long".equals(field.getType().getSimpleName())) {
            field.setLong(check, Long.parseLong(value));

        } else if ("double".equals(field.getType().getSimpleName())) {
            field.setDouble(check, Double.parseDouble(value));

        } else if ("boolean".equals(field.getType().getSimpleName())) {
            field.setBoolean(check, Boolean.parseBoolean(value));

        } else if ("byte".equals(field.getType().getSimpleName())) {
            field.setByte(check, Byte.parseByte(value));

        } else if (field.getType().equals(Integer.class)) {
            field.set(check, Integer.parseInt(value));

        } else if (field.getType().equals(Long.class)) {
            field.set(check, Long.parseLong(value));

        } else if (field.getType().equals(Double.class)) {
            field.set(check, Double.parseDouble(value));

        } else if (field.getType().equals(Boolean.class)) {
            field.set(check, Boolean.parseBoolean(value));

        } else {
            throw new SonarException(
                    "The type of the field " + field + " is not supported: " + field.getType());
        }
    } catch (IllegalAccessException e) {
        throw new SonarException(
                "Can not set the value of the field " + field + " in the class: " + check.getClass().getName(),
                e);
    }
}

From source file:org.sonar.api.checks.checkers.AnnotationCheckerFactory.java

private void configureField(Object checker, Field field, Map.Entry<String, String> parameter)
        throws IllegalAccessException {
    field.setAccessible(true);// ww w .ja  v  a 2  s .  c  o m

    if (field.getType().equals(String.class)) {
        field.set(checker, parameter.getValue());

    } else if (field.getType().getSimpleName().equals("int")) {
        field.setInt(checker, Integer.parseInt(parameter.getValue()));

    } else if (field.getType().getSimpleName().equals("short")) {
        field.setShort(checker, Short.parseShort(parameter.getValue()));

    } else if (field.getType().getSimpleName().equals("long")) {
        field.setLong(checker, Long.parseLong(parameter.getValue()));

    } else if (field.getType().getSimpleName().equals("double")) {
        field.setDouble(checker, Double.parseDouble(parameter.getValue()));

    } else if (field.getType().getSimpleName().equals("boolean")) {
        field.setBoolean(checker, Boolean.parseBoolean(parameter.getValue()));

    } else if (field.getType().getSimpleName().equals("byte")) {
        field.setByte(checker, Byte.parseByte(parameter.getValue()));

    } else if (field.getType().equals(Integer.class)) {
        field.set(checker, new Integer(Integer.parseInt(parameter.getValue())));

    } else if (field.getType().equals(Long.class)) {
        field.set(checker, new Long(Long.parseLong(parameter.getValue())));

    } else if (field.getType().equals(Double.class)) {
        field.set(checker, new Double(Double.parseDouble(parameter.getValue())));

    } else if (field.getType().equals(Boolean.class)) {
        field.set(checker, Boolean.valueOf(Boolean.parseBoolean(parameter.getValue())));

    } else {
        throw new UnvalidCheckerException(
                "The type of the field " + field + " is not supported: " + field.getType());
    }
}

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   w ww  .ja va  2  s. co  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: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   w  ww.  j  a va 2 s .c o  m*/
        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:cn.edu.zafu.corepage.base.BaseActivity.java

/**
 * ???/*  ww  w.  j a v a  2 s . c om*/
 *
 * @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.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  w ww .  j  av 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:com.qmetry.qaf.automation.data.BaseDataBean.java

protected void setField(Field field, String val) {
    try {/*from  ww w.  j a  v a 2 s  . co m*/
        // 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.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 ww. j  a v a 2  s  .  co  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);

            }
        }

    }

}