Example usage for java.lang.reflect Field setBoolean

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public void setBoolean(Object obj, boolean z) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

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

Usage

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

/**
 * Deserial the xml to object accord to the give model class.
 *
 * @param partitionKey//w  w  w  . j  ava  2s  .com
 * @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: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()
 */// www . j  a va  2s  .  c om
public final synchronized HardwareAddress fromConfigXML(Element pElement) {
    Class hwAddressClass = null;
    HardwareAddressImpl hwAddress = null;

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

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

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

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

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

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

/**
 * This will fill random data except those properties which has skip=true in
 * {@link Randomizer} annotation. Use {@link Randomizer} annotation to
 * specify data value to be generated for specific property.
 * /*  w  w  w.ja  v  a  2s .  com*/
 * @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:org.tvbrowser.tvbrowser.TvBrowser.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    handler = new Handler();
    PrefUtils.initialize(TvBrowser.this);

    Intent start = getIntent();/* www. j  a va 2 s.  c  om*/

    if (start != null && start.hasExtra(SettingConstants.CHANNEL_ID_EXTRA)) {
        mProgramListChannelId = start.getIntExtra(SettingConstants.CHANNEL_ID_EXTRA,
                FragmentProgramsList.NO_CHANNEL_SELECTION_ID);
        mProgramListScrollTime = start.getLongExtra(SettingConstants.START_TIME_EXTRA, -1);
    }

    /*
     * Hack to force overflow menu button to be shown from:
     * http://stackoverflow.com/questions/9286822/how-to-force-use-of-overflow-menu-on-devices-with-menu-button
     */
    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception ex) {
        // Ignore
    }

    try {
        PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

        int oldVersion = PrefUtils.getIntValueWithDefaultKey(R.string.OLD_VERSION,
                R.integer.old_version_default);
        //FAVORITE_LIST
        if (oldVersion > getResources().getInteger(R.integer.old_version_default) && oldVersion < 309) {
            new Thread("READ REMINDERS ONCE FOR ICON") {
                @Override
                public void run() {
                    Cursor reminders = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA,
                            new String[] { TvBrowserContentProvider.KEY_ID },
                            TvBrowserContentProvider.DATA_KEY_MARKING_REMINDER + " OR "
                                    + TvBrowserContentProvider.DATA_KEY_MARKING_FAVORITE_REMINDER,
                            null, TvBrowserContentProvider.KEY_ID);

                    try {
                        reminders.moveToPosition(-1);

                        int idColumn = reminders.getColumnIndex(TvBrowserContentProvider.KEY_ID);
                        ArrayList<String> reminderIdList = new ArrayList<String>();

                        while (reminders.moveToNext()) {
                            reminderIdList.add(String.valueOf(reminders.getLong(idColumn)));
                        }

                        ProgramUtils.addReminderIds(getApplicationContext(), reminderIdList);
                    } finally {
                        IOUtils.closeCursor(reminders);
                    }
                };
            }.start();
        }
        if (oldVersion < 304) {
            Set<String> favoritesSet = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this)
                    .getStringSet("FAVORITE_LIST", new HashSet<String>());

            int id = 1000;

            for (String favorite : favoritesSet) {
                Favorite fav = new Favorite(id++, favorite);

                if (fav.isValid()) {
                    fav.save(getApplicationContext());
                } else {
                    Favorite.handleFavoriteMarking(TvBrowser.this, fav, Favorite.TYPE_MARK_REMOVE);
                }
            }

            Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
            edit.remove("FAVORITE_LIST");
            edit.commit();
        }
        if (oldVersion < 204) {
            int firstTime = PrefUtils.getStringValueAsInt(R.string.PREF_REMINDER_TIME,
                    R.string.pref_reminder_time_default);
            boolean remindAgain = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this)
                    .getBoolean("PREF_REMIND_AGAIN_AT_START", false);
            Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
            edit.remove("PREF_REMIND_AGAIN_AT_START");
            edit.commit();

            if (remindAgain && firstTime > 0) {
                edit.putString(getString(R.string.PREF_REMINDER_TIME_SECOND),
                        getString(R.string.pref_reminder_time_default));
                edit.commit();

                Intent updateAlarmValues = new Intent(UpdateAlarmValue.class.getCanonicalName());
                sendBroadcast(updateAlarmValues);
            }
        }
        if (oldVersion < 218) {
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this);
            Editor edit = pref.edit();

            boolean userDefined = addUserColor(pref, edit,
                    R.color.pref_color_on_air_background_tvb_style_default,
                    R.string.PREF_COLOR_ON_AIR_BACKGROUND, R.string.PREF_COLOR_ON_AIR_BACKGROUND_USER_DEFINED);
            userDefined = addUserColor(pref, edit, R.color.pref_color_on_air_progress_tvb_style_default,
                    R.string.PREF_COLOR_ON_AIR_PROGRESS, R.string.PREF_COLOR_ON_AIR_PROGRESS_USER_DEFINED)
                    || userDefined;
            userDefined = addUserColor(pref, edit, R.color.pref_color_mark_tvb_style_default,
                    R.string.PREF_COLOR_MARKED, R.string.PREF_COLOR_MARKED_USER_DEFINED) || userDefined;
            userDefined = addUserColor(pref, edit, R.color.pref_color_mark_favorite_tvb_style_default,
                    R.string.PREF_COLOR_FAVORITE, R.string.PREF_COLOR_FAVORITE) || userDefined;
            userDefined = addUserColor(pref, edit, R.color.pref_color_mark_reminder_tvb_style_default,
                    R.string.PREF_COLOR_REMINDER, R.string.PREF_COLOR_REMINDER_USER_DEFINED) || userDefined;
            userDefined = addUserColor(pref, edit, R.color.pref_color_mark_sync_tvb_style_favorite_default,
                    R.string.PREF_COLOR_SYNC, R.string.PREF_COLOR_SYNC_USER_DEFINED) || userDefined;

            if (userDefined) {
                edit.putString(getString(R.string.PREF_COLOR_STYLE), "0");
            }

            edit.commit();
        }
        if (oldVersion < 242) {
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this);
            Editor edit = pref.edit();

            if (pref.contains("PREF_WIDGET_BACKGROUND_TRANSPARENCY")
                    && !pref.getBoolean("PREF_WIDGET_BACKGROUND_TRANSPARENCY", true)) {
                edit.remove("PREF_WIDGET_BACKGROUND_TRANSPARENCY");
                edit.putString(getString(R.string.PREF_WIDGET_BACKGROUND_TRANSPARENCY_HEADER), "0");
                edit.putString(getString(R.string.PREF_WIDGET_BACKGROUND_TRANSPARENCY_LIST), "0");
                edit.putBoolean(getString(R.string.PREF_WIDGET_BACKGROUND_ROUNDED_CORNERS), false);
            }

            if (pref.contains("SELECTED_TV_CHANNELS_LIST")) {
                edit.remove("SELECTED_TV_CHANNELS_LIST");
            }
            if (pref.contains("SELECTED_RADIO_CHANNELS_LIST")) {
                edit.remove("SELECTED_RADIO_CHANNELS_LIST");
            }
            if (pref.contains("SELECTED_CINEMA_CHANNELS_LIST")) {
                edit.remove("SELECTED_CINEMA_CHANNELS_LIST");
            }

            edit.commit();
        }
        if (oldVersion < 284 && PrefUtils
                .getStringValue(R.string.PREF_PROGRAM_LISTS_DIVIDER_SIZE,
                        R.string.pref_program_lists_divider_size_default)
                .equals(getString(R.string.divider_small))) {
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this);

            Editor edit = pref.edit();
            edit.remove(getString(R.string.PREF_PROGRAM_LISTS_DIVIDER_SIZE));
            edit.commit();
        }
        if (oldVersion < 287
                && PrefUtils.getBooleanValue(R.string.PREF_WIDGET_BACKGROUND_ROUNDED_CORNERS, true)) {
            Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
            edit.remove(getString(R.string.PREF_WIDGET_BACKGROUND_ROUNDED_CORNERS));
            edit.commit();

            UiUtils.updateImportantProgramsWidget(getApplicationContext());
            UiUtils.updateRunningProgramsWidget(getApplicationContext());
        }

        if (oldVersion > getResources().getInteger(R.integer.old_version_default)
                && oldVersion < pInfo.versionCode) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this);

                    builder.setTitle(R.string.info_version);
                    builder.setMessage(Html.fromHtml(getString(R.string.info_version_new)));
                    builder.setPositiveButton(android.R.string.ok, null);

                    builder.show();
                }
            }, 5000);

        } else if (oldVersion != getResources().getInteger(R.integer.old_version_default)) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    showNews();
                }
            }, 5000);
        }

        if (oldVersion != pInfo.versionCode) {
            Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
            edit.putInt(getString(R.string.OLD_VERSION), pInfo.versionCode);
            edit.commit();
        }
    } catch (NameNotFoundException e) {
    }

    super.onCreate(savedInstanceState);

    SettingConstants.initializeLogoMap(TvBrowser.this, false);

    setContentView(R.layout.activity_tv_browser);

    mProgamListStateStack = new Stack<ProgramsListState>();

    ALL_VALUE = getResources().getString(R.string.filter_channel_all);

    if (savedInstanceState != null) {
        updateRunning = savedInstanceState.getBoolean(SettingConstants.UPDATE_RUNNING_KEY, false);
        selectingChannels = savedInstanceState.getBoolean(SettingConstants.SELECTION_CHANNELS_KEY, false);
    }

    // Set up the action bar.
    actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOffscreenPageLimit(3);

    // When swiping between different sections, select the corresponding
    // tab. We can also use ActionBar.Tab#select() to do this if we have
    // a reference to the Tab.
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);

            Fragment fragment = mSectionsPagerAdapter.getRegisteredFragment(position);

            if (fragment instanceof ProgramTableFragment) {
                ((ProgramTableFragment) fragment).firstLoad(getLayoutInflater());
                ((ProgramTableFragment) fragment).scrollToTime(0, mScrollTimeItem);
            }

            if (mFilterItem != null) {
                mFilterItem.setVisible(!(fragment instanceof FragmentFavorites) && !mSearchExpanded);
            }
            if (mCreateFavorite != null) {
                mCreateFavorite.setVisible(fragment instanceof FragmentFavorites && !mSearchExpanded);
            }

            mProgramsListWasShow = false;

            if (position != 1) {
                mProgamListStateStack.clear();
            }
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by
        // the adapter. Also specify this Activity object, which implements
        // the TabListener interface, as the callback (listener) for when
        // this tab is selected.
        actionBar
                .addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
    }

    int startTab = Integer.parseInt(
            PrefUtils.getStringValue(R.string.TAB_TO_SHOW_AT_START, R.string.tab_to_show_at_start_default));

    if (mSectionsPagerAdapter.getCount() > startTab) {
        mViewPager.setCurrentItem(startTab);
    }

    PluginHandler.loadPlugins(getApplicationContext(), handler);

    IOUtils.handleDataUpdatePreferences(TvBrowser.this);
}

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

/**
 * /*from w w  w  .j  a va  2  s.  c  o  m*/
 * @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  ww w  . j ava2s.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;
    }
}