@Before public void setup() { activator = new IotCoreMQTTOutboundServiceActivator(); string = ExportStringData.newTestInstance(); string.setEventString(TEST_STRING); string.setEventId(TEST_ID); Addressable addressable = new Addressable(TEST_STRING, Protocol.OTHER, TEST_ADDRESS, TEST_PORT, TEST_PUBLISHER, TEST_USER, TEST_PASSWORD, TEST_TOPIC); ExportRegistration er = new ExportRegistration(); er.setAddressable(addressable); string.setRegistration(er, TEST_ID); message = MessageBuilder.withPayload(string).build(); try { FieldUtils.writeField(activator, "privateKeyFile", "rsa_private_pkcs8", true); FieldUtils.writeField(activator, "algorithm", "RS256", true); } catch (IllegalAccessException e) { e.printStackTrace(); } }
public static Field getTargetField(Class<?> targetClass, String fieldName) { Field field = null; try { if (targetClass == null) { return field; } if (Object.class.equals(targetClass)) { return field; } field = FieldUtils.getDeclaredField(targetClass, fieldName, true); if (field == null) { field = getTargetField(targetClass.getSuperclass(), fieldName); } } catch (Exception e) { } return field; }
protected Object toBaseInfoValue(String fieldName, String value) { Field field = FieldUtils.getField(BaseInfo.class, fieldName, true); // System.out.println("fieldName:" + fieldName + " field:" + field); Class<?> type = field.getType(); if (ClassTypeUtil.isInteger(type)) { return Integer.parseInt(value); } else if (ClassTypeUtil.isLong(type)) { return Long.parseLong(value); } else if (ClassTypeUtil.isFloat(type)) { return Float.parseFloat(value); } else if (ClassTypeUtil.isDouble(type)) { return Double.parseDouble(value); } else if (type.equals(String.class)) { return value; } else { throw new IllegalArgumentException("未知类型[" + type.getName() + "]."); } }
@SuppressWarnings("unchecked") @Test public void shouldFindEnumValues() throws IllegalAccessException { klass = modelPackage._getClass("Colour"); assertThat(klass.getClassType()).isEqualTo(ClassType.ENUM); Map<String,JEnumConstant> enums = (Map<String, JEnumConstant>) FieldUtils.readField(klass, "enumConstantsByName", true); assertThat(enums.keySet()).contains("LIGHT_BLUE", "RED"); JEnumConstant lightBlue = enums.get("LIGHT_BLUE"); assertThat(lightBlue.javadoc().get(0)).isEqualTo("Colour of the sky"); List<JExpression> args = (List<JExpression>) FieldUtils.readField(lightBlue, "args", true); assertThat(args).hasSize(1); assertThat(args.get(0)).isInstanceOf(JStringLiteral.class); String literal = (String) FieldUtils.readField(args.get(0), "str", true); assertThat(literal).isEqualTo("lightBlue"); }
@Test public void shouldInjectJobLauncherByReferenceName() throws Exception { // Given context().addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:launcherRefTest").to("spring-batch:mockJob?jobLauncher=#alternativeJobLauncher"); } }); // When template.sendBody("direct:launcherRefTest", "Start the job, please."); // Then SpringBatchEndpoint batchEndpoint = context().getEndpoint("spring-batch:mockJob?jobLauncher=#alternativeJobLauncher", SpringBatchEndpoint.class); JobLauncher batchEndpointJobLauncher = (JobLauncher) FieldUtils.readField(batchEndpoint, "jobLauncher", true); assertSame(alternativeJobLauncher, batchEndpointJobLauncher); }
@Test public void shouldResolveAnyJobLauncher() throws Exception { // Given SimpleRegistry registry = new SimpleRegistry(); registry.put("mockJob", job); registry.put("someRandomName", jobLauncher); CamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").to("spring-batch:mockJob"); } }); // When camelContext.start(); // Then SpringBatchEndpoint batchEndpoint = camelContext.getEndpoint("spring-batch:mockJob", SpringBatchEndpoint.class); JobLauncher batchEndpointJobLauncher = (JobLauncher) FieldUtils.readField(batchEndpoint, "jobLauncher", true); assertSame(jobLauncher, batchEndpointJobLauncher); }
@Test public void shouldUseJobLauncherFromComponent() throws Exception { // Given SpringBatchComponent batchComponent = new SpringBatchComponent(); batchComponent.setJobLauncher(alternativeJobLauncher); context.addComponent("customBatchComponent", batchComponent); // When context().addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:startCustom").to("customBatchComponent:mockJob"); } }); // Then SpringBatchEndpoint batchEndpoint = context().getEndpoint("customBatchComponent:mockJob", SpringBatchEndpoint.class); JobLauncher batchEndpointJobLauncher = (JobLauncher) FieldUtils.readField(batchEndpoint, "jobLauncher", true); assertSame(alternativeJobLauncher, batchEndpointJobLauncher); }
/** * @see ValueHolderFieldPair for information on why we need to do field sychronization related to weaving */ private void searchValueHolderFieldPairs(Class<?> type, List<ValueHolderFieldPair> pairs) { if (type.equals(Object.class)) { return; } for (Field valueHolderField : type.getDeclaredFields()) { Matcher matcher = VALUE_HOLDER_FIELD_PATTERN.matcher(valueHolderField.getName()); if (matcher.matches()) { valueHolderField.setAccessible(true); String fieldName = matcher.group(1); Field valueField = FieldUtils.getDeclaredField(type, fieldName, true); if (valueField != null) { pairs.add(new ValueHolderFieldPair(valueField, valueHolderField)); } } } searchValueHolderFieldPairs(type.getSuperclass(), pairs); }
/** * Parses the device informations into the binding model. */ @SuppressWarnings("unchecked") private HmDevice parseDevice(Map<String, ?> deviceData) throws IllegalAccessException { HmDevice device = new HmDevice(); FieldUtils.writeField(device, "address", deviceData.get("ADDRESS"), true); FieldUtils.writeField(device, "type", deviceData.get("TYPE"), true); FieldUtils.writeField(device, "hmInterface", HmInterface.HOMEGEAR, true); Object[] channelList = (Object[]) deviceData.get("CHANNELS"); for (int i = 0; i < channelList.length; i++) { Map<String, ?> channelData = (Map<String, ?>) channelList[i]; device.addChannel(parseChannel(device, channelData)); } return device; }
/** * Adds the battery info datapoint to the specified device if the device has * batteries. */ protected void addBatteryInfo(HmDevice device) throws HomematicClientException { HmBattery battery = HmBatteryTypeProvider.getBatteryType(device.getType()); if (battery != null) { for (HmChannel channel : device.getChannels()) { if ("0".equals(channel.getNumber())) { try { logger.debug("Adding battery type to device {}: {}", device.getType(), battery.getInfo()); HmDatapoint dp = new HmDatapoint(); FieldUtils.writeField(dp, "name", "BATTERY_TYPE", true); FieldUtils.writeField(dp, "writeable", Boolean.FALSE, true); FieldUtils.writeField(dp, "valueType", 20, true); dp.setValue(battery.getInfo()); channel.addDatapoint(dp); } catch (IllegalAccessException ex) { throw new HomematicClientException(ex.getMessage(), ex); } } } } }
private void addDefaultFetchGroupMetadata(FieldMetadata fmd, Class<?> definition) { java.lang.reflect.Field field = FieldUtils.getField(definition, fmd.getName(), true); if (field == null) { LOGGER.warn("Unable to retrieve field {} from class {}. Putting the field in the default fetch group by default.", fmd.getName(), definition.getName()); fmd.setDefaultFetchGroup(true); } else { Persistent persistentAnnotation = ReflectionsUtil.getAnnotationSelfOrAccessor(field, Persistent.class); // set to true, unless there is a JDO annotation that specifies otherwise if (persistentAnnotation == null || StringUtils.isBlank(persistentAnnotation.defaultFetchGroup())) { fmd.setDefaultFetchGroup(true); } } }
private void validateNonEditableField(FieldRecord fieldRecord, Object instance, Object parsedValue, MetadataDto versionMetadata) throws IllegalAccessException { Object fieldOldValue = FieldUtils.readField(instance, StringUtils.uncapitalize(fieldRecord.getName()), true); // We need to check if read only field value isn't changed // in some unexpected way. If so then throw exception if (fieldRecord.isNonEditable() // There is need to use Objects.equals as values - one or both - can be null // which would cause NullPointerException when just .equals() on null value && !Objects.equals(fieldOldValue, parsedValue)) { // Skip for version field if (versionMetadata != null && Constants.Util.TRUE.equals(versionMetadata.getValue())) { return; } throw new FieldReadOnlyException(instance.getClass().getName(), fieldRecord.getName()); } }
@Test public void checkTrackingWhenAclChangeSetsToPurge() throws IllegalAccessException, IOException { @SuppressWarnings("unchecked") ConcurrentLinkedQueue<Long> aclChangeSetsToPurge = (ConcurrentLinkedQueue<Long>) FieldUtils.readField(tracker, "aclChangeSetsToPurge", true); aclChangeSetsToPurge.add(101L); aclChangeSetsToPurge.add(102L); aclChangeSetsToPurge.add(103L); // Invoke the behaviour we're testing testTrackChangesRan(); // aclChangeSetsToPurge verify(informationServer).deleteByAclChangeSetId(101L); verify(informationServer).deleteByAclChangeSetId(102L); verify(informationServer).deleteByAclChangeSetId(103L); // TODO: verify checkShutdown verify(informationServer).commit(); }
@Test public void checkTrackingWhenAclsToPurge() throws IllegalAccessException, IOException { @SuppressWarnings("unchecked") ConcurrentLinkedQueue<Long> aclsToPurge = (ConcurrentLinkedQueue<Long>) FieldUtils.readField(tracker, "aclsToPurge", true); aclsToPurge.add(201L); aclsToPurge.add(202L); aclsToPurge.add(203L); // Invoke the behaviour we're testing testTrackChangesRan(); // aclsToPurge verify(informationServer).deleteByAclId(201L); verify(informationServer).deleteByAclId(202L); verify(informationServer).deleteByAclId(203L); // TODO: verify checkShutdown verify(informationServer).commit(); }
@Test public void trackingAbortsWhenAlreadyRunning() throws Throwable { trackerState.setRunning(true); // Prove running state, before attempt to track() assertTrue(trackerState.isRunning()); FieldUtils.writeField(tracker, "state", trackerState, true); tracker.track(); // Still running - these values are unaffected. assertTrue(trackerState.isRunning()); assertFalse(trackerState.isCheck()); // Prove doTrack() was not called verify(tracker, never()).doTrack(); }
@Test public void allModelsSerializable() throws IOException, NoSuchFieldException, IllegalAccessException { final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); for (ClassInfo classInfo : from(contextClassLoader).getTopLevelClasses("com.github.dockerjava.api.model")) { if (classInfo.getName().endsWith("Test")) { continue; } final Class<?> aClass = classInfo.load(); if (aClass.getProtectionDomain().getCodeSource().getLocation().getPath().endsWith("test-classes/") || aClass.isEnum()) { continue; } LOG.debug("aClass: {}", aClass); assertThat(aClass, typeCompatibleWith(Serializable.class)); final Object serialVersionUID = FieldUtils.readDeclaredStaticField(aClass, "serialVersionUID", true); if (!excludeClasses.contains(aClass.getName())) { assertThat(serialVersionUID, instanceOf(Long.class)); assertThat("Follow devel docs", (Long) serialVersionUID, is(1L)); } } }
private static Object mapExpression(List<String> expressions, Object value) throws Exception { if(expressions.isEmpty()) return value; String head = expressions.get(0); List<String> tail = expressions.subList(1, expressions.size()); if(head.equals("this")) return mapExpression(tail, value); if(head.endsWith("()")) { head = head.substring(0, head.length() - 2); // method call return mapExpression(tail, invokeMethod(value, head)); } else { // field access return mapExpression(tail, FieldUtils.readField(value, head, true)); } }
@Test public void checkLocalRepositoryWithDefaults() throws Exception { Cli c = new Cli(); File settings = writeSettings( temp.newFile()); executeMethod( c, "run", new Object[] { new String[] { "-s", settings.toString()} } ); ManipulationSession session = (ManipulationSession) FieldUtils.readField( c, "session", true ); MavenSession ms = (MavenSession)FieldUtils.readField( session, "mavenSession", true ); assertTrue( ms.getRequest().getLocalRepository().getBasedir().equals( ms.getRequest().getLocalRepositoryPath().toString() ) ); assertTrue ( "File " + new File ( ms.getRequest().getLocalRepository().getBasedir() ).getParentFile().toString() + " was not equal to " + System.getProperty( "user.home" ) + File.separatorChar + ".m2", new File ( ms.getRequest().getLocalRepository().getBasedir() ).getParentFile().toString(). equals( System.getProperty( "user.home" ) + File.separatorChar + ".m2" ) ); }
@Before public void before() throws Exception { userCliProperties = new Properties(); session = new ManipulationSession(); final GalleyInfrastructure galleyInfra = new GalleyInfrastructure( session.getTargetDir(), session.getRemoteRepositories(), session.getLocalRepository(), session.getSettings(), session.getActiveProfiles(), null, null, null, temp.newFolder( "cache-dir" ) ); final GalleyAPIWrapper wrapper = new GalleyAPIWrapper( galleyInfra ); manipulator = new DistributionEnforcingManipulator( ); FieldUtils.writeField (manipulator, "galleyWrapper", wrapper, true); }
@Test(expected = ManipulationException.class) @BMRule(name = "retrieve-first-null", targetClass = "ArtifactManagerImpl", targetMethod = "retrieveFirst(List<? extends Location> locations, ArtifactRef ref)", targetLocation = "AT ENTRY", action = "RETURN null" ) public void resolveArtifactTest() throws Exception { final ManipulationSession session = new ManipulationSession(); final GalleyInfrastructure galleyInfra = new GalleyInfrastructure( session.getTargetDir(), session.getRemoteRepositories(), session.getLocalRepository(), session.getSettings(), session.getActiveProfiles(), null, null, null, temp.newFolder( "cache-dir" ) ); final GalleyAPIWrapper wrapper = new GalleyAPIWrapper( galleyInfra ); final ModelIO model = new ModelIO(); FieldUtils.writeField( model, "galleyWrapper", wrapper, true ); model.resolveRawModel( SimpleProjectVersionRef.parse( "org.commonjava:commonjava:5" ) ); }
private <T extends Annotation> T getAnnotation( Class<? extends Entity> entityClass, PropertyDescriptor descriptor, Class<T> annotationClass ) { try { if ( ( descriptor.getReadMethod() != null ) && descriptor.getReadMethod() .isAnnotationPresent( annotationClass ) ) { return descriptor.getReadMethod().getAnnotation( annotationClass ); } if ( ( descriptor.getWriteMethod() != null ) && descriptor.getWriteMethod() .isAnnotationPresent( annotationClass ) ) { return descriptor.getWriteMethod().getAnnotation( annotationClass ); } Field field = FieldUtils.getField( entityClass, descriptor.getName(), true ); if ( field != null ) { if ( field.isAnnotationPresent( annotationClass ) ) { return field.getAnnotation( annotationClass ); } } } catch ( Exception e ) { logger.error( "Could not retrieve the annotations", e ); } return null; }
/** * Finds the current field class. * * @param baseClass * @return */ public Class getClass(String baseClass) { try { final String _property = getProperty(); final String[] _properties = _property.split("[.]"); Class<?> clazz = Class.forName(baseClass); for (int i = 0; i < _properties.length - 1; i++) { clazz = FieldUtils.getField(clazz, _properties[i], true).getType(); } final String className = FieldUtils.getField(clazz, _properties[_properties.length - 1], true).getType().getName(); return Class.forName(className); } catch (ClassNotFoundException ex) { JPMUtils.getLogger().error(ex); } return null; }
/** * Wires variables from a map into a controller. Useful to inject parameters passed in an * argument map. * * @param map The argument map. * @param controller The controller to be wired. */ public static void wireController(Map<?, ?> map, Object controller) { if (map == null || map.isEmpty() || controller == null) { return; } for (Entry<?, ?> entry : map.entrySet()) { String key = entry.getKey().toString(); Object value = entry.getValue(); try { PropertyUtils.setProperty(controller, key, value); } catch (Exception e) { try { FieldUtils.writeField(controller, key, value, true); } catch (Exception e1) {} } } }
@Before public void setUp() throws Exception { // a tricky initialisation - first inject private fields controller = new ConnectionsController(); connectionsTable = mock( XulTree.class ); FieldUtils.writeDeclaredField( controller, "connectionsTable", connectionsTable, true ); // and then spy the controller controller = spy( controller ); databaseDialog = mock( DatabaseDialog.class ); doReturn( databaseDialog ).when( controller ).getDatabaseDialog(); databaseMeta = mock( DatabaseMeta.class ); doReturn( databaseMeta ).when( databaseDialog ).getDatabaseMeta(); doNothing().when( controller ).refreshConnectionList(); doNothing().when( controller ).showAlreadyExistsMessage(); repository = mock( Repository.class ); controller.init( repository ); }
@BeforeClass public static void hackPropsUi() throws Exception { Field props = getPropsField(); if ( props == null ) { throw new IllegalStateException( "Cannot find 'props' field in " + Props.class.getName() ); } Object value = FieldUtils.readStaticField( props, true ); if ( value == null ) { PropsUI mock = mock( PropsUI.class ); FieldUtils.writeStaticField( props, mock, true ); changedPropsUi = true; } else { changedPropsUi = false; } }
private void testDeletedFlagForObject( Callable<RepositoryElementInterface> elementProvider ) throws Exception { TransDelegate transDelegate = new TransDelegate( purRepository, unifiedRepository ); JobDelegate jobDelegate = new JobDelegate( purRepository, unifiedRepository ); FieldUtils.writeField( purRepository, "transDelegate", transDelegate, true ); FieldUtils.writeField( purRepository, "jobDelegate", jobDelegate, true ); RepositoryElementInterface element = elementProvider.call(); RepositoryDirectoryInterface directory = purRepository.findDirectory( element.getRepositoryDirectory().getPath() ); element.setRepositoryDirectory( directory ); purRepository.save( element, null, null ); assertNotNull( "Element was saved", element.getObjectId() ); RepositoryObject information; information = purRepository.getObjectInformation( element.getObjectId(), element.getRepositoryElementType() ); assertNotNull( information ); assertFalse( information.isDeleted() ); purRepository.deleteTransformation( element.getObjectId() ); assertNotNull( "Element was moved to Trash", unifiedRepository.getFileById( element.getObjectId().getId() ) ); information = purRepository.getObjectInformation( element.getObjectId(), element.getRepositoryElementType() ); assertNotNull( information ); assertTrue( information.isDeleted() ); }
@Test public void testCanSetMaxUsageInMB() throws IllegalAccessException { quota.setMaxUsageMB(0); assertEquals(0, ((Long) FieldUtils.readDeclaredField(quota, "maxUsageBytes", true)).longValue()); quota.setMaxUsageMB(500); assertEquals(524288000, ((Long) FieldUtils.readDeclaredField(quota, "maxUsageBytes", true)).longValue()); // 1 GB quota.setMaxUsageMB(1024); assertEquals(1073741824, ((Long) FieldUtils.readDeclaredField(quota, "maxUsageBytes", true)).longValue()); }
public static void replaceTransformTask(TransformTask transformTask, Transform newTransform) { Field transfromField = FieldUtils.getDeclaredField(TransformTask.class, "transform", true); if (null != transfromField) { try { transfromField.set(transformTask, newTransform); } catch (IllegalAccessException e) { throw new GradleException(e.getMessage(), e); } } }
public static Object getFieldValue(Object obj , String fieldName ){ if(obj == null){ return null ; } Field targetField = getTargetField(obj.getClass(), fieldName); try { return FieldUtils.readField(targetField, obj, true ) ; } catch (IllegalAccessException e) { e.printStackTrace(); } return null ; }
public static void setFieldValue(Object obj , String fieldName , Object value ){ if(null == obj){return;} Field targetField = getTargetField(obj.getClass(), fieldName); try { FieldUtils.writeField(targetField, obj, value) ; } catch (IllegalAccessException e) { e.printStackTrace(); } }
public static Object getFieldValue(Object bean, String fieldName) { Field field = FieldUtils.getField(bean.getClass(), fieldName, true); if (field == null) { throw new NullPointerException("在对象[" + bean.getClass().getName() + "]找不到属性[" + fieldName + "]."); } return getFieldValue(bean, field); }
/** * Initializes the QualityCheckSession defined in the parent step, using Reflection */ public QualityCheckStep() { super(); try { parentSession = new QualityCheckSession(); // replace the "session" with our own version Field field = FieldUtils.getDeclaredField(this.getClass().getSuperclass(), "session", true); field.set(this, parentSession); } catch (IllegalAccessException e) { logger.error("Cannot replace the QualityCheckSession with Reflection"); } }
@SuppressWarnings("unchecked") @Test public void shouldFindEnumValues() throws IllegalAccessException { klass = modelPackage._getClass("Colour"); assertThat(klass.getClassType()).isEqualTo(ClassType.ENUM); Map<String,JEnumConstant> enums = (Map<String, JEnumConstant>) FieldUtils.readField(klass, "enumConstantsByName", true); assertThat(enums.keySet()).containsExactly("LIGHT_BLUE", "RED", "YELLOW", "GREEN"); }
public static void setValue(Entity entity, String attribute, @Nullable Object value) { Preconditions.checkNotNullArgument(entity, "entity is null"); Field field = FieldUtils.getField(entity.getClass(), attribute, true); if (field == null) throw new RuntimeException(String.format("Cannot find field '%s' in class %s", attribute, entity.getClass().getName())); try { field.set(entity, value); } catch (IllegalAccessException e) { throw new RuntimeException(String.format("Unable to set value to %s.%s", entity.getClass().getSimpleName(), attribute), e); } }
public static void setValueForHolder(Entity entity, String attribute, @Nullable Object value) { Preconditions.checkNotNullArgument(entity, "entity is null"); Field field = FieldUtils.getField(entity.getClass(), String.format("_persistence_%s_vh",attribute), true); if (field == null) return; try { field.set(entity, value); } catch (IllegalAccessException e) { throw new RuntimeException(String.format("Unable to set value to %s.%s", entity.getClass().getSimpleName(), attribute), e); } }