Java 类org.apache.commons.lang3.reflect.FieldUtils 实例源码

项目:CreeperKiller    文件:HammerKiller.java   
public static Object createProxy(Object realObject) {
    try {
        MethodInterceptor interceptor = new HammerKiller();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(realObject.getClass());
        enhancer.setCallbackType(interceptor.getClass());
        Class classForProxy = enhancer.createClass();
        Enhancer.registerCallbacks(classForProxy, new Callback[]{interceptor});
        Object createdProxy = classForProxy.newInstance();

        for (Field realField : FieldUtils.getAllFieldsList(realObject.getClass())) {
            if (Modifier.isStatic(realField.getModifiers()))
                continue;
            realField.setAccessible(true);

            realField.set(createdProxy, realField.get(realObject));
        }
        CreeperKiller.LOG.info("Removed HammerCore main menu hook, ads will no longer be displayed.");
        return createdProxy;
    } catch (Exception e) {
        CreeperKiller.LOG.error("Failed to create a proxy for HammerCore ads, they will not be removed.", e);
    }
    return realObject;
}
项目:testee.fi    文件:AbstractBaseMockContributor.java   
@Override
public Map<Field, Object> contributeMocks() {
    injectMocks(testInstance);
    return stream(FieldUtils.getAllFields(testInstance.getClass()))
            .filter(this::isMockField)
            .collect(Collectors.toMap(
                    it -> it,
                    it -> {
                        try {
                            it.setAccessible(true);
                            return it.get(testInstance);
                        } catch (IllegalAccessException e) {
                            throw new TestEEfiException("Failed to retrieve mock from test instance", e);
                        }
                    }
            ));
}
项目:mpd-tools    文件:DataTypeTest.java   
private void validate(Object object, Class<?> clazz) throws Exception {
    for (Field field : FieldUtils.getAllFields(clazz)) {
        int modifiers = field.getModifiers();

        // Ignore static fields
        if (Modifier.isStatic(modifiers)) {
            continue;
        }

        assertTrue("Field is private", Modifier.isPrivate(modifiers));
        assertTrue("Field is final", Modifier.isFinal(modifiers));

        Method getter = clazz.getMethod(getterName(field.getName()));
        assertNotNull("Getter exists", getter);
        assertTrue("Getter is public", Modifier.isPublic(getter.getModifiers()));
    }

    // Check that hashCode, toString and equals are defined
    assertNotNull(clazz.getDeclaredMethod("hashCode").invoke(object));
    assertNotNull(clazz.getDeclaredMethod("toString").invoke(object));
    assertTrue((Boolean) clazz.getDeclaredMethod("equals", Object.class).invoke(object, object));
}
项目:spring-data-documentdb    文件:DocumentDbEntityInformation.java   
private Field getIdField(Class<?> domainClass) {
    Field idField = null;

    final List<Field> fields = FieldUtils.getFieldsListWithAnnotation(domainClass, Id.class);

    if (fields.isEmpty()) {
        idField = ReflectionUtils.findField(getJavaType(), "id");
    } else if (fields.size() == 1) {
        idField = fields.get(0);
    } else {
        throw new IllegalArgumentException("only one field with @Id annotation!");
    }

    if (idField != null && idField.getType() != String.class) {
        throw new IllegalArgumentException("type of id field must be String");
    }
    return idField;
}
项目:spring-data-documentdb    文件:DocumentDbEntityInformation.java   
private Field getPartitionKeyField(Class<?> domainClass) {
    Field partitionKeyField = null;

    final List<Field> fields = FieldUtils.getFieldsListWithAnnotation(domainClass, PartitionKey.class);

    if (fields.size() == 1) {
        partitionKeyField = fields.get(0);
    } else if (fields.size() > 1) {
        throw new IllegalArgumentException("Azure Cosmos DB supports only one partition key, " +
                "only one field with @PartitionKey annotation!");
    }

    if (partitionKeyField != null && partitionKeyField.getType() != String.class) {
        throw new IllegalArgumentException("type of PartitionKey field must be String");
    }
    return partitionKeyField;
}
项目:tifoon    文件:ReflectionObjectTreeAware.java   
@Override
@Nullable
public final List<ObjectTreeAware> traceObjectPath(@NonNull final Object _objectToFind) {
    for (final Field field : FieldUtils.getAllFieldsList(getClass())) {
        try {
            final List<ObjectTreeAware> result = findValue(FieldUtils.readField(this, field.getName(), true), _objectToFind);

            if (result != null) {
                return result;
            }
       } catch (IllegalAccessException _e) {
            // safe to ignore
        }
    }

    return null;
}
项目:gremlin-ogm    文件:Properties.java   
/**
 * Given an {@link Element}, {@link #some} filter's its fields using the given predicate, creates
 * a property key and value for each field, flattens them, and returns it as a {@link List}.
 *
 * @throws IllegalArgumentException, if it finds a property that doesn't have a value, and that
 *                                   property corresponds to a {@link org.apache.tinkerpop.gremlin.object.model.PrimaryKey}
 *                                   or {@link org.apache.tinkerpop.gremlin.object.model.OrderingKey}
 *                                   field.
 */
@SneakyThrows
public static <E extends Element> List<Object> some(E element, Predicate<Field> predicate) {
  List<Object> properties = new ArrayList<>();
  for (Field field : fields(element, predicate)) {
    Object propertyValue = FieldUtils.readField(field, element);
    if (isMissing(propertyValue)) {
      if (isKey(field)) {
        throw Element.Exceptions.requiredKeysMissing(element.getClass(), propertyKey(field));
      }
      continue;
    }
    String propertyName = propertyKey(field);
    properties.add(propertyName);
    if (isPrimitive(field)) {
      if (field.getType().isEnum()) {
        properties.add(((Enum) propertyValue).name());
      } else {
        properties.add(propertyValue);
      }
    } else {
      properties.add(propertyValue);
    }
  }
  return properties;
}
项目:atlas    文件:InjectTransformManager.java   
/**
 * Update the parameters for the transformTask
 *
 * @param transformTask
 * @param consumedInputStreams
 * @param referencedInputStreams
 * @param outputStream
 */
private void updateTransformTaskConfig(TransformTask transformTask,
                                       @NonNull Collection<TransformStream> consumedInputStreams,
                                       @NonNull Collection<TransformStream> referencedInputStreams,
                                       @Nullable IntermediateStream outputStream) throws IllegalAccessException {
    Field consumedInputStreamsField = FieldUtils.getDeclaredField(StreamBasedTask.class,
                                                                  "consumedInputStreams",
                                                                  true);
    Field referencedInputStreamsField = FieldUtils.getDeclaredField(StreamBasedTask.class,
                                                                    "referencedInputStreams",
                                                                    true);
    Field outputStreamField = FieldUtils.getDeclaredField(StreamBasedTask.class,
                                                          "outputStream",
                                                          true);

    if (null == consumedInputStreamsField ||
            null == referencedInputStreamsField ||
            null == outputStreamField) {
        throw new StopExecutionException(
                "The TransformTask does not has field with name: consumedInputStreams or referencedInputStreams or outputStream! Plugin version does not support!");
    }
    consumedInputStreamsField.set(transformTask, consumedInputStreams);
    referencedInputStreamsField.set(transformTask, referencedInputStreams);
    outputStreamField.set(transformTask, outputStream);
}
项目:atlas    文件:InjectTransformManager.java   
/**
 * Gets the parameters of a transformTask
 *
 * @param transformTask
 * @return
 * @throws IllegalAccessException
 */
private TransformTaskParam getTransformParam(TransformTask transformTask) throws IllegalAccessException {
    TransformTaskParam transformTaskParam = new TransformTaskParam();
    Field consumedInputStreamsField = FieldUtils.getDeclaredField(StreamBasedTask.class,
                                                                  "consumedInputStreams",
                                                                  true);
    Field referencedInputStreamsField = FieldUtils.getDeclaredField(StreamBasedTask.class,
                                                                    "referencedInputStreams",
                                                                    true);
    Field outputStreamField = FieldUtils.getDeclaredField(StreamBasedTask.class,
                                                          "outputStream",
                                                          true);

    if (null == consumedInputStreamsField ||
            null == referencedInputStreamsField ||
            null == outputStreamField) {
        throw new StopExecutionException(
                "The TransformTask does not has field with name: consumedInputStreams or referencedInputStreams or outputStream! Plugin version does not support!");
    }
    transformTaskParam.consumedInputStreams = (Collection<TransformStream>) consumedInputStreamsField
            .get(transformTask);
    transformTaskParam.referencedInputStreams = (Collection<TransformStream>) referencedInputStreamsField
            .get(transformTask);
    transformTaskParam.outputStream = (IntermediateStream) outputStreamField.get(transformTask);
    return transformTaskParam;
}
项目:plugin-prov    文件:TerraformUtilsTest.java   
private void checkCommands(final String os, final String... command) throws ReflectiveOperationException {
    final URL[] urLs = ((URLClassLoader) Main.class.getClassLoader()).getURLs();
    ThreadClassLoaderScope scope = null;
    try {
        System.setProperty("os.name", os);
        final URLClassLoader urlClassLoader = new URLClassLoader(urLs, null);
        scope = new ThreadClassLoaderScope(urlClassLoader);
        final Object terra = urlClassLoader.loadClass("org.ligoj.app.plugin.prov.terraform.TerraformUtils").newInstance();
        final Object mock = MethodUtils.invokeStaticMethod(urlClassLoader.loadClass("org.mockito.Mockito"), "mock",
                urlClassLoader.loadClass("org.ligoj.bootstrap.resource.system.configuration.ConfigurationResource"));
        FieldUtils.writeField(terra, "configuration", mock, true);
        Assert.assertEquals(Arrays.asList(command),
                ((ProcessBuilder) MethodUtils.invokeMethod(terra, true, "newBuilder", new Object[] { new String[] { "terraform" } }))
                        .command());
    } finally {
        IOUtils.closeQuietly(scope);
    }
}
项目:xm-ms-entity    文件:TypeKeyValidator.java   
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    try {
        String typeKey = (String) FieldUtils.readField(value, typeKeyField, true);
        if (value instanceof XmEntity) {
            return xmEntitySpecService.getAllKeys().containsKey(typeKey);
        } else {
            XmEntity entity = (XmEntity) FieldUtils.readField(value, entityField, true);
            if (entity == null) {
                return true;
            }
            String entityTypeKey = entity.getTypeKey();
            Map<String, Set<String>> keysByEntityType = xmEntitySpecService.getAllKeys().get(entityTypeKey);
            return !(keysByEntityType == null || keysByEntityType.get(getClassName(value)) == null)
                            && keysByEntityType.get(getClassName(value)).contains(typeKey);
        }
    } catch (IllegalAccessException e) {
        log.debug("Could not get keys for validation", e);
        return false;
    }
}
项目:imagetozxspec    文件:PreferencesService.java   
/**
 * Saves (persists) the options in the OptionsObject that are marked with the
 * PreferencesField annotation.
 */
public static void save() {
    OptionsObject oo = OptionsObject.getInstance();
    Field[] fields = FieldUtils.getFieldsWithAnnotation(OptionsObject.class, PreferencesField.class);
    for (Field field : fields) {
        field.setAccessible(true);
        Object value;
        try {
            value = field.get(oo);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
        if (value != null) {
            if (!field.getType().isPrimitive()) {
                log.debug("Non primitive field found {}", field.getName());
            }
            preferences.put(field.getName(), value.toString());
        }
    }
}
项目:UniversalRemote    文件:InjectionHandler.java   
public static <T> void writeAllFieldsOfType(Object o, T t, Class<T> c) throws IllegalAccessException
{
    boolean wroteSomething = false;

       for (Field f : FieldUtils.getAllFields(o.getClass()))
    {
        if (!Modifier.isStatic(f.getModifiers()) && f.getType().equals(c))
        {
            FieldUtils.writeField(f, o, t, true);
            wroteSomething = true;
        }
    }

       if (!wroteSomething)
        throw new IllegalAccessException();
}
项目:UniversalRemote    文件:InjectionHandler.java   
@SuppressWarnings({ "rawtypes" })
public static <T> void writeAllStaticFieldsOfType(Class d, T t, Class c) throws IllegalAccessException
{
    boolean wroteSomething = false;

       for (Field f : FieldUtils.getAllFields(d))
    {
        if (Modifier.isStatic(f.getModifiers()) && f.getType().equals(c))
        {
            FieldUtils.writeStaticField(f, t, true);
            wroteSomething = true;
        }
    }

       if (!wroteSomething)
        throw new IllegalAccessException();
}
项目:MMORPG_Prototype    文件:ChatMessagePacketHandler.java   
@Override
public void handle(Connection connection, ChatMessagePacket packet)
{
    Field connectionsField = FieldUtils.getField(Server.class, "connections", true);

    Connection[] connections;
    try
    {
        connections = (Connection[])FieldUtils.readField(connectionsField, server, true);
    } catch (IllegalAccessException e)
    {
        throw new RuntimeException(e);
    }
    ChatMessageReplyPacket newPacket = new ChatMessageReplyPacket();
    Character sender = gameData.getUserCharacterByConnectionId(connection.getID());
    String nickname = sender.getNickname();
    newPacket.setMessage(packet.getMessage());
    newPacket.setNickname(nickname);
    Character character;
    for(Connection client : connections)        
        if((character = gameData.getUserCharacterByConnectionId(client.getID())) != null)
        {
            newPacket.setSourceCharacterId(character.getId());
            server.sendToTCP(client.getID(), newPacket);
        }
}
项目:plugin-id    文件:UserFullLdapTaskTest.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);

    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();
    Assert.assertEquals(Boolean.TRUE, importTask.getStatus().getStatus());
    Assert.assertEquals(1, importTask.getStatus().getDone());
    Assert.assertEquals(1, importTask.getStatus().getEntries());
}
项目:bootstrap    文件:BackendProxyServletTest.java   
@Before
public void setup() throws IllegalAccessException {
    servletContext = Mockito.mock(ServletContext.class);
    servlet = new BackendProxyServlet() {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        {
            _log = Log.getLogger("junit");
        }

        @Override
        public ServletContext getServletContext() {
            return servletContext;
        }
    };

    FieldUtils.writeField(servlet, "_log", Mockito.mock(Logger.class), true);
    callback = Mockito.mock(Callback.class);
}
项目:jvm-sandbox    文件:ControlModule.java   
private void cleanSpy() throws ClassNotFoundException, IllegalAccessException {
    // 清理Spy中的所有方法
    final Class<?> classOfSpy = getClass().getClassLoader()
            .loadClass("java.com.alibaba.jvm.sandbox.spy.Spy");
    for (final Field waitingCleanField : classOfSpy.getDeclaredFields()) {
        if (Method.class.isAssignableFrom(waitingCleanField.getType())) {
            FieldUtils.writeDeclaredStaticField(
                    classOfSpy,
                    waitingCleanField.getName(),
                    null,
                    true
            );
        }
    }
    logger.info("clean Spy's method success, for jvm-sandbox shutdown.");
}
项目:core-config-seed    文件:EdgeXConfigSeedTest.java   
@Before
public void setup() throws IllegalAccessException {
  MockitoAnnotations.initMocks(this);
  List<String> yamlExtensions = new ArrayList<>();
  yamlExtensions.add(".yaml");
  yamlExtensions.add(".yml");
  FieldUtils.writeField(seed, "yamlExtensions", yamlExtensions, true);
  FieldUtils.writeField(seed, "protocol", CONSUL_PROTOCOL, true);
  FieldUtils.writeField(seed, "host", CONSUL_HOST, true);
  FieldUtils.writeField(seed, "port", CONSUL_PORT, true);
  FieldUtils.writeField(seed, "globalPrefix", CONSUL_GLOBAL_PREFIX, true);
  FieldUtils.writeField(seed, "failLimit", FAIL_LIMIT, true);
  FieldUtils.writeField(seed, "waitTimeBetweenFails", WAIT_TIME, true);
  FieldUtils.writeField(seed, "configPath", CONFIG_PATH, true);
  List<String> acceptableFileExtenstions = new ArrayList<>();
  acceptableFileExtenstions.addAll(yamlExtensions);
  acceptableFileExtenstions.add(".properties");
  FieldUtils.writeField(seed, "acceptablePropertyExtensions", acceptableFileExtenstions, true);
  consul = seed.getConsul();
  assertNotNull("Unable to get Consul instance for testing (check that Consul is running).",
      consul);
  kvClient = consul.keyValueClient();
  assertNotNull("Key Value Client is null.  Can't run tests", kvClient);
}
项目:OffIt    文件:OffIt.java   
private Retrofit getModifiedRetrofit(boolean isEnabled) {
    MockableCallAdapterFactory factory = MockableCallAdapterFactory.getInstance(context, isEnabled);

    List<CallAdapter.Factory> factories = new ArrayList<>();
    factories.add(factory);
    factories.addAll(retrofit.callAdapterFactories());

    try {
        FieldUtils.writeField(retrofitBuilder, "adapterFactories", factories, true);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    factory.setFactory(retrofit.callFactory());

    retrofit = retrofitBuilder.build();

    return retrofit;
}
项目:bobcat    文件:Bobcumber.java   
@SuppressWarnings("unchecked")
private void closeWebDriverPool() {
  try {
    Runtime runtime = (Runtime) FieldUtils.readField(this, "runtime", true);
    Collection<? extends Backend> backends =
        (Collection<? extends Backend>) FieldUtils.readField(runtime, "backends", true);
    for (Backend backend : backends) {
      if (backend instanceof JavaBackend) {
        GuiceFactory factory =
            (GuiceFactory) FieldUtils.readField(backend, "objectFactory", true);
        WebDriverRegistry webDriverRegistry = factory.getInstance(WebDriverRegistry.class);
        webDriverRegistry.shutdown();
      }
    }
  } catch (IllegalAccessException e) {
    LOG.error("unable to close web driver pool", e);
  }
}
项目:btm-DropwizardHealthChecks    文件:CassandraHealthCheckTest.java   
@Test
public void testCheckException() throws Exception {
    TestCassandraHealthCheck testCassandraHealthCheck = new TestCassandraHealthCheck(TEST_SERVER);
    testCassandraHealthCheck.cluster = testCluster;
    FieldUtils.writeField(testCassandraHealthCheck, "logger", loggerMock, true);
    Mockito.when(session.execute(Matchers.anyString())).thenThrow(new RuntimeException("crap"));
    Result result = testCassandraHealthCheck.check();

    Assert.assertFalse(result.isHealthy());
    Mockito.verify(session).close();
    Mockito.verify(session).execute(Matchers.anyString());
    Assert.assertEquals(1, testCluster.nbrTimesCloseCalled);

    ArgumentCaptor<ContextedRuntimeException> exCaptor = ArgumentCaptor.forClass(ContextedRuntimeException.class);
    Mockito.verify(loggerMock).error(Matchers.anyString(), exCaptor.capture());
    Assert.assertEquals(3, exCaptor.getValue().getContextLabels().size());
    Assert.assertEquals(result.getError(), exCaptor.getValue());
}
项目:sharding-mybatis    文件:ReflectionUtils.java   
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;  
}
项目:twitter-java-ads-sdk    文件:Resource.java   
protected String getResourcePath() {

        String id = getObjectId();
        String account_id = getAccountId();
        String resourcePath = null;

        try {

            String resource = (String) FieldUtils.readField(resourceObject, "RESOURCE", true);
            String resourceCollection = (String) FieldUtils.readField(resourceObject, "RESOURCE_COLLECTION", true);

            if (null != resourceCollection) {

                resourcePath =  (id != null) ? resource.replace("{account_id}", account_id).replace("{id}", id)
                        : resourceCollection.replace("{account_id}", account_id);
            }

        } catch (Exception e) {
            log.warn("unable to read 'RESOURCE' or 'RESOURCE_COLLECTION', errror : {}", e.toString());
            // return null;
        }
        log.info("resource path = "+resourcePath);
        return resourcePath;
    }
项目:amos-ss16-proj2    文件:MotorControllerImpl.java   
public MotorControllerImpl(PWMOutput output,
        MotorControllerConfiguration configuration) {

    this.output = output;
    this.configuration = configuration;
    this.gpio = GpioFactory.getInstance();

    try {
        Pin myGPIOMotorPin = (Pin) FieldUtils.readDeclaredStaticField(
                RaspiPin.class, configuration.gpioPin());

        motorPin = gpio.provisionDigitalOutputPin(myGPIOMotorPin,
                configuration.name(), PinState.LOW);
        motorPin.setShutdownOptions(true, PinState.LOW);

    } catch (IllegalAccessException e) {
        LOGGER.error("Error on construct MotorControllerImpl", e);
    }

}
项目:dropwizard-db-sharding-bundle    文件:LookupDao.java   
/**
 * Creates a new sharded DAO. The number of managed shards and bucketing is controlled by the {@link ShardManager}.
 *
 * @param sessionFactories a session provider for each shard
 */
public LookupDao(List<SessionFactory> sessionFactories,
                 Class<T> entityClass,
                 ShardManager shardManager,
                 BucketIdExtractor<String> bucketIdExtractor) {
    this.shardManager = shardManager;
    this.bucketIdExtractor = bucketIdExtractor;
    this.daos = sessionFactories.stream().map(LookupDaoPriv::new).collect(Collectors.toList());
    this.entityClass = entityClass;

    Field fields[] = FieldUtils.getFieldsWithAnnotation(entityClass, LookupKey.class);
    Preconditions.checkArgument(fields.length != 0, "At least one field needs to be sharding key");
    Preconditions.checkArgument(fields.length == 1, "Only one field can be sharding key");
    keyField = fields[0];
    if(!keyField.isAccessible()) {
        try {
            keyField.setAccessible(true);
        } catch (SecurityException e) {
            log.error("Error making key field accessible please use a public method and mark that as LookupKey", e);
            throw new IllegalArgumentException("Invalid class, DAO cannot be created.", e);
        }
    }
    Preconditions.checkArgument(ClassUtils.isAssignable(keyField.getType(), String.class), "Key field must be a string");
}
项目:dropwizard-db-sharding-bundle    文件:RelationalDao.java   
/**
 * Create a relational DAO.
 * @param sessionFactories List of session factories. One for each shard.
 * @param entityClass The class for which the dao will be used.
 * @param shardManager The {@link ShardManager} used to manage the bucket to shard mapping.
 */
public RelationalDao(List<SessionFactory> sessionFactories, Class<T> entityClass,
                     ShardManager shardManager, BucketIdExtractor<String> bucketIdExtractor) {
    this.shardManager = shardManager;
    this.bucketIdExtractor = bucketIdExtractor;
    this.daos = sessionFactories.stream().map(RelationalDaoPriv::new).collect(Collectors.toList());
    this.entityClass = entityClass;

    Field fields[] = FieldUtils.getFieldsWithAnnotation(entityClass, Id.class);
    Preconditions.checkArgument(fields.length != 0, "A field needs to be designated as @Id");
    Preconditions.checkArgument(fields.length == 1, "Only one field can be designated as @Id");
    keyField = fields[0];
    if(!keyField.isAccessible()) {
        try {
            keyField.setAccessible(true);
        } catch (SecurityException e) {
            log.error("Error making key field accessible please use a public method and mark that as @Id", e);
            throw new IllegalArgumentException("Invalid class, DAO cannot be created.", e);
        }
    }
}
项目:Hvalspik    文件:HvalspikRunner.java   
private void injectContainers() {
  List<Field> fields = FieldUtils.getFieldsListWithAnnotation(testClass, InjectContainer.class);
  for (Field field : fields) {
    if (!Container.class.isAssignableFrom(field.getType())) {
      continue;
    }

    InjectContainer container = field.getAnnotation(InjectContainer.class);
    Container instance = controller.getContainer(container.name(), field.getType().asSubclass(Container.class));
    LOG.info("Binding [{}] -> [{}]", container.name(), instance.getName());
    try {
      FieldUtils.writeField(field, target, instance, true);
    } catch (IllegalAccessException e) {
      throw new IllegalStateException("Could not set field:" + field.getName());
    }
  }
}
项目:orika-mapper    文件:MappingBuilder.java   
private void buildFieldMap(Map<String, MappingBean> fieldMap, Set<String> fields, Class<?> sourceClass, Class<?> destinationClass){
    for(Field field: FieldUtils.getAllFields(sourceClass)){
        fields.add(field.getName());
        Optional<FieldMapping> optional = this.getFieldMapping(field, this.destinationClass);
        if(optional.isPresent()){
            FieldMapping fieldMapping = optional.get();
            MappingBean bean = new MappingBean();
            bean.setSourceField(field.getName());
            bean.setMappedField(Strings.isNullOrEmpty(fieldMapping.value())?field.getName():fieldMapping.value());
            bean.setMappedIn(fieldMapping.mappedIn());
            bean.setMappedOut(fieldMapping.mappedOut());
            bean.setIgnore(fieldMapping.ignore());
            fieldMap.put(field.getName(),bean);
        }
    }
}
项目:ApexJorjeExample    文件:CompilerService.java   
/**
 * This is temporary workaround to bypass the validation stage of the
 * compiler while *still* doing the additional_validate stage. We are
 * bypassing the validation stage because it does a deep validation that we
 * don't have all the parts for yet in the offline compiler. Rather than
 * stop all work on that, we bypass it so that we can still do useful things
 * like find all your types, find all your methods, etc.
 * 
 */
@SuppressWarnings("unchecked")
private void callAdditionalPassVisitor(ApexCompiler compiler) {
    try {
        List<CodeUnit> allUnits = (List<CodeUnit>) FieldUtils.readDeclaredField(compiler, "allUnits", true);
        CompilerContext compilerContext = (CompilerContext) FieldUtils.readDeclaredField(compiler,
                "compilerContext", true);

        for (CodeUnit unit : allUnits) {
            Method getOperation = CompilerStage.ADDITIONAL_VALIDATE.getDeclaringClass()
                    .getDeclaredMethod("getOperation");
            getOperation.setAccessible(true);
            CompilerOperation operation = (CompilerOperation) getOperation
                    .invoke(CompilerStage.ADDITIONAL_VALIDATE);
            operation.invoke(compilerContext, unit);
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    }
}
项目:unit-testing    文件:SuperMarketTest.java   
@Test
public void testNetworkFluctuation() throws Exception {
    SuperMarket superMarket = new SuperMarket();
    HttpDiscountService mockedHttpDiscountService = mock(HttpDiscountService.class);
    FieldUtils.writeField(superMarket, "httpDiscountService", mockedHttpDiscountService, true);

    when(mockedHttpDiscountService.getDiscountFromRemoteService())
            .thenThrow(new SocketTimeoutException())
            .thenCallRealMethod();

    float price = superMarket.checkout(10);

    // 10 * 3.5 * 0.5 = 17.5
    assertEquals(price, 17.5f);
    verify(mockedHttpDiscountService, times(2)).getDiscountFromRemoteService();
}
项目:fitnesse-selenium-slim    文件:SeleniumScriptTable.java   
private void injectValueInFirstArg(List<SlimAssertion> assertions, boolean not, Object contentToCheck) {
    SlimAssertion.getInstructions(assertions).forEach(instruction -> {
        try {
            String valueToInject = FitnesseMarkup.SELECTOR_VALUE_SEPARATOR + (not ? FitnesseMarkup.SELECTOR_VALUE_DENY_INDICATOR : StringUtils.EMPTY) + contentToCheck;
            Object args = FieldUtils.readField(instruction, SeleniumScriptTable.CALL_INSTRUCTION_ARGS_FIELD, true);
            Object[] argsToInject;
            if (args instanceof Object[] && ArrayUtils.getLength(args) > NumberUtils.INTEGER_ZERO) {
                argsToInject = (Object[]) args;
                argsToInject[NumberUtils.INTEGER_ZERO] += valueToInject;
            } else {
                argsToInject = ArrayUtils.toArray(valueToInject);
            }
            String methodName = Objects.toString(FieldUtils.readField(instruction, SeleniumScriptTable.CALL_INSTRUCTION_METHODNAME_FIELD, true));
            if (Objects.isNull(MethodUtils.getAccessibleMethod(SeleniumFixture.class, Objects.toString(methodName), ClassUtils.toClass(argsToInject)))) {
                SeleniumScriptTable.LOGGER.fine("Method for instruction not found on SeleniumFixture, injection aborted: " + instruction);
                return;
            }
            FieldUtils.writeField(instruction, SeleniumScriptTable.CALL_INSTRUCTION_ARGS_FIELD, argsToInject, true);
        } catch (IllegalArgumentException | ReflectiveOperationException e) {
            SeleniumScriptTable.LOGGER.log(Level.FINE, "Failed to inject check value using reflection", e);
        }
    });
}
项目:owsi-core-parent    文件:HibernateSearchDaoImpl.java   
@Override
public Analyzer getAnalyzer(Class<?> entityType) {
    if (jpaPropertiesProvider.isHibernateSearchElasticSearchEnabled()) {
        ExtendedSearchIntegrator searchIntegrator = Search.getFullTextEntityManager(getEntityManager())
                .getSearchFactory().unwrap(ExtendedSearchIntegrator.class);
        ScopedElasticsearchAnalyzer scopedAnalyzer = (ScopedElasticsearchAnalyzer) searchIntegrator.getAnalyzerReference(entityType).getAnalyzer();

        try {
            // these properties are package protected !
            ElasticsearchAnalyzer globalAnalyzer = (ElasticsearchAnalyzer) FieldUtils.getField(ScopedElasticsearchAnalyzer.class, "globalAnalyzer", true).get(scopedAnalyzer);
            @SuppressWarnings("unchecked")
            Map<String, ElasticsearchAnalyzer> analyzers = (Map<String, ElasticsearchAnalyzer>) FieldUtils.getField(ScopedElasticsearchAnalyzer.class, "scopedAnalyzers", true).get(scopedAnalyzer);

            Map<String, Analyzer> luceneAnalyzers = Maps.newHashMap();
            for (Entry<String, ElasticsearchAnalyzer> analyzer : analyzers.entrySet()) {
                luceneAnalyzers.put(analyzer.getKey(), getAnalyzer(analyzer.getValue().getName(null)));
            }
            return new ScopedLuceneAnalyzer(getAnalyzer(globalAnalyzer.getName(null)) /* parameter is not used */, luceneAnalyzers);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("illegal access on scoped analyzer", e);
        }
    } else {
        return Search.getFullTextEntityManager(getEntityManager()).getSearchFactory().unwrap(SearchIntegrator.class).getAnalyzer(entityType);
    }
}
项目:lmis-moz-mobile    文件:BaseViewHolder.java   
private void prepareFields() {
    viewsForInjection = new ArrayList<>();
    for (Field field : FieldUtils.getAllFields(this.getClass())) {
        if (field.isAnnotationPresent(InjectView.class)) {
            viewsForInjection.add(new ViewMembersInjector(field, field.getAnnotation(InjectView.class)));
        }
    }
}
项目:dolphin    文件:CommentsWavePlugin.java   
@Override
public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
  try {
    // use reflect to fix the root comment
    Document document = (Document) FieldUtils.readDeclaredField(sqlMap, "document", true);
    ExtendedDocument extendedDocument = new ExtendedDocument(document);
    FieldUtils.writeDeclaredField(sqlMap, "document", extendedDocument, true);
    if (context.getCommentGenerator() instanceof CommentGenerator) {
      CommentGenerator cg = (CommentGenerator) context.getCommentGenerator();
      cg.addSqlMapFileComment(extendedDocument);
    }
  } catch (IllegalAccessException e) {
    e.printStackTrace();
  }
  return true;
}
项目:dolphin    文件:ColumnNameConversionPlugin.java   
@SuppressWarnings("unchecked")
protected void convertUseReflect(IntrospectedTable introspectedTable) {
  if (baseColumnsField == null || blobColumnsField == null) {
    baseColumnsField = FieldUtils.getField(IntrospectedTable.class, "baseColumns", true);
    blobColumnsField = FieldUtils.getField(IntrospectedTable.class, "blobColumns", true);
  }
  List<IntrospectedColumn> introspectedColumns = null;
  try {
    introspectedColumns = (List<IntrospectedColumn>) baseColumnsField.get(introspectedTable);
    convertForAll(introspectedColumns);
    //print("after calculate for base", introspectedColumns);
    baseColumnsField.set(introspectedTable, introspectedColumns);
    introspectedColumns = (List<IntrospectedColumn>) blobColumnsField.get(introspectedTable);
    convertForAll(introspectedColumns);
    //print("after calculate for blob", introspectedColumns);
    blobColumnsField.set(introspectedTable, introspectedColumns);

  } catch (IllegalArgumentException | IllegalAccessException e) {
    e.printStackTrace();
  }
}
项目:dolphin    文件:PostgisGeoPlugin.java   
@Override
public boolean validate(List<String> warnings) {
    boolean valid = true;
    srid = properties.getProperty(SRID_NAME);
    if(StringUtils.isEmpty(srid)){
        srid = "3857";
    }
    if(connection == null){
        try {
            connection = ConnectionFactory.getInstance().getConnection(context.getJdbcConnectionConfiguration());
        } catch (SQLException e) {
            e.printStackTrace();
            valid = false;
        }   
    }
    elementsList = FieldUtils.getField(XmlElement.class, "elements", true);
    return valid;
}
项目:dolphin    文件:PostgisGeoPlugin.java   
protected void checkAndReplaceInput(List<IntrospectedColumn> columns, TextElement te) {
  String sql = te.getContent();
  for(IntrospectedColumn column : columns){
    if(column.getFullyQualifiedJavaType().getShortName().equals("Geometry")){
        String paramStr = MyBatis3FormattingUtilities.getParameterClause(column);
        sql = StringUtils.replace(sql, paramStr, "ST_GeomFromText(" + paramStr + ","+srid+")"); //replace no prefix geo relate column
        paramStr = MyBatis3FormattingUtilities.getParameterClause(column, "record.");
        sql = StringUtils.replace(sql, paramStr, "ST_GeomFromText(" + paramStr + ","+srid+")"); //replace mbg generate prefix geo relate column
        paramStr = MyBatis3FormattingUtilities.getParameterClause(column, "item.");
        sql = StringUtils.replace(sql, paramStr, "ST_GeomFromText(" + paramStr + ","+srid+")"); //replace mbg batch plugin generate prefix geo relate column                
//              System.out.println();
//              System.out.println(sql);
    }
  }
  try {
    FieldUtils.writeDeclaredField(te, "content", sql, true);
  } catch (IllegalAccessException e) {
    e.printStackTrace();
  }
}
项目:dolphin    文件:PostgisGeoPlugin.java   
protected void checkAndReplaceOutput(List<IntrospectedColumn> columns, TextElement te) {
    String sql = te.getContent();
        for(IntrospectedColumn column : columns){
            if(column.getFullyQualifiedJavaType().getShortName().equals("Geometry")){
                String columnStr = null;
                if(column.isColumnNameDelimited()){
                    columnStr = "\""+column.getActualColumnName()+"\"";
                }else{
                    columnStr = column.getActualColumnName();
                }
                sql = StringUtils.replaceOnce(sql, columnStr, "ST_AsText("+columnStr+") as " + columnStr);
                //sql = sql.replace(column.getActualColumnName(), "ST_AsText("+column.getActualColumnName()+")");
//              System.out.println();
//              System.out.println(sql);
            }
        }
    try {
      FieldUtils.writeDeclaredField(te, "content", sql, true);
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }       
  }
项目:psi-probe    文件:DefaultAccessor.java   
/**
 * Gets the property.
 *
 * @param obj the obj
 * @param name the name
 * @param defaultValue the default value
 * @param forced whether or not to force access to the field
 * @return the property
 */
protected Object getProperty(Object obj, String name, Object defaultValue, boolean forced) {
  try {
    if (forced) {
      return FieldUtils.readField(obj, name, forced);
    } else {
      return PropertyUtils.isReadable(obj, name) ? PropertyUtils.getProperty(obj, name)
          : defaultValue;
    }
  } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException
      | NoSuchMethodException e) {
    logger.error("", e);
  }
  logger.debug("Could not access property '{}' of object '{}'", name, obj);
  return defaultValue;
}