Example usage for java.lang.reflect Field set

List of usage examples for java.lang.reflect Field set

Introduction

In this page you can find the example usage for java.lang.reflect Field set.

Prototype

@CallerSensitive
@ForceInline 
public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the field represented by this Field object on the specified object argument to the specified new value.

Usage

From source file:io.druid.server.namespace.cache.JDBCExtractionNamespaceTest.java

@Test(timeout = 60_000)
public void testMapping() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException,
        ExecutionException, InterruptedException {
    MetadataStorageConnectorConfig config = new MetadataStorageConnectorConfig();
    Field uriField = MetadataStorageConnectorConfig.class.getDeclaredField("connectURI");
    uriField.setAccessible(true);//from   w  ww .  j  a  v a 2  s .c o m
    uriField.set(config, connectionURI);

    final JDBCExtractionNamespace extractionNamespace = new JDBCExtractionNamespace(namespace, config,
            tableName, keyName, valName, tsColumn, new Period(0));
    NamespaceExtractionCacheManagersTest.waitFor(extractionCacheManager.schedule(extractionNamespace));
    Function<String, String> extractionFn = fnCache.get(extractionNamespace.getNamespace());
    for (Map.Entry<String, String> entry : renames.entrySet()) {
        String key = entry.getKey();
        String val = entry.getValue();
        Assert.assertEquals(val, String.format(val, extractionFn.apply(key)));
    }
    Assert.assertEquals(null, extractionFn.apply("baz"));
}

From source file:com.splunk.Command.java

public Command parse(String[] argv) {
    CommandLineParser parser = new PosixParser();

    CommandLine cmdline = null;//from   w ww  . j a  v a  2  s . c  o  m
    try {
        cmdline = parser.parse(this.rules, argv);
    } catch (ParseException e) {
        error(e.getMessage());
    }

    // Unpack the cmdline into a simple Map of options and optionally
    // assign values to any corresponding fields found in the Command class.
    for (Option option : cmdline.getOptions()) {
        String name = option.getLongOpt();
        Object value = option.getValue();

        // Figure out the type of the option and convert the value.
        if (!option.hasArg()) {
            // If it has no arg, then its implicitly boolean and presence
            // of the argument indicates truth.
            value = true;
        } else {
            Class type = (Class) option.getType();
            if (type == null) {
                // Null implies String, no conversion necessary
            } else if (type == Integer.class) {
                value = Integer.parseInt((String) value);
            } else {
                assert false; // Unsupported type
            }
        }

        this.opts.put(name, value);

        // Look for a field of the Command class (or subclass) that
        // matches the long name of the option and, if found, assign the
        // corresponding option value in order to provide simplified
        // access to command options.
        try {
            java.lang.reflect.Field field = this.getClass().getField(name);
            field.set(this, value);
        } catch (NoSuchFieldException e) {
            continue;
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    String[] orig = this.args;
    String[] more = cmdline.getArgs();
    this.args = new String[orig.length + more.length];
    System.arraycopy(orig, 0, this.args, 0, orig.length);
    System.arraycopy(more, 0, this.args, orig.length, more.length);

    if (this.help) {
        printHelp();
        System.exit(0);
    }

    return this;
}

From source file:io.druid.server.namespace.cache.JDBCExtractionNamespaceTest.java

@Test(timeout = 60_000)
public void testFindNew()
        throws NoSuchFieldException, IllegalAccessException, ExecutionException, InterruptedException {
    MetadataStorageConnectorConfig config = new MetadataStorageConnectorConfig();
    Field uriField = MetadataStorageConnectorConfig.class.getDeclaredField("connectURI");
    uriField.setAccessible(true);/*from  w ww.  ja  va2 s  .c o  m*/
    uriField.set(config, connectionURI);
    final JDBCExtractionNamespace extractionNamespace = new JDBCExtractionNamespace(namespace, config,
            tableName, keyName, valName, tsColumn, new Period(1));
    extractionCacheManager.schedule(extractionNamespace);
    while (!fnCache.containsKey(extractionNamespace.getNamespace())) {
        Thread.sleep(1);
    }
    Function<String, String> extractionFn = fnCache.get(extractionNamespace.getNamespace());
    Assert.assertEquals("bar", extractionFn.apply("foo"));

    insertValues("foo", "baz", "2900-01-01 00:00:00");
    Thread.sleep(100);
    extractionFn = fnCache.get(extractionNamespace.getNamespace());
    Assert.assertEquals("baz", extractionFn.apply("foo"));
}

From source file:com.gothiaforum.controller.ActorSearchThinCientControllerTest.java

@Before
public void before()
        throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {

    // mock of services.
    /*//from   w  w  w.j  a  va 2  s  .c  o  m
     articleService = mock(JournalArticleLocalService.class);
     expandoColumnService = mock(ExpandoColumnLocalService.class);
     expandoTableService = mock(ExpandoTableLocalService.class);
     expandoValueService = mock(ExpandoValueLocalService.class);
     portletService = mock(PortletService.class);
     */

    // mock creation
    actionRequest = mock(ActionRequest.class);
    actionResponse = mock(ActionResponse.class);

    renderRequest = mock(RenderRequest.class);
    renderResponse = mock(RenderResponse.class);
    model = mock(Model.class);

    Field field = mockActorsSearchThinClientController.getClass().getDeclaredField("settingsService");
    field.setAccessible(true);
    field.set(mockActorsSearchThinClientController, settingsService);

    Field fieldArcticle = mockActorsSearchThinClientController.getClass().getDeclaredField("articleService");
    fieldArcticle.setAccessible(true);
    fieldArcticle.set(mockActorsSearchThinClientController, articleService);

    Field fieldValue = settingsService.getClass().getDeclaredField("expandoValueService");
    fieldValue.setAccessible(true);
    fieldValue.set(settingsService, expandoValueService);

}

From source file:my.adam.smo.common.LoggerInjector.java

@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);
            if (field.getAnnotation(InjectLogger.class) != null) {
                Logger logger = LoggerFactory.getLogger(bean.getClass());
                field.set(bean, logger);
            }/*www .j  av a2  s.c om*/
        }
    });

    return bean;
}

From source file:io.druid.server.namespace.cache.JDBCExtractionNamespaceTest.java

@Test(timeout = 60_000)
public void testSkipOld()
        throws NoSuchFieldException, IllegalAccessException, ExecutionException, InterruptedException {
    MetadataStorageConnectorConfig config = new MetadataStorageConnectorConfig();
    Field uriField = MetadataStorageConnectorConfig.class.getDeclaredField("connectURI");
    uriField.setAccessible(true);/*from  w  ww  . java  2s .c  om*/
    uriField.set(config, connectionURI);
    final JDBCExtractionNamespace extractionNamespace = new JDBCExtractionNamespace(namespace, config,
            tableName, keyName, valName, tsColumn, new Period(1));
    extractionCacheManager.schedule(extractionNamespace);
    while (!fnCache.containsKey(extractionNamespace.getNamespace())) {
        Thread.sleep(1);
    }
    Assert.assertEquals("bar", fnCache.get(extractionNamespace.getNamespace()).apply("foo"));
    if (tsColumn != null) {
        insertValues("foo", "baz", "1900-01-01 00:00:00");
    }

    Thread.sleep(10);

    Assert.assertEquals("bar", fnCache.get(extractionNamespace.getNamespace()).apply("foo"));
    extractionCacheManager.delete(namespace);
}

From source file:org.slc.sli.ingestion.tool.ValidationControllerTest.java

@Test
public void testValidatorValid() throws IOException, NoSuchFieldException, IllegalAccessException {
    Resource xmlResource = new ClassPathResource("test/InterchangeStudent.xml");
    File xmlFile = xmlResource.getFile();

    IngestionFileEntry ife = Mockito.mock(IngestionFileEntry.class);
    Mockito.when(ife.getFileName()).thenReturn("InterchangeStudent.xml");
    Mockito.when(ife.getFile()).thenReturn(xmlFile);
    Mockito.when(ife.getFileType()).thenReturn(FileType.XML_STUDENT_PARENT_ASSOCIATION);
    Job job = BatchJob.createDefault("testJob");
    job.addFile(ife);/*from  w  w w .  j  av  a2 s .c o  m*/

    Logger log = Mockito.mock(Logger.class);
    Field logField = validationController.getClass().getDeclaredField("logger");
    logField.setAccessible(true);
    logField.set(null, log);

    validationController.processValidators(job);
    Mockito.verify(log, Mockito.atLeastOnce()).info("Processing of file: {} completed.", ife.getFileName());
}

From source file:org.slc.sli.ingestion.tool.ValidationControllerTest.java

@Test
public void testValidatorInValid() throws IOException, NoSuchFieldException, IllegalAccessException {
    Resource xmlResource = new ClassPathResource("emptyXml/InterchangeStudent.xml");
    File xmlFile = xmlResource.getFile();

    IngestionFileEntry ife = Mockito.mock(IngestionFileEntry.class);
    Mockito.when(ife.getFileName()).thenReturn("InterchangeStudent.xml");
    Mockito.when(ife.getFile()).thenReturn(xmlFile);
    Mockito.when(ife.getFileType()).thenReturn(FileType.XML_STUDENT_PARENT_ASSOCIATION);

    Job job = BatchJob.createDefault("testJob");
    job.addFile(ife);//ww w .j  av a  2s  . c o  m

    Logger log = Mockito.mock(Logger.class);
    Field logField = validationController.getClass().getDeclaredField("logger");
    logField.setAccessible(true);
    logField.set(null, log);

    validationController.processValidators(job);
    Mockito.verify(log, Mockito.atLeastOnce()).info("Processing of file: {} resulted in errors.",
            ife.getFileName());
}

From source file:com.erudika.para.utils.filters.FieldFilter.java

private void filterObject(List<String> fields, Object entity) {
    if (fields == null || fields.isEmpty()) {
        return;/*from ww  w  . j  av  a2  s .  c  o m*/
    }
    if (entity instanceof List) {
        for (Object obj : (List) entity) {
            filterObject(fields, obj);
        }
    } else if (entity instanceof Map) {
        for (Object obj : ((Map) entity).values()) {
            filterObject(fields, obj);
        }
    } else if (entity instanceof Object[]) {
        for (Object obj : (Object[]) entity) {
            filterObject(fields, obj);
        }
    } else if (!ClassUtils.isPrimitiveOrWrapper(entity.getClass()) && !(entity instanceof String)) {
        for (Field field : entity.getClass().getDeclaredFields()) {
            try {
                String fieldName = field.getName();
                field.setAccessible(true);
                if (!fields.contains(fieldName)) {
                    field.set(entity, null);
                }
            } catch (Exception e) {
                LoggerFactory.getLogger(this.getClass()).warn(null, e);
            }
        }
    }
}

From source file:org.openmrs.module.radiology.hl7.message.RadiologyORMO01Test.java

@Before
public void runBeforeEachTest() throws Exception {

    patient = new Patient();
    patient.setPatientId(1);//from   w w  w .  j a v  a 2  s  . c  o m

    PatientIdentifierType patientIdentifierType = new PatientIdentifierType();
    patientIdentifierType.setPatientIdentifierTypeId(1);
    patientIdentifierType.setName("Test Identifier Type");
    patientIdentifierType.setDescription("Test description");
    PatientIdentifier patientIdentifier = new PatientIdentifier();
    patientIdentifier.setIdentifierType(patientIdentifierType);
    patientIdentifier.setIdentifier("100");
    patientIdentifier.setPreferred(true);
    Set<PatientIdentifier> patientIdentifiers = new HashSet<PatientIdentifier>();
    patientIdentifiers.add(patientIdentifier);
    patient.addIdentifiers(patientIdentifiers);

    patient.setGender("M");

    Set<PersonName> personNames = new HashSet<PersonName>();
    PersonName personName = new PersonName();
    personName.setFamilyName("Doe");
    personName.setGivenName("John");
    personName.setMiddleName("Francis");
    personNames.add(personName);
    patient.setNames(personNames);

    Calendar calendar = Calendar.getInstance();
    calendar.set(1950, Calendar.APRIL, 1, 0, 0, 0);
    patient.setBirthdate(calendar.getTime());

    radiologyOrder = new RadiologyOrder();
    radiologyOrder.setOrderId(20);

    Field orderNumber = Order.class.getDeclaredField("orderNumber");
    orderNumber.setAccessible(true);
    orderNumber.set(radiologyOrder, "ORD-" + radiologyOrder.getOrderId());

    radiologyOrder.setPatient(patient);
    calendar.set(2015, Calendar.FEBRUARY, 4, 14, 35, 0);
    radiologyOrder.setScheduledDate(calendar.getTime());
    radiologyOrder.setUrgency(Order.Urgency.ON_SCHEDULED_DATE);
    radiologyOrder.setInstructions("CT ABDOMEN PANCREAS WITH IV CONTRAST");

    study = new Study();
    study.setStudyId(1);
    study.setStudyInstanceUid("1.2.826.0.1.3680043.8.2186.1.1");
    study.setModality(Modality.CT);
    radiologyOrder.setStudy(study);
}