Example usage for java.lang.reflect Field setInt

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public void setInt(Object obj, int i) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the value of a field as an int on the specified object.

Usage

From source file:org.apache.hadoop.hbase.HBaseTestingUtility.java

/**
 * Tasktracker has a bug where changing the hadoop.log.dir system property
 * will not change its internal static LOG_DIR variable.
 *//*  w  ww  .ja v a  2 s  . com*/
private void forceChangeTaskLogDir() {
    Field logDirField;
    try {
        logDirField = TaskLog.class.getDeclaredField("LOG_DIR");
        logDirField.setAccessible(true);

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(logDirField, logDirField.getModifiers() & ~Modifier.FINAL);

        logDirField.set(null, new File(hadoopLogDir, "userlogs"));
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

public AAIService(URL propURL) {
    LOG.info("Entered AAIService.ctor");

    String runtime = System.getProperty("aaiclient.runtime");
    if (runtime != null && runtime.equals("OSGI")) {
        runtimeOSGI = true;/*  ww  w.ja  v  a 2 s  . c  o m*/
    } else {
        runtimeOSGI = false;
    }

    Properties props = null;
    try {
        props = initialize(propURL);
        AAIRequest.setProperties(props, this);

    } catch (Exception exc) {
        LOG.error("AicAAIResource.static", exc);
    }

    executor = new AAIRequestExecutor();

    user_name = props.getProperty(CLIENT_NAME);
    user_password = props.getProperty(CLIENT_PWWD);

    if (user_name == null || user_name.isEmpty()) {
        LOG.debug("Basic user name is not set");
    }
    if (user_password == null || user_password.isEmpty()) {
        LOG.debug("Basic password is not set");
    }

    truststore_path = props.getProperty(TRUSTSTORE_PATH);
    truststore_password = props.getProperty(TRUSTSTORE_PSSWD);
    keystore_path = props.getProperty(KEYSTORE_PATH);
    keystore_password = props.getProperty(KEYSTORE_PSSWD);

    target_uri = props.getProperty(TARGET_URI);
    query_path = props.getProperty(QUERY_PATH);
    update_path = props.getProperty(UPDATE_PATH);

    String applicationId = props.getProperty(APPLICATION_ID);
    if (applicationId == null || applicationId.isEmpty()) {
        applicationId = "SDNC";
    }
    application_id = applicationId;

    // connection timeout
    int tmpConnectionTimeout = 30000;
    int tmpReadTimeout = 30000;

    try {
        String tmpValue = null;
        tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000");
        tmpConnectionTimeout = Integer.parseInt(tmpValue);
        tmpValue = props.getProperty(READ_TIMEOUT, "30000");
        tmpReadTimeout = Integer.parseInt(tmpValue);
    } catch (Exception exc) {
        LOG.error("Failed setting connection timeout", exc);
        tmpConnectionTimeout = 30000;
        tmpReadTimeout = 30000;
    }
    connection_timeout = tmpConnectionTimeout;
    read_timeout = tmpReadTimeout;

    network_vserver_path = props.getProperty(NETWORK_VSERVER_PATH);

    svc_instance_path = props.getProperty(SVC_INSTANCE_PATH); // "/aai/v1/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances");
    //      "/aai/v1/business/customers/customer/ma9181-203-customerid/service-subscriptions/service-subscription/ma9181%20Hosted%20Voice/service-instances";

    //      svc_inst_qry_path   = props.getProperty(SVC_INST_QRY_PATH, "/aai/v1/search/generic-query?key=service-instance.service-instance-id:ma9181-204-instance&start-node-type=service-instance&include=service-instance");
    svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH); // "/aai/v1/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance");

    param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type");

    // P-Interfaces
    p_interface_path = props.getProperty(P_INTERFACE_PATH);

    vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH);

    ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH);
    selflink_avpn = props.getProperty(SELFLINK_AVPN);
    selflink_fqdn = props.getProperty(SELFLINK_FQDN);

    service_path = props.getProperty(SERVICE_PATH);

    site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH);

    query_nodes_path = props.getProperty(QUERY_NODES_PATH);

    String iche = props.getProperty(CERTIFICATE_HOST_ERROR);
    boolean host_error = false;
    if (iche != null && !iche.isEmpty()) {
        host_error = Boolean.valueOf(iche);
    }

    ignore_certificate_host_error = host_error;

    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String string, SSLSession ssls) {
            return ignore_certificate_host_error;
        }
    });

    if (truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) {
        System.setProperty("javax.net.ssl.trustStore", truststore_path);
        System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
    }

    if (keystore_path != null && keystore_password != null && (new File(keystore_path)).exists()) {
        DefaultClientConfig config = new DefaultClientConfig();
        //both jersey and HttpURLConnection can use this
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");

            KeyManagerFactory kmf = null;
            try {
                String def = "SunX509";
                String storeType = "PKCS12";
                def = KeyStore.getDefaultType();
                kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                FileInputStream fin = new FileInputStream(keystore_path);
                //                KeyStore ks = KeyStore.getInstance("PKCS12");

                String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1);

                if (extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) {
                    storeType = "JKS";
                }
                KeyStore ks = KeyStore.getInstance(storeType);

                char[] pwd = keystore_password.toCharArray();
                ks.load(fin, pwd);
                kmf.init(ks, pwd);
            } catch (Exception ex) {
                LOG.error("AAIResource", ex);
            }

            ctx.init(kmf.getKeyManagers(), null, null);
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return ignore_certificate_host_error;
                        }
                    }, ctx));

            CTX = ctx;
            LOG.debug("SSLContext created");

        } catch (KeyManagementException | NoSuchAlgorithmException exc) {
            LOG.error("AAIResource", exc);
        }
    }

    LOG.info("AAIResource.ctor initialized.");

    try {
        Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
        methodsField.setAccessible(true);
        // get the methods field modifiers
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        // bypass the "private" modifier
        modifiersField.setAccessible(true);

        // remove the "final" modifier
        modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);

        /* valid HTTP methods */
        String[] methods = { "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH" };
        // set the new methods - including patch
        methodsField.set(null, methods);

    } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException 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/*  w ww.  j  av a 2s  .  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 . j  a va  2s .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:at.treedb.db.Base.java

/**
 * Updates an entity./* w  w w. j a  v  a  2  s . co m*/
 * 
 * @param dao
 *            {@code DAOiface} (data access object)
 * @param user
 *            user who updates the entity
 * @param map
 *            map containing the changes
 * @throws Exception
 */
protected void update(DAOiface dao, User user, UpdateMap map) throws Exception {
    Class<?> c = this.getClass();

    for (Enum<?> field : map.getMap().keySet()) {
        Update u = map.get(field);
        Field f;
        try {
            f = c.getDeclaredField(field.name());
        } catch (java.lang.NoSuchFieldException e) {
            f = c.getSuperclass().getDeclaredField(field.name());
        }
        f.setAccessible(true);
        switch (u.getType()) {
        case STRING:
            f.set(this, u.getString());
            break;
        case DOUBLE:
            f.set(this, u.getDouble());
            break;
        case FLOAT:
            f.set(this, u.getFloat());
            break;
        case LONG:
            f.set(this, u.getLong());
            break;
        case INT:
            f.set(this, u.getInt());
            break;
        case LAZY_BINARY:
        case BINARY:
            f.set(this, u.getBinary());
            break;
        case BOOLEAN:
            f.set(this, u.getBoolean());
            break;
        case DATE:
            f.set(this, u.getDate());
            break;
        case ENUM:
            f.set(this, u.getEnum());
            break;
        case BIGDECIMAL:
            f.set(this, u.getBigDecimal());
            break;
        case ISTRING: {
            DBkey a = f.getAnnotation(DBkey.class);
            if (a == null || !a.value().equals(Istring.class)) {
                throw new Exception("Base.update(): Field type mismatch for an IString");
            }
            ArrayList<IstringDummy> list = u.getIstringDummy();
            // dao.flush();
            for (IstringDummy i : list) {
                Istring istr = null;
                int userId = user != null ? user.getHistId() : 0;
                if (f.getInt(this) == 0) {
                    istr = Istring.create(dao, domain, user, this.getCID(), i.getText(), i.getLanguage());
                } else {
                    istr = Istring.saveOrUpdate(dao, domain, userId, f.getInt(this), i.getText(),
                            i.getLanguage(), i.getCountry(), this.getCID());
                }
                // only for CI make a reference form IString to the owner
                if (this instanceof CI) {
                    istr.setCI(this.getHistId());
                }
                if (f.getInt(this) == 0) {
                    f.setInt(this, istr.getHistId());
                    dao.update(this);
                }
            }
            break;
        }
        case ISTRING_DELETE: {
            DBkey a = f.getAnnotation(DBkey.class);
            if (a == null || !a.value().equals(Istring.class)) {
                throw new Exception("Base.update(): Field type mismatch for an IString");
            }
            ArrayList<IstringDummy> list = u.getIstringDummy();
            for (IstringDummy i : list) {
                if (i.getCountry() == null && i.getLanguage() == null) {
                    Istring.delete(dao, user, f.getInt(this));
                } else if (i.getCountry() == null && i.getLanguage() != null) {
                    Istring.delete(dao, user, f.getInt(this), i.getLanguage());
                } else if (i.getCountry() != null && i.getLanguage() != null) {
                    Istring.delete(dao, user, f.getInt(this), i.getLanguage(), i.getCountry());
                }
            }
            break;
        }
        case IMAGE: {
            DBkey a = f.getAnnotation(DBkey.class);
            if (a == null || !a.value().equals(Image.class)) {
                throw new Exception("Base.update(): Field type mismatch for an Image");
            }
            Image.update(dao, user, f.getInt(this), u.getUpdateMap());
            break;
        }
        case IMAGE_DUMMY: {
            DBkey a = f.getAnnotation(DBkey.class);
            if (a == null || !a.value().equals(Image.class)) {
                throw new Exception("Base.update(): Field type mismatch for an Image");
            }
            int id = f.getInt(this);
            if (id == 0) {
                ImageDummy idummy = u.getImageDummy();
                if (this instanceof User) {
                    User uuser = (User) this;
                    Image i = Image.create(dao, null, user, "userImage_" + Base.getRandomLong(),
                            idummy.getData(), idummy.getMimeType(), idummy.getLicense());
                    uuser.setImage(i.getHistId());
                } else if (this instanceof DBcategory) {
                    DBcategory cat = (DBcategory) this;
                    Image i = Image.create(dao, null, user, "catImage_" + Base.getRandomLong(),
                            idummy.getData(), idummy.getMimeType(), idummy.getLicense());
                    cat.setIcon(i.getHistId());
                } else {
                    throw new Exception("Base.update(): ImageDummy for this relationship is't defined");
                }
            } else {
                Image.update(dao, user, id, u.getImageDummy().getImageUpdateMap());
            }
            break;
        }
        case IMAGE_DELETE: {
            DBkey a = f.getAnnotation(DBkey.class);
            if (a == null || !a.value().equals(Image.class)) {
                throw new Exception("Base.update(): Field type mismatch for an Image");
            }
            Image.delete(dao, user, f.getInt(this));
            f.setInt(this, 0);
            break;
        }
        default:
            throw new Exception("Base.update(): Type not implemented!");
        }
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

private static void allowPatch(HttpURLConnection connection) {
    if (enabledPatch) {
        return;//from w  ww .  j  a va 2s .c  o  m
    }
    if (patchFailed) {
        connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
        return;
    }
    try {
        Field methodsField = HttpURLConnection.class.getDeclaredField("methods");

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);

        methodsField.setAccessible(true);

        String[] oldMethods = (String[]) methodsField.get(null);
        Set<String> methodsSet = new LinkedHashSet<String>(Arrays.asList(oldMethods));
        methodsSet.addAll(Arrays.asList("PATCH"));
        String[] newMethods = methodsSet.toArray(new String[0]);

        methodsField.set(null/*static field*/, newMethods);
        enabledPatch = true;
    } catch (NoSuchFieldException e) {
        patchFailed = true;
        connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
    } catch (IllegalAccessException ee) {
        patchFailed = true;
        connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
    }
}

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

/**
 * //from w  ww.  ja va 2s.com
 * @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;
}

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;
    }
}