List of usage examples for java.lang.reflect Field setInt
@CallerSensitive @ForceInline public void setInt(Object obj, int i) throws IllegalArgumentException, IllegalAccessException
From source file:org.apache.zeppelin.service.ShiroAuthenticationServiceTest.java
private void setFinalStatic(Field field, Object newValue) throws NoSuchFieldException, IllegalAccessException { field.setAccessible(true);/*from ww w . j av a2 s . co m*/ Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); }
From source file:org.apache.nifi.controller.MonitorMemoryTest.java
private CapturingLogger wrapAndReturnCapturingLogger() throws Exception { Field loggerField = MonitorMemory.class.getDeclaredField("logger"); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true);//from ww w .j a va 2 s. c o m modifiersField.setInt(loggerField, loggerField.getModifiers() & ~Modifier.FINAL); loggerField.setAccessible(true); CapturingLogger capturingLogger = new CapturingLogger((Logger) loggerField.get(null)); loggerField.set(null, capturingLogger); return capturingLogger; }
From source file:com.orange.clara.cloud.servicedbdumper.task.boot.sequences.BootSequenceSecurity.java
public void removeEncryptionRestriction() { if (!isRestrictedCryptography()) { logger.info("Cryptography restrictions removal not needed"); return;/*from w w w. j ava2 s . com*/ } try { /* * Do the following, but with reflection to bypass access checks: * * JceSecurity.isRestricted = false; * JceSecurity.defaultPolicy.perms.clear(); * JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE); */ final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity"); final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions"); final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission"); final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted"); isRestrictedField.setAccessible(true); final Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL); isRestrictedField.set(null, false); final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy"); defaultPolicyField.setAccessible(true); final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null); final Field perms = cryptoPermissions.getDeclaredField("perms"); perms.setAccessible(true); ((Map<?, ?>) perms.get(defaultPolicy)).clear(); final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE"); instance.setAccessible(true); defaultPolicy.add((Permission) instance.get(null)); logger.info("Successfully removed cryptography restrictions"); } catch (final Exception e) { logger.warn("Failed to remove cryptography restrictions", e); } }
From source file:edu.cornell.med.icb.goby.util.barcode.BarcodeMatcherResult.java
/** * This constructor is provided as an alternate to the one above. It uses a map * to set the values of the fields. This method is considerably slower because it uses reflection to * set the values of the class from a map so don't use this in the case where you are creating * millions of these objects./*w ww . j av a 2 s. c om*/ * @param init the map to initiaize the class with */ public BarcodeMatcherResult(final Map<String, Object> init) { ensureFieldsMap(); for (final Map.Entry<String, Object> entry : init.entrySet()) { try { final Object value = entry.getValue(); if (value == null) { continue; } final Field f = FIELDS_MAP.get(entry.getKey()); if (value instanceof Integer) { f.setInt(this, (Integer) value); } else if (value instanceof Boolean) { f.setBoolean(this, (Boolean) value); } } catch (IllegalAccessException e) { LOG.error(e); } catch (IllegalArgumentException e) { LOG.error(e); } } }
From source file:org.kaaproject.kaa.server.verifiers.facebook.verifier.FacebookUserVerifierTest.java
private void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true);/* w ww. j a v a 2s .co m*/ Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); }
From source file:com.cubusmail.server.user.PreferencesTypeHandler.java
public Object getResult(ResultGetter getter) throws SQLException { String preferencesJson = getter.getString(); Preferences preferences = null; if (preferencesJson != null) { preferences = new Preferences(); try {/*from w w w . j ava 2s .c om*/ JSONObject object = new JSONObject(preferencesJson); Field[] fields = Preferences.class.getFields(); if (fields != null) { for (Field field : fields) { Object value = object.has(field.getName()) ? object.get(field.getName()) : null; if (value != null) { if (value instanceof Integer) { field.setInt(preferences, ((Integer) value).intValue()); } else if (value instanceof Boolean) { field.setBoolean(preferences, ((Boolean) value).booleanValue()); } else if (value instanceof String) { field.set(preferences, value); } } } } } catch (JSONException e) { log.error(e.getMessage(), e); } catch (NumberFormatException e) { log.error(e.getMessage(), e); } catch (IllegalArgumentException e) { log.error(e.getMessage(), e); } catch (IllegalAccessException e) { log.error(e.getMessage(), e); } } return preferences; }
From source file:com.baidu.api.client.core.VersionService.java
private void setField(Field field, String value) throws Exception { field.setAccessible(true);/*from ww w . j a v a2 s . c o m*/ Class<?> cls = field.getType(); if (cls.equals(int.class)) { field.setInt(this, Integer.parseInt(value)); } else if (cls.equals(long.class)) { field.setLong(this, Long.parseLong(value)); } else if (cls.equals(boolean.class)) { field.setBoolean(this, Boolean.parseBoolean(value)); } else if (cls.equals(Integer.class)) { field.set(this, Integer.parseInt(value)); } else if (cls.equals(Long.class)) { field.set(this, Long.parseLong(value)); } else if (cls.equals(Boolean.class)) { field.set(this, Boolean.parseBoolean(value)); } else { field.set(this, value); } }
From source file:code.elix_x.excore.utils.nbt.mbt.encoders.NBTClassEncoder.java
public void populate(MBT mbt, NBTTagCompound nbt, Object o) { Class clazz = o.getClass();/*from ww w . j av a 2s.c o m*/ try { while (clazz != null && clazz != Object.class) { if (!clazz.isAnnotationPresent(MBTIgnore.class)) { for (Field field : clazz.getDeclaredFields()) { if (!field.isAnnotationPresent(MBTIgnore.class)) { field.setAccessible(true); if (nbt.hasKey(field.getName())) { if (encodeStatic || !Modifier.isStatic(field.getModifiers())) { if (Modifier.isFinal(field.getModifiers())) { if (encodeFinal) { Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL); if (field.getGenericType() instanceof ParameterizedType) { Type[] types = ((ParameterizedType) field.getGenericType()) .getActualTypeArguments(); Class[] clas = new Class[] {}; for (Type type : types) { if (type instanceof Class) { clas = ArrayUtils.add(clas, (Class) type); } } field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType(), clas)); } else { field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType())); } } } else { if (field.getGenericType() instanceof ParameterizedType) { Type[] types = ((ParameterizedType) field.getGenericType()) .getActualTypeArguments(); Class[] clas = new Class[] {}; for (Type type : types) { if (type instanceof Class) { clas = ArrayUtils.add(clas, (Class) type); } } field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType(), clas)); } else { field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType())); } } } } } } } clazz = encodeSuper ? clazz.getSuperclass() : Object.class; } } catch (IllegalArgumentException e) { Throwables.propagate(e); } catch (IllegalAccessException e) { Throwables.propagate(e); } catch (NoSuchFieldException e) { Throwables.propagate(e); } catch (SecurityException e) { Throwables.propagate(e); } }
From source file:co.cask.cdap.filetailer.FileTailerIT.java
private void mockMetricsProcessor(PipeManager manager) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { List<Pipe> pipeList = new ArrayList<Pipe>(); StreamClient client = null;// w ww . ja v a 2 s .c o m StreamWriter writer = null; try { Method method1 = manager.getClass().getDeclaredMethod("getPipeConfigs"); method1.setAccessible(true); List<PipeConfiguration> pipeConfList = (List<PipeConfiguration>) method1.invoke(manager); for (PipeConfiguration pipeConf : pipeConfList) { FileTailerQueue queue = new FileTailerQueue(pipeConf.getQueueSize()); client = pipeConf.getSinkConfiguration().getStreamClient(); String streamName = pipeConf.getSinkConfiguration().getStreamName(); Method method2 = manager.getClass().getDeclaredMethod("getStreamWriterForPipe", StreamClient.class, String.class); method2.setAccessible(true); writer = (StreamWriter) method2.invoke(manager, client, streamName); FileTailerStateProcessor stateProcessor = new FileTailerStateProcessorImpl(pipeConf.getDaemonDir(), pipeConf.getStateFile()); FileTailerMetricsProcessor metricsProcessor = new FileTailerMetricsProcessor( pipeConf.getDaemonDir(), pipeConf.getStatisticsFile(), pipeConf.getStatisticsSleepInterval(), pipeConf.getPipeName(), pipeConf.getSourceConfiguration().getFileName()) { @Override public void onReadEventMetric(int eventSize) { super.onReadEventMetric(eventSize); read.incrementAndGet(); } @Override public void onIngestEventMetric(int latency) { super.onIngestEventMetric(latency); ingest.incrementAndGet(); } }; pipeList.add(new Pipe(new LogTailer(pipeConf, queue, stateProcessor, metricsProcessor, null), new FileTailerSink(queue, writer, SinkStrategy.LOADBALANCE, stateProcessor, metricsProcessor, null, pipeConf.getSinkConfiguration().getPackSize()), metricsProcessor)); client = null; writer = null; } Field field = manager.getClass().getDeclaredField("serviceManager"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(manager, new ServiceManager(pipeList)); } finally { if (client != null) { client.close(); } if (writer != null) { writer.close(); } } }
From source file:org.kv.KVConfig.java
/** * Code to read a json file into this structure. * Sorta possible with the json library, but this works * * @param configFile File to read./*from ww w . ja v a2 s. c o m*/ * @return A KVConfig instance with values set from the file. */ public static KVConfig load(File configFile) { try { BufferedReader in = new BufferedReader(new FileReader(configFile)); KVConfig config = new KVConfig(); // read the whole file into a single string String jsonStr = ""; String line; while ((line = in.readLine()) != null) jsonStr += line + "\n"; in.close(); // build a json object from the string JSONObject json = new JSONObject(jsonStr); // while there are keys, set the members of the KVConfig instance Iterator<?> keyiter = json.keys(); while (keyiter.hasNext()) { String key = (String) keyiter.next(); Field field = KVConfig.class.getField(key); // handle arrays first, then scalars if (field.getType().isArray()) { JSONArray array = json.getJSONArray(key); Class<?> component = field.getType().getComponentType(); Object value = Array.newInstance(component, array.length()); for (int i = 0; i < array.length(); i++) { if (component == int.class) { Array.setInt(value, i, array.getInt(i)); } if (component == long.class) { Array.setLong(value, i, array.getLong(i)); } else if (component == String.class) { Array.set(value, i, array.getString(i)); } else if (component == double.class) { Array.setDouble(value, i, array.getDouble(i)); } } field.set(config, value); } else if (field.getType() == int.class) { field.setInt(config, json.getInt(key)); } else if (field.getType() == long.class) { field.setLong(config, json.getLong(key)); } else if (field.getType() == String.class) { field.set(config, json.getString(key)); } else if (field.getType() == double.class) { field.set(config, json.getDouble(key)); } } return config; } catch (Exception e) { e.printStackTrace(); System.exit(-1); } return null; }