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:com.nonninz.robomodel.RoboModel.java

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

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

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

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

@SuppressWarnings("unchecked")
/**//from  w ww . ja va  2s  .  c o  m
 * Given a set of properties, load this into the current SqoopOptions
 * instance.
 */
public void loadProperties(Properties props) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:org.apache.ambari.server.controller.AmbariManagementControllerImplTest.java

@Test
public void testgetAmbariServerURI() throws Exception {
    // create mocks
    Injector injector = createStrictMock(Injector.class);
    Capture<AmbariManagementController> controllerCapture = new Capture<AmbariManagementController>();

    // set expectations
    injector.injectMembers(capture(controllerCapture));
    expect(injector.getInstance(Gson.class)).andReturn(null);

    //replay//from  w  w  w . ja v  a 2 s .  c om
    replay(injector);

    AmbariManagementControllerImpl controller = new AmbariManagementControllerImpl(null, null, injector);

    class AmbariConfigsSetter {
        public void setConfigs(AmbariManagementController controller, String masterProtocol,
                String masterHostname, Integer masterPort) throws Exception {
            // masterProtocol
            Class<?> c = controller.getClass();
            Field f = c.getDeclaredField("masterProtocol");
            f.setAccessible(true);

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

            f.set(controller, masterProtocol);

            // masterHostname
            f = c.getDeclaredField("masterHostname");
            f.setAccessible(true);

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

            f.set(controller, masterHostname);

            // masterPort
            f = c.getDeclaredField("masterPort");
            f.setAccessible(true);

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

            f.set(controller, masterPort);
        }
    }

    AmbariConfigsSetter ambariConfigsSetter = new AmbariConfigsSetter();

    ambariConfigsSetter.setConfigs(controller, "http", "hostname", 8080);
    assertEquals("http://hostname:8080/jdk_path", controller.getAmbariServerURI("/jdk_path"));

    ambariConfigsSetter.setConfigs(controller, "https", "somesecuredhost", 8443);
    assertEquals("https://somesecuredhost:8443/mysql_path", controller.getAmbariServerURI("/mysql_path"));

    ambariConfigsSetter.setConfigs(controller, "https", "othersecuredhost", 8443);
    assertEquals("https://othersecuredhost:8443/oracle/ojdbc/",
            controller.getAmbariServerURI("/oracle/ojdbc/"));

    verify(injector);
}

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

/**
 * Set maxRecoveryErrorCount in DFSClient.  In 0.20 pre-append its hard-coded to 5 and
 * makes tests linger.  Here is the exception you'll see:
 * <pre>/* w  w w.  j  a  va  2s. c  om*/
 * 2010-06-15 11:52:28,511 WARN  [DataStreamer for file /hbase/.logs/hlog.1276627923013 block blk_928005470262850423_1021] hdfs.DFSClient$DFSOutputStream(2657): Error Recovery for block blk_928005470262850423_1021 failed  because recovery from primary datanode 127.0.0.1:53683 failed 4 times.  Pipeline was 127.0.0.1:53687, 127.0.0.1:53683. Will retry...
 * </pre>
 * @param stream A DFSClient.DFSOutputStream.
 * @param max
 * @throws NoSuchFieldException
 * @throws SecurityException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
public static void setMaxRecoveryErrorCount(final OutputStream stream, final int max) {
    try {
        Class<?>[] clazzes = DFSClient.class.getDeclaredClasses();
        for (Class<?> clazz : clazzes) {
            String className = clazz.getSimpleName();
            if (className.equals("DFSOutputStream")) {
                if (clazz.isInstance(stream)) {
                    Field maxRecoveryErrorCountField = stream.getClass()
                            .getDeclaredField("maxRecoveryErrorCount");
                    maxRecoveryErrorCountField.setAccessible(true);
                    maxRecoveryErrorCountField.setInt(stream, max);
                    break;
                }
            }
        }
    } catch (Exception e) {
        LOG.info("Could not set max recovery field", e);
    }
}

From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerTest.java

@Test
public void testBacklogCursor() throws Exception {
    ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("cache_backlog_ledger");

    final long maxMessageCacheRetentionTimeMillis = 100;
    Field field = ManagedLedgerImpl.class.getDeclaredField("maxMessageCacheRetentionTimeMillis");
    field.setAccessible(true);/*from w  w  w  .jav  a 2s .c o  m*/
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(ledger, maxMessageCacheRetentionTimeMillis);
    Field backlogThresholdField = ManagedLedgerImpl.class.getDeclaredField("maxActiveCursorBacklogEntries");
    backlogThresholdField.setAccessible(true);
    final long maxActiveCursorBacklogEntries = (long) backlogThresholdField.get(ledger);

    // Open Cursor also adds cursor into activeCursor-container
    ManagedCursor cursor1 = ledger.openCursor("c1");
    ManagedCursor cursor2 = ledger.openCursor("c2");

    final int totalBacklogSizeEntries = (int) maxActiveCursorBacklogEntries;
    CountDownLatch latch = new CountDownLatch(totalBacklogSizeEntries);
    for (int i = 0; i < totalBacklogSizeEntries + 1; i++) {
        String content = "entry"; // 5 bytes
        ByteBuf entry = getMessageWithMetadata(content.getBytes());
        ledger.asyncAddEntry(entry, new AddEntryCallback() {
            @Override
            public void addComplete(Position position, Object ctx) {
                latch.countDown();
                entry.release();
            }

            @Override
            public void addFailed(ManagedLedgerException exception, Object ctx) {
                latch.countDown();
                entry.release();
            }

        }, null);
    }
    latch.await();

    // Verify: cursors are active as :haven't started deactivateBacklogCursor scan
    assertTrue(cursor1.isActive());
    assertTrue(cursor2.isActive());

    // it allows message to be older enough to be considered in backlog
    Thread.sleep(maxMessageCacheRetentionTimeMillis * 2);

    // deactivate backlog cursors
    ledger.checkBackloggedCursors();
    Thread.sleep(100);

    // both cursors have to be inactive
    assertFalse(cursor1.isActive());
    assertFalse(cursor2.isActive());

    // read entries so, cursor1 reaches maxBacklog threshold again to be active again
    List<Entry> entries1 = cursor1.readEntries(50);
    for (Entry entry : entries1) {
        log.info("Read entry. Position={} Content='{}'", entry.getPosition(), new String(entry.getData()));
        entry.release();
    }

    // activate cursors which caught up maxbacklog threshold
    ledger.checkBackloggedCursors();

    // verify: cursor1 has consumed messages so, under maxBacklog threshold => active
    assertTrue(cursor1.isActive());

    // verify: cursor2 has not consumed messages so, above maxBacklog threshold => inactive
    assertFalse(cursor2.isActive());

    ledger.close();
}

From source file:lineage2.gameserver.Config.java

/**
 * Method loadGMAccess.//www.j a  v  a  2  s .co  m
 * @param file File
 */
public static void loadGMAccess(File file) {
    try {
        Field fld;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        Document doc = factory.newDocumentBuilder().parse(file);
        for (Node z = doc.getFirstChild(); z != null; z = z.getNextSibling()) {
            for (Node n = z.getFirstChild(); n != null; n = n.getNextSibling()) {
                if (!n.getNodeName().equalsIgnoreCase("char")) {
                    continue;
                }
                PlayerAccess pa = new PlayerAccess();
                for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                    Class<?> cls = pa.getClass();
                    String node = d.getNodeName();
                    if (node.equalsIgnoreCase("#text")) {
                        continue;
                    }
                    try {
                        fld = cls.getField(node);
                    } catch (NoSuchFieldException e) {
                        _log.info("Not found desclarate ACCESS name: " + node + " in XML Player access Object");
                        continue;
                    }
                    if (fld.getType().getName().equalsIgnoreCase("boolean")) {
                        fld.setBoolean(pa,
                                Boolean.parseBoolean(d.getAttributes().getNamedItem("set").getNodeValue()));
                    } else if (fld.getType().getName().equalsIgnoreCase("int")) {
                        fld.setInt(pa, Integer.valueOf(d.getAttributes().getNamedItem("set").getNodeValue()));
                    }
                }
                gmlist.put(pa.PlayerID, pa);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:at.treedb.backup.Import.java

private void adjustFields(DAOiface dao, Class<?> c, Iterator iter) throws Exception {
    ArrayList<Field> list = ClassDependency.getAllFields(c);
    ArrayList<Field> dbKeys = new ArrayList<Field>();
    ArrayList<Field> detached = new ArrayList<Field>();
    // System.out.println("adjust class:" + c.getSimpleName() + ":");
    for (Field f : list) {
        f.setAccessible(true);//from  w  ww . ja v  a2  s .c  o  m
        if (f.getAnnotation(Detach.class) != null) {
            detached.add(f);
        } else if (f.getAnnotation(DBkey.class) != null) {
            dbKeys.add(f);
        }
    }
    HashMap<Integer, Integer> detachMap = detachIdMap.get(c);
    HashMap<Integer, Integer> historicMap = historicIdMap.get(c);

    while (iter.hasNext()) {
        List<Object> l = iter.next();
        for (Object o : l) {
            Base b = (Base) o;
            for (Field f : dbKeys) {
                f.setAccessible(true);
                Class<?> clazz = f.getAnnotation(DBkey.class).value();
                HashMap<Integer, Integer> idMap;
                Class<?> sel = null;
                // ClassSelector necessary for ID re-mapping?
                if (clazz.equals(ClassSelector.class)) {
                    sel = ((ClassSelector) b).getClass(f);
                    if (sel == null) {
                        continue;
                    }
                    idMap = classIdMap.get(sel);
                } else {
                    idMap = classIdMap.get(clazz);
                }

                if (sel != null && f.getType().equals(Long.TYPE)) {
                    long oldKey = f.getLong(b);
                    if (oldKey > 0) {
                        int id = UIelement.extractHistIdFromComposedId(oldKey);
                        if (idMap.get(id) != null) {
                            long newKey = (oldKey & 0xffffffff00000000L) + idMap.get(id);
                            f.setLong(b, newKey);
                        }
                    }
                } else {
                    int oldKey = f.getInt(b);
                    if (oldKey > 0) {
                        if (c.getName().contains("CIimage")) {
                            System.out.println(f.getName() + ":" + idMap.get(oldKey));
                        }
                        f.setInt(b, idMap.get(oldKey));
                    }
                }
            }
            // re-attach detached binary data
            for (Field f : detached) {
                int index = f.getAnnotation(Detach.class).index();
                String path = Export.createBinaryPath(index, b.getCID(), detachMap.get(b.getDBid()));
                f.set(b, readData(path));

            }
            // set new historic ID

            b.setHistId(historicMap.get(b.getHistId()));

            if (c.equals(CIfile.class)) {
                ciFileHashSet.add(((CIfile) b).getDBfile());
            }

            dao.update(b);
            // re-import DBfile data
            if (c.equals(DBfile.class)) {
                DBfile file = (DBfile) b;
                if (ciFileHashSet.contains(file.getHistId())) {
                    // adapt CIfile virtual path:
                    // /files/ciId/uiElementId/fileName
                    String[] split = file.getPath().split("/");
                    split[2] = "" + classIdMap.get(CI.class).get(Integer.parseInt(split[2]));
                    long composed = Long.parseLong(split[3]);
                    int id = UIelement.extractHistIdFromComposedId(composed);
                    HashMap<Integer, Integer> idMap = classIdMap
                            .get(UIelement.getClassIdFromComposedId(composed));
                    split[3] = "" + ((composed & 0xffffffff00000000L) + idMap.get(id));
                    StringBuffer buf = new StringBuffer();
                    for (String s : split) {
                        if (s.equals("")) {
                            continue;
                        }
                        buf.append("/");
                        buf.append(s);
                    }
                    dBFilePathField.set(file, buf.toString());
                }
                writeFile(dao, file, Export.FILES_DIR + fileIdMap.get(file.getDBid()));
            }
            dao.flush();
            // try to free memory
            if (b instanceof CIblob) {
                // for EclipseLink a session clearing necessary! only
                // detaching isn't working really -
                // memory consumption is increasing in spite of detaching
                // objects!
                if (dao.isJPA() && dao.getJPAimpl() == DAO.JPA_IMPL.ECLIPSELINK) {
                    dao.clear();
                } else {
                    dao.detach(b);
                }
                // clear binary data
                ((CIblob) b).resetBlob();
                b = null;
            }
        }
    }
}