下面列出了怎么用org.apache.commons.lang.reflect.FieldUtils的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void test() throws SQLException, IllegalAccessException {
DasClient client = DasClientFactory.getClient("MySqlSimple");
SqlBuilder sqlBuilder = SqlBuilder.selectCount().from(Person.PERSON).intoObject();
Number before = client.queryObject(sqlBuilder);
DataSourceConfigure oldConfig = DataSourceConfigureLocatorManager.getInstance().getDataSourceConfigure("dal_shard_0");
DataSourceConfigure newConfig = new DataSourceConfigure(oldConfig.getName(), oldConfig.getProperties());
DataSourceConfigureChangeEvent event = new DataSourceConfigureChangeEvent("testEvent", newConfig, oldConfig);
ConcurrentHashMap<String, DataSource> dss = (ConcurrentHashMap<String, DataSource>) FieldUtils.readStaticField(DataSourceLocator.class, "cache", true);
RefreshableDataSource dataSource = (RefreshableDataSource) dss.get("dal_shard_0");
SingleDataSource oldSingleDataSource = ((AtomicReference<SingleDataSource>)FieldUtils.readField(dataSource, "dataSourceReference", true)).get();
dataSource.configChanged(event);
Number after = client.queryObject(sqlBuilder);
//verify datasource changed
assertNotSame(oldSingleDataSource, ((AtomicReference<SingleDataSource>)FieldUtils.readField(dataSource, "dataSourceReference", true)).get());
//verify new datasource work fine
assertEquals(before, after);
}
@Test
public void testUpdateOffsetIdLess() throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
MockMqClientBase mockMqClientBase = new MockMqClientBase();
ConsumerQueueDto consumerQueueDto = buildDefaultConsumerQueueDto();
consumerQueueDto.setPullBatchSize(100);
MqQueueExcutorService mqQueueExcutorService = new MqQueueExcutorService(mockMqClientBase, consumerGroupName,
consumerQueueDto);
mqQueueExcutorService.updateQueueMeta(consumerQueueDto);
consumerQueueDto = buildDefaultConsumerQueueDto();
mqQueueExcutorService.updateOffset(consumerQueueDto, consumerQueueDto.getOffset() - 1);
Field f = FieldUtils.getDeclaredField(MqQueueExcutorService.class, "consumerQueueRef", true);
@SuppressWarnings("unchecked")
AtomicReference<ConsumerQueueDto> consumerQueueRef = (AtomicReference<ConsumerQueueDto>) (f
.get(mqQueueExcutorService));
assertEquals("testUpdateOffsetIdLess error", consumerQueueRef.get().getOffset(), consumerQueueDto.getOffset());
}
@Test
public void testUpdateOffsetIdMore() throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
MockMqClientBase mockMqClientBase = new MockMqClientBase();
ConsumerQueueDto consumerQueueDto = buildDefaultConsumerQueueDto();
consumerQueueDto.setPullBatchSize(100);
MqQueueExcutorService mqQueueExcutorService = new MqQueueExcutorService(mockMqClientBase, consumerGroupName,
consumerQueueDto);
mqQueueExcutorService.updateQueueMeta(consumerQueueDto);
consumerQueueDto = buildDefaultConsumerQueueDto();
mqQueueExcutorService.updateOffset(consumerQueueDto, consumerQueueDto.getOffset() + 1);
Field f = FieldUtils.getDeclaredField(MqQueueExcutorService.class, "consumerQueueRef", true);
@SuppressWarnings("unchecked")
AtomicReference<ConsumerQueueDto> consumerQueueRef = (AtomicReference<ConsumerQueueDto>) (f
.get(mqQueueExcutorService));
assertEquals("testUpdateOffsetIdLess error", consumerQueueRef.get().getOffset() + 1,
consumerQueueDto.getOffset());
}
@Test
public void testUpdateLastIdLess() throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
MockMqClientBase mockMqClientBase = new MockMqClientBase();
ConsumerQueueDto consumerQueueDto = buildDefaultConsumerQueueDto();
consumerQueueDto.setPullBatchSize(100);
MqQueueExcutorService mqQueueExcutorService = new MqQueueExcutorService(mockMqClientBase, consumerGroupName,
consumerQueueDto);
mqQueueExcutorService.updateQueueMeta(consumerQueueDto);
consumerQueueDto = buildDefaultConsumerQueueDto();
MessageDto messageDto = new MessageDto();
messageDto.setId(consumerQueueDto.getLastId() - 1);
mqQueueExcutorService.updateLastId(consumerQueueDto, messageDto);
Field f = FieldUtils.getDeclaredField(MqQueueExcutorService.class, "consumerQueueRef", true);
@SuppressWarnings("unchecked")
AtomicReference<ConsumerQueueDto> consumerQueueRef = (AtomicReference<ConsumerQueueDto>) (f
.get(mqQueueExcutorService));
assertEquals("testUpdateLastIdLess error", consumerQueueRef.get().getLastId(), consumerQueueDto.getOffset());
}
@Test
public void testUpdateLastIdMore() throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
MockMqClientBase mockMqClientBase = new MockMqClientBase();
ConsumerQueueDto consumerQueueDto = buildDefaultConsumerQueueDto();
consumerQueueDto.setPullBatchSize(100);
MqQueueExcutorService mqQueueExcutorService = new MqQueueExcutorService(mockMqClientBase, consumerGroupName,
consumerQueueDto);
mqQueueExcutorService.updateQueueMeta(consumerQueueDto);
consumerQueueDto = buildDefaultConsumerQueueDto();
MessageDto messageDto = new MessageDto();
messageDto.setId(consumerQueueDto.getOffset() + 1);
mqQueueExcutorService.updateLastId(consumerQueueDto, messageDto);
Field f = FieldUtils.getDeclaredField(MqQueueExcutorService.class, "consumerQueueRef", true);
@SuppressWarnings("unchecked")
AtomicReference<ConsumerQueueDto> consumerQueueRef = (AtomicReference<ConsumerQueueDto>) (f
.get(mqQueueExcutorService));
assertEquals("testUpdateLastIdMore error", consumerQueueRef.get().getLastId() + 1,
consumerQueueDto.getLastId());
}
@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;
}
}
@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;
}
}
@Test
public void destroy_inited() throws IllegalAccessException {
AtomicInteger count = new AtomicInteger();
ConfigCenterClient configCenterClient = new MockUp<ConfigCenterClient>() {
@Mock
void destroy() {
count.incrementAndGet();
}
}.getMockInstance();
ConfigCenterConfigurationSourceImpl configCenterSource = new ConfigCenterConfigurationSourceImpl();
FieldUtils.writeDeclaredField(configCenterSource, "configCenterClient", configCenterClient, true);
configCenterSource.destroy();
Assert.assertEquals(1, count.get());
}
@Test
public void destroy_inited() throws IllegalAccessException {
AtomicInteger count = new AtomicInteger();
KieClient kieClient = new MockUp<KieClient>() {
@Mock
void destroy() {
count.incrementAndGet();
}
}.getMockInstance();
KieConfigurationSourceImpl kieSource = new KieConfigurationSourceImpl();
FieldUtils
.writeDeclaredField(kieSource, "kieClient", kieClient, true);
kieSource.destroy();
Assert.assertEquals(1, count.get());
}
public static void copyFields(Object source, Object target, String... fieldNames)
{
Assert.assertNotNull(source);
Assert.assertNotNull(target);
Assert.assertSame(source.getClass(), target.getClass());
for (String fieldName : fieldNames)
{
try
{
Field field = FieldUtils.getField(source.getClass(), fieldName, true);
field.setAccessible(true);
field.set(target, field.get(source));
}
catch (Exception e)
{
Logger.getLogger(CloneUtils.class).warn(e.getMessage());
}
}
}
/**
* @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);
}
@Test
public void checkLocalRepositoryWithDefaults() throws Exception
{
Cli c = new Cli();
File settings = writeSettings( temp.newFile());
TestUtils.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 );
assertEquals( ms.getRequest().getLocalRepository().getBasedir(),
ms.getRequest().getLocalRepositoryPath().toString() );
assertEquals( "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(),
System.getProperty( "user.home" ) + File.separatorChar + ".m2" );
}
@Test
public void checkLocalRepositoryWithExplicitMavenRepoAndSettings() throws Exception
{
File folder = temp.newFolder();
Cli c = new Cli();
TestUtils.executeMethod( c, "run", new Object[] { new String[]
{ "--settings=" + getClass().getResource("/settings-test.xml").getFile(),
"-Dmaven.repo.local=" + folder.toString() }} );
ManipulationSession session = (ManipulationSession) FieldUtils.readField( c, "session", true );
MavenSession ms = (MavenSession)FieldUtils.readField( session, "mavenSession", true );
assertEquals( ms.getLocalRepository().getBasedir(), folder.toString() );
assertEquals( ms.getRequest().getLocalRepository().getBasedir(),
ms.getRequest().getLocalRepositoryPath().toString() );
}
@Test
public void testRoundTripPOMs()
throws Exception
{
URL resource = PomIOTest.class.getResource( filename );
assertNotNull( resource );
File pom = new File( resource.getFile() );
assertTrue( pom.exists() );
File targetFile = folder.newFile( "target.xml" );
FileUtils.copyFile( pom, targetFile );
List<Project> projects = pomIO.parseProject( targetFile );
assertNull( projects.get( 0 ).getModel().getModelEncoding() );
// We don't want this to be the execution root so that it doesn't add "Modified by" which breaks the comparison
FieldUtils.writeDeclaredField( projects.get( 0 ), "executionRoot", false, true);
HashSet<Project> changed = new HashSet<>(projects);
pomIO.rewritePOMs( changed );
assertTrue( FileUtils.contentEqualsIgnoreEOL( pom, targetFile, StandardCharsets.UTF_8.toString() ) );
assertTrue( FileUtils.contentEquals( targetFile, pom ) );
}
/**
* 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 <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;
}
@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;
}
}
@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() );
}
default void writeField(Object target, String fieldName, Object value) {
try {
FieldUtils.writeField(target, fieldName, value, true);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
default Object readField(Object target, String fieldName) {
try {
return FieldUtils.readField(target, fieldName, true);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Test
public void testConstruct() throws IllegalArgumentException, IllegalAccessException {
MockMqClientBase mockMqClientBase = new MockMqClientBase();
MqQueueExcutorService mqQueueExcutorService = new MqQueueExcutorService(mockMqClientBase, consumerGroupName,
buildDefaultConsumerQueueDto());
Field f = FieldUtils.getDeclaredField(MqQueueExcutorService.class, "executor", true);
assertNotEquals("executor construct error", null, f.get(mqQueueExcutorService));
f = FieldUtils.getDeclaredField(MqQueueExcutorService.class, "iSubscriber", true);
assertNotEquals("iSubscriber construct error", null, f.get(mqQueueExcutorService));
f = FieldUtils.getDeclaredField(MqQueueExcutorService.class, "mqResource", true);
assertNotEquals("mqResource construct error", null, f.get(mqQueueExcutorService));
}
@Test
public void testThreadSize() throws IllegalArgumentException, IllegalAccessException {
MockMqClientBase mockMqClientBase = new MockMqClientBase();
MqQueueExcutorService mqQueueExcutorService = new MqQueueExcutorService(mockMqClientBase, consumerGroupName,
buildDefaultConsumerQueueDto());
ConsumerQueueDto consumerQueueDto = buildDefaultConsumerQueueDto();
consumerQueueDto.setThreadSize(consumerQueueDto.getThreadSize() + 1);
mqQueueExcutorService.updateQueueMeta(consumerQueueDto);
Field f = FieldUtils.getDeclaredField(MqQueueExcutorService.class, "consumerQueueRef", true);
@SuppressWarnings("unchecked")
AtomicReference<ConsumerQueueDto> consumerQueueRef = (AtomicReference<ConsumerQueueDto>) (f
.get(mqQueueExcutorService));
assertEquals("threadSize error", consumerQueueDto.getThreadSize(), consumerQueueRef.get().getThreadSize());
}
@Test
public void testQueueOffsetVersion() throws IllegalArgumentException, IllegalAccessException {
MockMqClientBase mockMqClientBase = new MockMqClientBase();
MqQueueExcutorService mqQueueExcutorService = new MqQueueExcutorService(mockMqClientBase, consumerGroupName,
buildDefaultConsumerQueueDto());
ConsumerQueueDto consumerQueueDto = buildDefaultConsumerQueueDto();
consumerQueueDto.setOffsetVersion(consumerQueueDto.getOffsetVersion() + 1);
mqQueueExcutorService.updateQueueMeta(consumerQueueDto);
Field f = FieldUtils.getDeclaredField(MqQueueExcutorService.class, "consumerQueueRef", true);
@SuppressWarnings("unchecked")
AtomicReference<ConsumerQueueDto> consumerQueueRef = (AtomicReference<ConsumerQueueDto>) (f
.get(mqQueueExcutorService));
assertEquals("OffsetVersion error", consumerQueueDto.getOffset(), consumerQueueRef.get().getLastId());
}
@Test
public void testDoPullingDataNotFull() throws IllegalArgumentException, IllegalAccessException,
NoSuchMethodException, SecurityException, InvocationTargetException {
MockMqClientBase mockMqClientBase = new MockMqClientBase();
MqQueueExcutorService mqQueueExcutorService = new MqQueueExcutorService(mockMqClientBase, consumerGroupName,
buildDefaultConsumerQueueDto());
// MqQueueResource resource = (MqQueueResource)
// mockMqClientBase.getContext().getMqResource();
ConsumerQueueDto consumerQueueDto = buildDefaultConsumerQueueDto();
consumerQueueDto.setStopFlag(0);
mqQueueExcutorService.updateQueueMeta(consumerQueueDto);
// Method doPullingData = MqQueueExcutorService.class.getDeclaredMethod("doPullingData");
// doPullingData.setAccessible(true);
// doPullingData.invoke(mqQueueExcutorService);
mqQueueExcutorService.doPullingData();
Field f = FieldUtils.getDeclaredField(MqQueueExcutorService.class, "messages", true);
@SuppressWarnings("unchecked")
BlockingQueue<MessageDto> messages = (BlockingQueue<MessageDto>) (f.get(mqQueueExcutorService));
assertEquals("testDoPullingDataNotFull 1 error", 1, messages.size());
// doPullingData.invoke(mqQueueExcutorService);
mqQueueExcutorService.doPullingData();
assertEquals("testDoPullingDataNotFull 2 error", 2, messages.size());
}
@Test
public void testDoPullingDataFull() throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException,
SecurityException, InvocationTargetException {
MockMqClientBase mockMqClientBase = new MockMqClientBase();
MqQueueExcutorService mqQueueExcutorService = new MqQueueExcutorService(mockMqClientBase, consumerGroupName,
buildDefaultConsumerQueueDto());
// MqQueueResource resource = (MqQueueResource)
// mockMqClientBase.getContext().getMqResource();
ConsumerQueueDto consumerQueueDto = buildDefaultConsumerQueueDto();
consumerQueueDto.setStopFlag(0);
consumerQueueDto.setPullBatchSize(301);
mqQueueExcutorService.updateQueueMeta(consumerQueueDto);
// Method doPullingData = MqQueueExcutorService.class.getDeclaredMethod("doPullingData");
// doPullingData.setAccessible(true);
Runnable runnable = new Runnable() {
@Override
public void run() {
// doPullingData.invoke(mqQueueExcutorService);
mqQueueExcutorService.doPullingData();
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(runnable);
Util.sleep(2000);
Field f = FieldUtils.getDeclaredField(MqQueueExcutorService.class, "messages", true);
@SuppressWarnings("unchecked")
BlockingQueue<MessageDto> messages = (BlockingQueue<MessageDto>) (f.get(mqQueueExcutorService));
assertEquals("testDoPullingDataFull 300 error", 300, messages.size());
for (int i = 0; i < 300; i++) {
messages.poll();
}
Util.sleep(2000);
assertEquals("testDoPullingDataFull 1 error", 1, messages.size());
}
@AfterClass
public static void restoreNullInPropsUi() throws Exception {
if ( changedPropsUi ) {
Field props = getPropsField();
FieldUtils.writeStaticField( props, null, true );
}
}
@AfterClass
public static void restoreNullInPropsUi() throws Exception {
if ( changedPropsUi ) {
Field props = getPropsField();
FieldUtils.writeStaticField( props, null, true );
}
}