List of usage examples for org.apache.commons.lang3.reflect FieldUtils getField
public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess)
From source file:org.ktc.soapui.maven.extension.impl.ErrorHandler.java
private static List<TestCase> getFailedTests(SoapUITestCaseRunner runner) { String fieldName = "failedTests"; Field field = FieldUtils.getField(SoapUITestCaseRunner.class, fieldName, true); try {//from ww w .ja v a2 s . c o m @SuppressWarnings("unchecked") List<TestCase> failedTests = (List<TestCase>) FieldUtils.readField(field, runner, true); return failedTests; } catch (IllegalAccessException e) { throw new RuntimeException("Unable to read field " + fieldName, e); } }
From source file:org.ktc.soapui.maven.extension.impl.ErrorHandler.java
private static List<TestAssertion> getFailedAssertions(SoapUITestCaseRunner runner) { String fieldName = "assertions"; Field field = FieldUtils.getField(SoapUITestCaseRunner.class, fieldName, true); try {/*from w w w. j a va 2s. c om*/ @SuppressWarnings("unchecked") List<TestAssertion> failedAssertionss = (List<TestAssertion>) FieldUtils.readField(field, runner, true); return failedAssertionss; } catch (IllegalAccessException e) { throw new RuntimeException("Unable to read field " + fieldName, e); } }
From source file:org.lenskit.data.dao.file.StaticDataSourceTest.java
@Test public void testLoadRatingsList() throws IOException, URISyntaxException, ClassNotFoundException, IllegalAccessException { URI baseURI = TextEntitySourceTest.class.getResource("ratings.csv").toURI(); JsonNode node = reader.readTree("[{\"file\": \"ratings.csv\", \"format\": \"csv\"}]"); StaticDataSource daoProvider = StaticDataSource.fromJSON(node, baseURI); DataAccessObject dao = daoProvider.get(); verifyRatingsCsvData(dao);//from www . j a va2 s. c o m Field f = FieldUtils.getField(EntityCollectionDAO.class, "storage", true); Class<?> cls = Class.forName("org.lenskit.data.store.PackedEntityCollection"); Map<EntityType, EntityCollection> storage = (Map<EntityType, EntityCollection>) f.get(dao); assertThat(storage.get(CommonTypes.RATING), instanceOf(cls)); }
From source file:org.lenskit.data.dao.file.StaticDataSourceTest.java
@Test public void testLoadRatingsMap() throws IOException, URISyntaxException, ClassNotFoundException, IllegalAccessException { URI baseURI = TextEntitySourceTest.class.getResource("ratings.csv").toURI(); JsonNode node = reader.readTree("{\"ratings\":{\"file\": \"ratings.csv\", \"format\": \"csv\"}}"); StaticDataSource daoProvider = StaticDataSource.fromJSON(node, baseURI); DataAccessObject dao = daoProvider.get(); verifyRatingsCsvData(dao);//from w w w . ja va 2s .c o m Field f = FieldUtils.getField(EntityCollectionDAO.class, "storage", true); Class<?> cls = Class.forName("org.lenskit.data.store.PackedEntityCollection"); Map<EntityType, EntityCollection> storage = (Map<EntityType, EntityCollection>) f.get(dao); assertThat(storage.get(CommonTypes.RATING), instanceOf(cls)); }
From source file:org.ligoj.app.plugin.id.resource.batch.UserFullTaskTest.java
@Test public void configureMessage() throws IllegalArgumentException, IllegalAccessException { final ServerProviderFactory instance = ServerProviderFactory.getInstance(); @SuppressWarnings("unchecked") final List<ProviderInfo<ExceptionMapper<?>>> object = (List<ProviderInfo<ExceptionMapper<?>>>) FieldUtils .getField(ServerProviderFactory.class, "exceptionMappers", true).get(instance); final FailSafeExceptionMapper provider = new FailSafeExceptionMapper(); object.add(new ProviderInfo<>(provider, null, true)); final JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider(); FieldUtils.getField(FailSafeExceptionMapper.class, "jacksonJsonProvider", true).set(provider, jacksonJsonProvider);/*from w ww .j a v a2s.c om*/ final UserImportEntry entry = Mockito.mock(UserImportEntry.class); Mockito.when(entry.getId()).thenThrow(new RuntimeException()); final BatchTaskVo<UserImportEntry> importTask = new BatchTaskVo<>(); importTask.setEntries(Collections.singletonList(entry)); task.configure(importTask); task.jaxrsFactory = instance; task.run(); Assertions.assertEquals(Boolean.TRUE, importTask.getStatus().getStatus()); Assertions.assertEquals(1, importTask.getStatus().getDone()); Assertions.assertEquals(1, importTask.getStatus().getEntries()); }
From source file:org.ligoj.app.plugin.vm.schedule.VmScheduleResourceTest.java
@Test public void createAndUpdateSchedule() throws Exception { final ApplicationContext mockContext = Mockito.mock(ApplicationContext.class); final VmScheduleRepository repository = Mockito.mock(VmScheduleRepository.class); final VmExecutionResource mockResource = Mockito.mock(VmExecutionResource.class); final Subscription entity = this.subscriptionRepository.findOneExpected(subscription); Mockito.when(mockContext.getBean(VmScheduleRepository.class)).thenReturn(repository); Mockito.when(mockContext.getBean(SecurityHelper.class)).thenReturn(Mockito.mock(SecurityHelper.class)); Mockito.when(mockContext.getBean(VmExecutionResource.class)).thenReturn(mockResource); final StdScheduler scheduler = (StdScheduler) vmSchedulerFactoryBean.getScheduler(); final QuartzScheduler qscheduler = (QuartzScheduler) FieldUtils.getField(StdScheduler.class, "sched", true) .get(scheduler);/* w w w .j a va2 s . c o m*/ final QuartzSchedulerResources resources = (QuartzSchedulerResources) FieldUtils .getField(QuartzScheduler.class, "resources", true).get(qscheduler); final JobDetail jobDetail = scheduler .getJobDetail(scheduler.getJobKeys(GroupMatcher.anyJobGroup()).iterator().next()); // "ON" call would fail Mockito.doThrow(new RuntimeException()).when(mockResource).execute(entity, VmOperation.ON); try { // Mock the factory jobDetail.getJobDataMap().put("context", mockContext); ((RAMJobStore) resources.getJobStore()).storeJob(jobDetail, true); Assertions.assertEquals(1, this.repository.findAll().size()); // Schedule all operations within the next 2 seconds final String cron = "" + ((DateUtils.newCalendar().get(Calendar.SECOND) + 2) % 60) + " * * * * ?"; final int id = mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.OFF))); mockSchedule(repository, resource.create(subscription, newSchedule(cron + " *", VmOperation.ON))); Assertions.assertEquals(3, this.repository.findAll().size()); // Yield for the schedules Thread.sleep(2500); // Check the executions Mockito.verify(mockResource).execute(entity, VmOperation.OFF); Mockito.verify(mockResource).execute(entity, VmOperation.ON); // Failed Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.REBOOT); Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.RESET); Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.SHUTDOWN); Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.SUSPEND); // Update the CRON and the operation final VmScheduleVo vo = newSchedule( "" + ((DateUtils.newCalendar().get(Calendar.SECOND) + 2) % 60) + " * * * * ?", VmOperation.SHUTDOWN); vo.setId(id); resource.update(subscription, vo); Assertions.assertEquals(3, this.repository.findAll().size()); // Yield for the schedules Thread.sleep(2500); Mockito.verify(mockResource).execute(entity, VmOperation.SHUTDOWN); } finally { // Restore the factory's context jobDetail.getJobDataMap().put("context", applicationContext); ((RAMJobStore) resources.getJobStore()).storeJob(jobDetail, true); } }
From source file:org.ligoj.app.plugin.vm.schedule.VmScheduleResourceTest.java
@Test public void unscheduleAll() throws Exception { Assertions.assertEquals(1, repository.findAll().size()); repository.deleteAll();/*from w w w . j ava 2 s . c om*/ Assertions.assertEquals(0, repository.findAll().size()); final Subscription entity = this.subscriptionRepository.findOneExpected(subscription); final ApplicationContext mockContext = Mockito.mock(ApplicationContext.class); final VmScheduleRepository repository = Mockito.mock(VmScheduleRepository.class); final VmExecutionResource mockResource = Mockito.mock(VmExecutionResource.class); Mockito.when(mockContext.getBean(VmScheduleRepository.class)).thenReturn(repository); Mockito.when(mockContext.getBean(SecurityHelper.class)).thenReturn(Mockito.mock(SecurityHelper.class)); Mockito.when(mockContext.getBean(VmExecutionResource.class)).thenReturn(mockResource); final StdScheduler scheduler = (StdScheduler) vmSchedulerFactoryBean.getScheduler(); final QuartzScheduler qscheduler = (QuartzScheduler) FieldUtils.getField(StdScheduler.class, "sched", true) .get(scheduler); final QuartzSchedulerResources resources = (QuartzSchedulerResources) FieldUtils .getField(QuartzScheduler.class, "resources", true).get(qscheduler); final JobDetail jobDetail = scheduler .getJobDetail(scheduler.getJobKeys(GroupMatcher.anyJobGroup()).iterator().next()); // One call would fail Mockito.doThrow(new RuntimeException()).when(mockResource).execute(entity, VmOperation.ON); final Subscription otherEntity = new Subscription(); try { // Mock the factory jobDetail.getJobDataMap().put("context", mockContext); ((RAMJobStore) resources.getJobStore()).storeJob(jobDetail, true); // Schedule all operations within the next 2 seconds final String cron = "" + ((DateUtils.newCalendar().get(Calendar.SECOND) + 2) % 60) + " * * * * ? *"; mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.ON))); mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.ON))); mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.ON))); mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.ON))); mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.ON))); Assertions.assertEquals(5, this.repository.findAll().size()); // Persist another VM schedule for another subscription within the // next 2 seconds otherEntity.setProject(entity.getProject()); otherEntity.setNode(entity.getNode()); this.subscriptionRepository.saveAndFlush(otherEntity); final VmScheduleVo schedule2 = newSchedule("0 0 0 1 1 ? 2050", VmOperation.ON); resource.create(otherEntity.getId(), schedule2); Assertions.assertEquals(6, this.repository.findAll().size()); // Yield for the schedules Thread.sleep(2500); } finally { // Restore the factory's context jobDetail.getJobDataMap().put("context", applicationContext); ((RAMJobStore) resources.getJobStore()).storeJob(jobDetail, true); } Mockito.inOrder(mockResource).verify(mockResource, Mockito.calls(5)).execute(entity, VmOperation.ON); Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.OFF); Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.REBOOT); Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.RESET); Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.SHUTDOWN); Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.SUSPEND); // Remove all triggers of the subscription resource.unscheduleAll(subscription); Assertions.assertEquals(1, this.repository.findAll().size()); resource.unscheduleAll(otherEntity.getId()); Assertions.assertEquals(0, this.repository.findAll().size()); }
From source file:org.meveo.commons.utils.ReflectionUtils.java
/** * Check if object has a field//from w ww .j a v a2 s. c om * * @param object Object to check * @param fieldName Name of a field to check * @return True if object has a field */ public static boolean hasField(Object object, String fieldName) { if (object == null) { return false; } Field field = FieldUtils.getField(object.getClass(), fieldName, true); return field != null; }
From source file:org.objectpocket.util.IdSupport.java
/** * returns id for object that has been read from json string * // w ww.j a va 2s. c o m * @param obj * @param idFromProxyIn * @return */ public static String getId(Object obj, String idFromProxyIn) { if (idFromProxyIn.startsWith(OP_REF_STRING)) { String typeName = obj.getClass().getName(); if (!idFieldForType_ObjectsFromStore.containsKey(typeName)) { String fieldName = idFromProxyIn.substring(OP_REF_STRING.length(), idFromProxyIn.length()); Field field = FieldUtils.getField(obj.getClass(), fieldName, true); idFieldForType_ObjectsFromStore.put(typeName, field); } Field field = idFieldForType_ObjectsFromStore.get(typeName); try { idFromProxyIn = (String) field.get(obj); } catch (IllegalAccessException e) { Logger.getAnonymousLogger().log(Level.WARNING, "Could not read id from field " + field.getName() + " for class " + obj.getClass(), e); } } return idFromProxyIn; }
From source file:ubic.gemma.persistence.service.common.auditAndSecurity.AuditTrailDaoImpl.java
@Override public AuditEvent addEvent(final Auditable auditable, final AuditEvent auditEvent) { if (auditEvent.getAction() == null) { throw new IllegalArgumentException("auditEvent was missing a required field"); }/*from ww w. j a va 2 s. c om*/ assert auditEvent.getDate() != null; if (auditEvent.getPerformer() == null) { User user = getUser(); // could be null, if anonymous. Field f = FieldUtils.getField(AuditEvent.class, "performer", true); assert f != null; try { f.set(auditEvent, user); } catch (IllegalArgumentException | IllegalAccessException e) { // shouldn't happen, but just in case... throw new RuntimeException(e); } } AuditTrail trail = auditable.getAuditTrail(); if (trail == null) { /* * Note: this step should be done by the AuditAdvice when the entity was first created, so this is just * defensive. */ logger.warn( "AuditTrail was null. It should have been initialized by the AuditAdvice when the entity was first created."); trail = AuditTrail.Factory.newInstance(); auditable.setAuditTrail(trail); } else { /* * This assumes that nobody else in this session has modified this audit trail. */ if (trail.getId() != null) trail = (AuditTrail) this.getSessionFactory().getCurrentSession().get(AuditTrailImpl.class, trail.getId()); } trail.addEvent(auditEvent); this.getSessionFactory().getCurrentSession().saveOrUpdate(trail); auditable.setAuditTrail(trail); return auditEvent; }