public static void cancelListViewBounceShadow(ListView listView) { try { Class<?> c = (Class<?>) Class.forName(AbsListView.class.getName()); Field egtField = c.getDeclaredField("mEdgeGlowTop"); Field egbBottom = c.getDeclaredField("mEdgeGlowBottom"); egtField.setAccessible(true); egbBottom.setAccessible(true); Object egtObject = egtField.get(listView); // this 指的是ListiVew实例 Object egbObject = egbBottom.get(listView); // egtObject.getClass() 实际上是一个 EdgeEffect 其中有两个重要属性 mGlow mEdge // 并且这两个属性都是Drawable类型 Class<?> cc = (Class<?>) Class.forName(egtObject.getClass().getName()); Field mGlow = cc.getDeclaredField("mGlow"); mGlow.setAccessible(true); mGlow.set(egtObject, new ColorDrawable(Color.TRANSPARENT)); mGlow.set(egbObject, new ColorDrawable(Color.TRANSPARENT)); Field mEdge = cc.getDeclaredField("mEdge"); mEdge.setAccessible(true); mEdge.set(egtObject, new ColorDrawable(Color.TRANSPARENT)); mEdge.set(egbObject, new ColorDrawable(Color.TRANSPARENT)); } catch (Exception e) { } }
@Test public void testaddFieldDescSingletonStaticOnly() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { UMLArrows arrows = UMLArrows.getInstance(); Field whitelist = WorkerForArrows.class.getDeclaredField("whitelist"); whitelist.setAccessible(true); ArrayList<String> whitelistv1 = new ArrayList<String>(Arrays.asList("TestMisfitsPackage_UMLArrowsTest")); whitelist.set(arrows, whitelistv1); Field fields = UMLArrows.class.getDeclaredField("fields"); fields.setAccessible(true); SingletonDetector detect = new SingletonDetector("red", "purple"); Field detector = UMLArrows.class.getDeclaredField("detectors"); detector.setAccessible(true); ArrayList<PatternDetector> pattern = new ArrayList<PatternDetector>(); pattern.add(detect); detector.set(arrows, pattern); ArrayList<String> fieldsarray = new ArrayList<String>(); fields.set(arrows, new ArrayList<String>()); Field className = UMLArrows.class.getDeclaredField("className"); className.setAccessible(true); // We must avoid having the stripper from touching this string String toAdd = "TestMisfitsPackage_UMLArrowsTest"; String desc = "LTestMisfitsPackage/UMLArrowsTest;"; className.set(arrows, toAdd); fieldsarray.add(toAdd); int access = Opcodes.ACC_STATIC; // An Opcode of only static should leave // isSingle as false arrows.addFieldDesc(desc, access); assertEquals(false, detect.isDetected()); }
public void forceCustomAnnotationHover() throws NoSuchFieldException, IllegalAccessException { Class<SourceViewer> sourceViewerClazz = SourceViewer.class; sourceViewer.setAnnotationHover(new CommentAnnotationHover(null)); // hack for Eclipse 3.5 try { Field hoverControlCreator = TextViewer.class.getDeclaredField("fHoverControlCreator"); hoverControlCreator.setAccessible(true); hoverControlCreator.set(sourceViewer, new CommentInformationControlCreator()); } catch (Throwable t) { // ignore as it may not exist in other versions } // hack for Eclipse 3.5 try { Method ensureMethod = sourceViewerClazz.getDeclaredMethod("ensureAnnotationHoverManagerInstalled"); ensureMethod.setAccessible(true); ensureMethod.invoke(sourceViewer); } catch (Throwable t) { // ignore as it may not exist in other versions } Field hoverManager = SourceViewer.class.getDeclaredField("fVerticalRulerHoveringController"); hoverManager.setAccessible(true); AnnotationBarHoverManager manager = (AnnotationBarHoverManager) hoverManager.get(sourceViewer); if (manager != null) { Field annotationHover = AnnotationBarHoverManager.class.getDeclaredField("fAnnotationHover"); annotationHover.setAccessible(true); IAnnotationHover hover = (IAnnotationHover) annotationHover.get(manager); annotationHover.set(manager, new CommentAnnotationHover(hover)); } sourceViewer.showAnnotations(true); sourceViewer.showAnnotationsOverview(true); }
public void testSharedCache() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, KeyStoreException, CertificateException, NoSuchProviderException, InvalidAlgorithmParameterException, UnrecoverableEntryException, DigestException, IllegalBlockSizeException, BadPaddingException, IOException, NameNotFoundException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { AuthenticationSettings.INSTANCE.setSharedPrefPackageName("mockpackage"); StorageHelper mockSecure = mock(StorageHelper.class); Context mockContext = mock(Context.class); Context packageContext = mock(Context.class); SharedPreferences prefs = mock(SharedPreferences.class); when(prefs.contains("testkey")).thenReturn(true); when(prefs.getString("testkey", "")).thenReturn("test_encrypted"); when(mockSecure.decrypt("test_encrypted")).thenReturn("{\"mClientId\":\"clientId23\"}"); when(mockContext.createPackageContext("mockpackage", Context.MODE_PRIVATE)) .thenReturn(packageContext); when(packageContext.getSharedPreferences("com.microsoft.aad.adal.cache", Activity.MODE_PRIVATE)) .thenReturn(prefs); Class<?> c = DefaultTokenCacheStore.class; Field encryptHelper = c.getDeclaredField("sHelper"); encryptHelper.setAccessible(true); encryptHelper.set(null, mockSecure); DefaultTokenCacheStore cache = new DefaultTokenCacheStore(mockContext); TokenCacheItem item = cache.getItem("testkey"); // Verify returned item assertEquals("Same item as mock", "clientId23", item.getClientId()); encryptHelper.set(null, null); }
private void readObject(java.io.ObjectInputStream in) throws IOException { float x = in.readFloat(); float y = in.readFloat(); float z = in.readFloat(); String world = in.readUTF(); World w = Spout.getEngine().getWorld(world); try { Field field; field = Vector3.class.getDeclaredField("x"); field.setAccessible(true); field.set(this, x); field = Vector3.class.getDeclaredField("y"); field.setAccessible(true); field.set(this, y); field = Vector3.class.getDeclaredField("z"); field.setAccessible(true); field.set(this, z); field = Point.class.getDeclaredField("world"); field.setAccessible(true); field.set(this, w); } catch (Exception e) { if (Spout.debugMode()) { e.printStackTrace(); } } }
/** * 把查询结果填充到vo中 * * @param rs 查询结果,由调用负责游标 * @param t vo * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ private void fillVO(ResultSet rs, T t) throws IllegalArgumentException, IllegalAccessException, SQLException { for (Field f : listTableFields(t.getClass())) { String name = findFieldName(f); Object object = rs.getObject(name); if (object != null) { if (!f.isAccessible()) { f.setAccessible(true); } if (isBoolean(f)) { f.setBoolean(t, rs.getBoolean(name)); } else if (isInt(f)) { f.setInt(t, rs.getInt(name)); } else if (isLong(f)) { f.setLong(t, rs.getLong(name)); } else if (isString(f)) { f.set(t, rs.getString(name)); } else if (isDate(f)) { f.set(t, rs.getTimestamp(name)); } else if (isByte(f)) { f.setByte(t, rs.getByte(name)); } else if (isChar(f)) { f.setChar(t, rs.getString(name).charAt(0)); } else if (isDouble(f)) { f.setDouble(t, rs.getDouble(name)); } else if (isFloat(f)) { f.setFloat(t, rs.getFloat(name)); } else { f.set(t, object); } } } }
/** * オブジェクトのフィールドにデータを設定する<br> * Integer、Float、Float[]、Stringにしか対応していない * * @param obj 設定対象オブジェクト * @param fl 設定対象フィールド * @param ty 設定対象フィールドの型 * @param data 設定データ * @throws IllegalArgumentException * @throws IllegalAccessException */ protected void dataSetter(Object obj, Field fl, Class ty, String data) throws IllegalArgumentException, IllegalAccessException { // Integer型のデータを設定 if (ty.toString().equals("class java.lang.Integer")) { fl.set(obj, Integer.parseInt(data)); } // Float型のデータを設定 if (ty.toString().equals("class java.lang.Float")) { fl.set(obj, Float.parseFloat(data)); } // String型のデータを設定(""の内側) if (ty.toString().equals("class java.lang.String")) { fl.set(obj, getDoubleQuoatString(data)); } // Float[]型のデータを設定 if (ty.toString().equals("class [Ljava.lang.Float;")) { String[] s; s = data.split(" "); Float[] f = new Float[s.length]; for (int i = 0; i < s.length; i++) { f[i] = Float.parseFloat(s[i]); } fl.set(obj, f); } }
public static void read() { System.out.println("Reading Configuration"); File config = new File(FileUtil.getSpoutcraftDirectory(), "spoutcraft.properties"); try { if (!config.exists()) { config.createNewFile(); } SettingsHandler settings = new SettingsHandler(config); Field[] fields = ConfigReader.class.getDeclaredFields(); for (Field f : fields) { Object value = f.get(null); if (value instanceof Boolean) { f.set(null, getOrSetBooleanProperty(settings, f.getName(), (Boolean) value)); } else if (value instanceof Integer) { f.set(null, getOrSetIntegerProperty(settings, f.getName(), (Integer) value)); } else if (value instanceof Float) { f.set(null, getOrSetFloatProperty(settings, f.getName(), (Float) value)); } } } catch (Exception e) { e.printStackTrace(); } Minecraft.theMinecraft.gameSettings.anaglyph = ConfigReader.anaglyph3D; Minecraft.theMinecraft.gameSettings.gammaSetting = ConfigReader.brightnessSlider; Minecraft.theMinecraft.gameSettings.renderDistance = ConfigReader.renderDistance; Minecraft.theMinecraft.gameSettings.fancyGraphics = ConfigReader.fancyGraphics; Minecraft.theMinecraft.gameSettings.advancedOpengl = ConfigReader.advancedOpenGL != 0; Minecraft.theMinecraft.gameSettings.guiScale = ConfigReader.guiScale; Minecraft.theMinecraft.gameSettings.limitFramerate = ConfigReader.performance; Minecraft.theMinecraft.gameSettings.viewBobbing = ConfigReader.viewBobbing; System.out.println("Finished Reading Configuration"); }
public TestResult mapRow(ResultSet rs, int rowNum) throws SQLException { TestResult result = new TestResult(); // 反射构建PatientInfo实体 Field[] fields = result.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String name = field.getName(); String type = field.getType().getName(); try { if (type.equals(String.class.getName())) { field.set(result, rs.getString(name)); } else if (type.equals(int.class.getName())) { field.setInt(result, rs.getInt(name)); } else if (type.equals(Date.class.getName())) { field.set(result, new java.util.Date(rs.getTimestamp(name).getTime())); } else if (type.equals(char.class.getName())) { String sampleType = rs.getString(name); if (sampleType != null && sampleType.length() > 0) field.setChar(result, sampleType.charAt(0)); } else { field.set(result, rs.getObject(name)); } /*} catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace();*/ } catch (Exception e) { // e.printStackTrace(); } field.setAccessible(false); } return result; }
private Object setField(ResultSet rs, Object info) { Field[] fields = info.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String name = field.getName(); String type = field.getType().getName(); try { if (type.equals(String.class.getName())) { field.set(info, rs.getString(name)); } else if (type.equals(int.class.getName())) { field.setInt(info, rs.getInt(name)); } else if (type.equals(Date.class.getName())) { field.set(info, new java.util.Date(rs.getTimestamp(name).getTime())); } else if (type.equals(long.class.getName())) { field.setLong(info, rs.getLong(name)); } else if (type.equals(char.class.getName())) { String sampleType = rs.getString(name); if (sampleType != null && sampleType.length() > 0) field.setChar(info, sampleType.charAt(0)); } else { field.set(info, rs.getObject(name)); } /*} catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace();*/ } catch (Exception e) { } field.setAccessible(false); } return info; }
private static Object readSynchronizedCollectionFrom( Input input, Schema<?> schema, Object owner, IdStrategy strategy, boolean graph, Object collection, boolean ss, boolean list) throws IOException { if (graph) { // update the actual reference. ((GraphInput) input).updateLast(collection, owner); } final Wrapper wrapper = new Wrapper(); Object c = input.mergeObject(wrapper, strategy.POLYMORPHIC_COLLECTION_SCHEMA); if (!graph || !((GraphInput) input).isCurrentMessageReference()) c = wrapper.value; try { fSynchronizedCollection_c.set(collection, c); // mutex is the object itself. fSynchronizedCollection_mutex.set(collection, collection); if (ss) fSynchronizedSortedSet_ss.set(collection, c); if (list) fSynchronizedList_list.set(collection, c); } catch (Exception e) { throw new RuntimeException(e); } return collection; }
@Override public void before() throws Throwable { super.before(); content = new JellyScriptContent(); listener = StreamTaskListener.fromStdout(); publisher = new ExtendedEmailPublisher(); publisher.defaultContent = "For only 10 easy payment of $69.99 , AWESOME-O 4000 can be yours!"; publisher.defaultSubject = "How would you like your very own AWESOME-O 4000?"; publisher.recipientList = "*****@*****.**"; Field f = ExtendedEmailPublisherDescriptor.class.getDeclaredField("defaultBody"); f.setAccessible(true); f.set(publisher.getDescriptor(), "Give me $4000 and I'll mail you a check for $40,000!"); f = ExtendedEmailPublisherDescriptor.class.getDeclaredField("defaultSubject"); f.setAccessible(true); f.set(publisher.getDescriptor(), "Nigerian needs your help!"); f = ExtendedEmailPublisherDescriptor.class.getDeclaredField("recipientList"); f.setAccessible(true); f.set(publisher.getDescriptor(), "*****@*****.**"); f = ExtendedEmailPublisherDescriptor.class.getDeclaredField("hudsonUrl"); f.setAccessible(true); f.set(publisher.getDescriptor(), "http://localhost/"); build = mock(AbstractBuild.class); AbstractProject project = mock(AbstractProject.class); DescribableList publishers = mock(DescribableList.class); when(publishers.get(ExtendedEmailPublisher.class)).thenReturn(publisher); when(project.getPublishersList()).thenReturn(publishers); when(build.getProject()).thenReturn(project); }
public static FileDescriptor getDescriptorFromChannel(Channel channel) { if (SEL_CH_IMPL_GET_FD != null && SEL_CH_IMPL.isInstance(channel)) { // Pipe Source and Sink, Sockets, and other several other selectable channels try { return (FileDescriptor) SEL_CH_IMPL_GET_FD.invoke(channel); } catch (Exception e) { // return bogus below } } else if (FILE_CHANNEL_IMPL_FD != null && FILE_CHANNEL_IMPL.isInstance(channel)) { // FileChannels try { return (FileDescriptor) FILE_CHANNEL_IMPL_FD.get(channel); } catch (Exception e) { // return bogus below } } else if (FILE_DESCRIPTOR_FD != null) { FileDescriptor unixFD = new FileDescriptor(); // UNIX sockets, from jnr-unixsocket try { if (channel instanceof UnixSocketChannel) { FILE_DESCRIPTOR_FD.set(unixFD, ((UnixSocketChannel) channel).getFD()); return unixFD; } else if (channel instanceof UnixServerSocketChannel) { FILE_DESCRIPTOR_FD.set(unixFD, ((UnixServerSocketChannel) channel).getFD()); return unixFD; } } catch (Exception e) { // return bogus below } } return new FileDescriptor(); }
/** * Populates an instance of an object based on its deserialized contents. That is, this method is * expected to "fill" the object's member fields with deserialized data. * * @param o The object to use as the basis for the population * @param contents The deserialized member fields of the object * @param clazz The class this object should be an instance of * @return A populated instance of the object. Note that this can be a different instance than the * one passed through <code>o</code>. * @throws SerializerException If the operation cannot be carried on */ @SuppressWarnings({"unchecked", "rawtypes"}) protected Object populateObject(Object o, Map<String, Object> contents, Class<?> clazz) throws SerializerException { if (o == null) { return null; } for (String attribute : contents.keySet()) { try { // Get the field associated with the map key and its declared type Field fld = GenericSerializer.getFromAllFields(attribute, clazz); fld.setAccessible(true); Object value_o = contents.get(attribute); if (fld.getType().isEnum()) { if (!(value_o instanceof String)) { throw new SerializerException( "The deserialized value of an enum field should be a string"); } fld.set(o, Enum.valueOf((Class<Enum>) fld.getType(), (String) value_o)); } else { fld.set(o, value_o); } } catch (NoSuchFieldException ex) { throw new SerializerException(ex); } catch (IllegalAccessException ex) { throw new SerializerException(ex); } } return o; }
/** * 填充模型对象 * * @param cursor * @param m */ private void fillField(Cursor cursor, M m) { Field[] fields = m.getClass().getDeclaredFields(); for (Field item : fields) { item.setAccessible(true); Column column = item.getAnnotation(Column.class); if (column != null) { int columnIndex = cursor.getColumnIndex(column.value()); String value = cursor.getString(columnIndex); try { if (item.getType() == int.class) { item.set(m, Integer.valueOf(value)); } else if (item.getType() == long.class) { item.set(m, Long.valueOf(value)); } else { item.set(m, value); } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } } }
public static Object parseString2Obj(JSONObject json, Class<?> clz) { try { Object obj = clz.newInstance(); for (Field tmp : clz.getDeclaredFields()) { tmp.setAccessible(true); try { if (tmp.getType().getName().equals("int")) { tmp.setInt(obj, json.getInt(tmp.getName())); } else if (tmp.getType().getName().equals("long")) { tmp.set(obj, json.getLong(tmp.getName())); } else { tmp.set(obj, json.get(tmp.getName())); } } catch (Exception e) { LogUtils.error(e); } } return obj; } catch (Exception e) { LogUtils.error(e); } return null; }
/** * get ViewHolder class and make reference for evert @link(DynamicViewId) to the actual view if * target contains HashMap<String, Integer> will replaced with the idsMap */ public static void parseDynamicView( Object target, View container, HashMap<String, Integer> idsMap) { for (Field field : target.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(DynamicViewId.class)) { /* if variable is annotated with @DynamicViewId */ final DynamicViewId dynamicViewIdAnnotation = field.getAnnotation(DynamicViewId.class); /* get the Id of the view. if it is not set in annotation user the variable name */ String id = dynamicViewIdAnnotation.id(); if (id.equalsIgnoreCase("")) id = field.getName(); if (idsMap.containsKey(id)) { try { /* get the view Id from the Hashmap and make the connection to the real View */ field.set(target, container.findViewById(idsMap.get(id))); } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { e.printStackTrace(); } } } else if ((field.getName().equalsIgnoreCase("ids")) && (field.getType() == idsMap.getClass())) { try { field.set(target, idsMap); } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { e.printStackTrace(); } } } }
public EntityBlockBreakingSkeleton(World world) { super(world); try { Field field = Navigation.class.getDeclaredField("e"); field.setAccessible(true); AttributeInstance e = (AttributeInstance) field.get(this.getNavigation()); e.setValue(128); } catch (Exception ex) { } try { Field gsa = PathfinderGoalSelector.class.getDeclaredField("b"); gsa.setAccessible(true); gsa.set(this.goalSelector, new UnsafeList<Object>()); gsa.set(this.targetSelector, new UnsafeList<Object>()); } catch (Exception e) { e.printStackTrace(); } this.getNavigation().b(true); // this.goalSelector.a(2, new PathfinderGoalMeleeAttack(this, // EntityHuman.class, 1.0D, false)); this.goalSelector.a(1, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); this.goalSelector.a(1, new PathfinderGoalRandomLookaround(this)); this.goalSelector.a( 1, new PathfinderGoalNearestAttackableTarget(this, EntityHuman.class, 0, true)); this.targetSelector.a(2, new PathfinderGoalHurtByTarget(this, true)); this.a(0.6F, 1.8F); }
private static void doEnhance(Field field, Object g, int depth) { final SmartDate sd = field.getAnnotation(SmartDate.class); if (sd != null) { final SmartDateType sdt = sd.type(); try { if (sdt.equals(SmartDateType.CreatedDate)) { if (Date.class.isAssignableFrom(field.getType())) { Object obj = field.get(g); if (obj == null) field.set(g, new Date()); } } else if (sdt.equals(SmartDateType.UpdatedDate)) { if (Date.class.isAssignableFrom(field.getType())) { field.setAccessible(true); Object obj = field.get(g); if (obj == null) { field.set(g, new Date()); } else if (!hasDisupdateFlag(g)) { field.set(g, new Date()); } } } } catch (Exception e) { debug("SmartDateUtils#doEnhance : %s, %s", e.getClass().getName(), e.getMessage()); throw new OrigamiUnexpectedException(e); } } }
/** * @param factory * @param value */ public void invoke(ConfigurableListableBeanFactory factory, String value) { for (Map.Entry<Field, List<Class>> entry : targets.entrySet()) { Field field = entry.getKey(); for (Class clazz : entry.getValue()) { Map map = factory.getBeansOfType(clazz); for (Object target : map.values()) { try { Object convert = convert(field.getType(), value); if (Enhancer.isEnhanced(target.getClass())) { Object source = getCGLIBSource(target, clazz); field.set(source, convert); } else { field.set(target, convert); } } catch (IllegalAccessException e) { logger.warn( "Can't set value: " + value + "in field: " + field.getName() + "because of: " + e.getMessage()); } } } } }
public void SetAlertDialog(DialogInterface arg0, boolean show) { if (show) { try { Field mField = arg0.getClass().getSuperclass().getDeclaredField("mShowing"); mField.setAccessible(true); mField.set(arg0, true); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { Field mField = arg0.getClass().getSuperclass().getDeclaredField("mShowing"); mField.setAccessible(true); mField.set(arg0, false); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public SizeFacet getMockFacet() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { SizeFacet f = new SizeFacet(); Field field = SizeFacet.class.getDeclaredField("bonusCheckingFacet"); field.setAccessible(true); BonusCheckingFacet fakeFacet = new BonusCheckingFacet() { @Override public double getBonus(CharID cid, String bonusType, String bonusName) { if ("SIZEMOD".equals(bonusType) && "NUMBER".equals(bonusName)) { Double d = bonusInfo.get(cid); return d == null ? 0 : d; } return 0; } }; field.set(f, fakeFacet); field = SizeFacet.class.getDeclaredField("levelFacet"); field.setAccessible(true); LevelFacet fakeLevelFacet = new LevelFacet() { @Override public int getMonsterLevelCount(CharID cid) { return fakeLevels; } }; field.set(f, fakeLevelFacet); return f; }
protected SocketImpl swapSocketImpl(Socket socket, SocketImpl socketImpl) throws Exception { Field implField = ReflectionUtil.getDeclaredField(Socket.class, "impl"); SocketImpl oldSocketImpl = (SocketImpl) implField.get(socket); if (socketImpl == null) { Socket unbindSocket = new Socket(); socketImpl = (SocketImpl) implField.get(unbindSocket); Field cmdsockField = ReflectionUtil.getDeclaredField(socketImpl.getClass(), "cmdsock"); cmdsockField.set( socketImpl, new Socket() { @Override public synchronized void close() throws IOException { throw new IOException(); } }); } implField.set(socket, socketImpl); return oldSocketImpl; }
/** * Unmarshal all the elements to their field values if the fields have the {@link Auto} annotation * defined. * * @param reader - The reader where the elements can be read. * @param o - The object for which the value of fields need to be populated. */ private static void autoUnmarshalEligible(HierarchicalStreamReader reader, Object o) { try { String nodeName = reader.getNodeName(); Class c = o.getClass(); Field f = null; try { f = c.getDeclaredField(nodeName); } catch (NoSuchFieldException e) { UNMARSHALL_ERROR_COUNTER.increment(); } if (f == null) { return; } Annotation annotation = f.getAnnotation(Auto.class); if (annotation == null) { return; } f.setAccessible(true); String value = reader.getValue(); Class returnClass = f.getType(); if (value != null) { if (!String.class.equals(returnClass)) { Method method = returnClass.getDeclaredMethod("valueOf", java.lang.String.class); Object valueObject = method.invoke(returnClass, value); f.set(o, valueObject); } else { f.set(o, value); } } } catch (Throwable th) { logger.error("Error in unmarshalling the object:", th); } }
public void testDateTimeFormatterOldFormat() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, KeyStoreException, CertificateException, NoSuchProviderException, InvalidAlgorithmParameterException, UnrecoverableEntryException, DigestException, IllegalBlockSizeException, BadPaddingException, IOException, NameNotFoundException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { StorageHelper mockSecure = mock(StorageHelper.class); Context mockContext = mock(Context.class); SharedPreferences prefs = mock(SharedPreferences.class); when(prefs.contains("testkey")).thenReturn(true); when(prefs.getString("testkey", "")).thenReturn("test_encrypted"); when(mockSecure.decrypt("test_encrypted")) .thenReturn("{\"mClientId\":\"clientId23\",\"mExpiresOn\":\"Apr 28, 2015 1:09:57 PM\"}"); when(mockContext.getSharedPreferences("com.microsoft.aad.adal.cache", Activity.MODE_PRIVATE)) .thenReturn(prefs); Class<?> c = DefaultTokenCacheStore.class; Field encryptHelper = c.getDeclaredField("sHelper"); encryptHelper.setAccessible(true); encryptHelper.set(null, mockSecure); DefaultTokenCacheStore cache = new DefaultTokenCacheStore(mockContext); TokenCacheItem item = cache.getItem("testkey"); // Verify returned item assertNotNull(item.getExpiresOn()); assertNotNull(item.getExpiresOn().after(new Date())); encryptHelper.set(null, null); }
@Test(dataProvider = "ImmutableFieldNames", expectedExceptions = DcpRuntimeException.class) public void testInvalidPatchImmutableFieldChanged(String fieldName) throws Throwable { InitializeDeploymentMigrationWorkflowService.State startState = buildValidStartState(null, null); Operation startOperation = testHost.startServiceSynchronously( initializeDeploymentMigrationWorkflowService, startState); assertThat(startOperation.getStatusCode(), is(200)); serviceCreated = true; InitializeDeploymentMigrationWorkflowService.State patchState = buildValidPatchState( TaskState.TaskStage.STARTED, InitializeDeploymentMigrationWorkflowService.TaskState.SubStage .PAUSE_DESTINATION_SYSTEM); Field declaredField = patchState.getClass().getDeclaredField(fieldName); if (declaredField.getType() == Integer.class) { declaredField.set(patchState, new Integer(0)); } else if (declaredField.getType() == Set.class) { declaredField.set(patchState, new HashSet<>()); } else { declaredField.set(patchState, declaredField.getType().newInstance()); } Operation patchOperation = Operation.createPatch(UriUtils.buildUri(testHost, TestHost.SERVICE_URI)) .setBody(patchState); testHost.sendRequestAndWait(patchOperation); }
private void setDNAndEntryFields(final T o, final Entry e) throws LDAPPersistException { if (dnField != null) { try { dnField.set(o, e.getDN()); } catch (Exception ex) { debugException(ex); throw new LDAPPersistException( ERR_OBJECT_HANDLER_ERROR_SETTING_DN.get( type.getName(), e.getDN(), dnField.getName(), getExceptionMessage(ex)), ex); } } if (entryField != null) { try { entryField.set(o, new ReadOnlyEntry(e)); } catch (Exception ex) { debugException(ex); throw new LDAPPersistException( ERR_OBJECT_HANDLER_ERROR_SETTING_ENTRY.get( type.getName(), entryField.getName(), getExceptionMessage(ex)), ex); } } }
public static <T> T collapseStructure(T object) { if (hasOnlyNullFields(object)) { return null; } List<Field> fields = getAllFields(object.getClass()); try { for (Field field : fields) { if (!field.isAccessible()) { field.setAccessible(true); } if (field.get(object) != null) { if (field.getType().getName().contains("java.util.List")) { @SuppressWarnings("unchecked") List<Object> list = (List<Object>) field.get(object); List<Object> newList = new ArrayList<Object>(list.size()); boolean isNull = true; for (int i = 0; i < list.size(); i++) { Object o = collapseStructure(list.get(i)); if (o != null) { isNull = false; newList.add(o); } } field.set(object, isNull ? null : newList); continue; } else if (field.getType().getName().contains("java.lang.String")) { if ("".equals(((String) field.get(object)).trim())) { field.set(object, null); } continue; } else if (field.getType().getName().contains("CodeOrText") || field.getType().getName().contains("NameTypeAttribute") || field.getType().getName().contains("PlaceAuthority") || field.getType().getName().contains("Yes")) { Field auxField = field.getType().getDeclaredField("value"); auxField.setAccessible(true); String s = (String) auxField.get(field.get(object)); if ("".equals(s)) { field.set(object, null); } continue; } else { collapseStructure(field.get(object)); } } } } catch (IllegalArgumentException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } catch (IllegalAccessException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } catch (SecurityException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } catch (NoSuchFieldException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } if (hasOnlyNullFields(object)) { return null; } return object; }
/** * 使用检索标准对象查询记录数 * * @param detachedCriteria * @return */ @SuppressWarnings("rawtypes") public long count(DetachedCriteria detachedCriteria) { Criteria criteria = detachedCriteria.getExecutableCriteria(getSession()); long totalCount = 0; try { // Get orders Field field = CriteriaImpl.class.getDeclaredField("orderEntries"); field.setAccessible(true); List orderEntrys = (List) field.get(criteria); // Remove orders field.set(criteria, new ArrayList()); // Get count criteria.setProjection(Projections.rowCount()); totalCount = Long.valueOf(criteria.uniqueResult().toString()); // Clean count criteria.setProjection(null); // Restore orders field.set(criteria, orderEntrys); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return totalCount; }
/** * Proper closure test * * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testStatementCacheCheckForProperClosure() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, SQLException { ConcurrentMap mockCache = createNiceMock(ConcurrentMap.class); List<StatementHandle> mockStatementCollections = createNiceMock(List.class); StatementCache testClass = new StatementCache(1, false, null); Field field = testClass.getClass().getDeclaredField("cache"); field.setAccessible(true); field.set(testClass, mockCache); field = testClass.getClass().getDeclaredField("logger"); field.setAccessible(true); field.set(null, mockLogger); Iterator<StatementHandle> mockIterator = createNiceMock(Iterator.class); StatementHandle mockStatement = createNiceMock(StatementHandle.class); expect(mockCache.values()).andReturn(mockStatementCollections).anyTimes(); expect(mockStatementCollections.iterator()).andReturn(mockIterator).anyTimes(); expect(mockIterator.hasNext()).andReturn(true).once().andReturn(false).once(); expect(mockIterator.next()).andReturn(mockStatement).anyTimes(); expect(mockStatement.isClosed()).andReturn(false).once(); mockLogger.error((String) anyObject()); expectLastCall().once(); replay(mockCache, mockStatementCollections, mockIterator, mockStatement, mockLogger); testClass.checkForProperClosure(); verify(mockCache, mockStatement, mockLogger); }