Example usage for org.springframework.beans DirectFieldAccessor DirectFieldAccessor

List of usage examples for org.springframework.beans DirectFieldAccessor DirectFieldAccessor

Introduction

In this page you can find the example usage for org.springframework.beans DirectFieldAccessor DirectFieldAccessor.

Prototype

public DirectFieldAccessor(Object object) 

Source Link

Document

Create a new DirectFieldAccessor for the given object.

Usage

From source file:org.openlegacy.rpc.support.binders.RpcPartsBinder.java

private void populateEntityDeep(String namespace, RpcPartEntityDefinition rpcPartEntityDefinition,
        SimpleRpcPojoFieldAccessor fieldAccesor, List<RpcField> rpcFields) {
    Map<String, RpcFieldDefinition> fieldsDefinitions = rpcPartEntityDefinition.getFieldsDefinitions();

    DirectFieldAccessor partAccesor = fieldAccesor.getPartAccessor(namespace);

    int order = rpcPartEntityDefinition.getOrder();
    int count = rpcPartEntityDefinition.getCount();
    if (count == 1) {
        if (partAccesor == null) {
            fieldAccesor.setPartFieldValue(namespace, rpcPartEntityDefinition.getPartName(),
                    ReflectionUtil.newInstance(rpcPartEntityDefinition.getPartClass()));
            partAccesor = fieldAccesor.getPartAccessor(namespace);
        }/*www.j  a  v  a2s  . c o m*/
        RpcStructureField structureField = (RpcStructureField) rpcFields.get(order);
        List<RpcField> rpcInnerFields = structureField.getChildrens();
        for (RpcFieldDefinition fieldDefinition : fieldsDefinitions.values()) {
            int inerOrder = structureField.getFieldRelativeOrder(fieldDefinition.getOrder());

            String name = StringUtil.removeNamespace(fieldDefinition.getName());
            Object value = ((RpcFlatField) rpcInnerFields.get(inerOrder)).getValue();
            if (value != null) {
                Object apiValue = bindFieldToApi(fieldDefinition, value);
                partAccesor.setPropertyValue(name, apiValue);
            }
        }
        Map<String, RpcPartEntityDefinition> innerPartDefinition = rpcPartEntityDefinition
                .getInnerPartsDefinitions();

        for (RpcPartEntityDefinition innerRpcPartEntityDefinition : innerPartDefinition.values()) {
            populateEntityDeep(namespace + "." + innerRpcPartEntityDefinition.getPartName(),
                    innerRpcPartEntityDefinition, fieldAccesor, rpcInnerFields);
        }
    } else {
        if (partAccesor == null) {
            fieldAccesor.setPartFieldValue(namespace, rpcPartEntityDefinition.getPartName(),
                    ReflectionUtil.newListInstance(rpcPartEntityDefinition.getPartClass(), count));
            partAccesor = fieldAccesor.getPartAccessor(namespace);
        }
        RpcStructureListField structureListField = (RpcStructureListField) rpcFields.get(order);

        List<RpcFields> rpcInnerFields = structureListField.getChildrens();

        Object[] objects;
        Object currentObject = fieldAccesor.getPartFieldValue(namespace, rpcPartEntityDefinition.getPartName());
        if (currentObject.getClass().isArray()) {
            objects = (Object[]) currentObject;
        } else {
            objects = ((List<?>) currentObject).toArray();
        }

        List<Integer> nullObjects = new ArrayList<Integer>();
        for (Integer i = 0; i < count; i++) {
            List<RpcField> rpcCurrentFields = rpcInnerFields.get(i).getFields();
            DirectFieldAccessor innerFieldAccessor = new DirectFieldAccessor(objects[i]);
            for (RpcFieldDefinition fieldDefinition : fieldsDefinitions.values()) {
                int inerOrder = fieldDefinition.getOrder();
                String name = StringUtil.removeNamespace(fieldDefinition.getName());
                Object value = ((RpcFlatField) rpcCurrentFields.get(inerOrder)).getValue();
                if (fieldDefinition.isKey() && fieldDefinition.getNullValue().equals(value)) {
                    nullObjects.add(i);
                    continue;
                }

                innerFieldAccessor.setPropertyValue(name, bindFieldToApi(fieldDefinition, value));
            }
            Map<String, RpcPartEntityDefinition> innerPartDefinition = rpcPartEntityDefinition
                    .getInnerPartsDefinitions();

            for (RpcPartEntityDefinition innerRpcPartEntityDefinition : innerPartDefinition.values()) {
                populateEntityDeep(namespace + "." + innerRpcPartEntityDefinition.getPartName(),
                        innerRpcPartEntityDefinition, new SimpleRpcPojoFieldAccessor(objects[i]),
                        rpcCurrentFields);
            }
        }
        filterNullObjects(namespace, rpcPartEntityDefinition.getPartName(), fieldAccesor, objects, nullObjects);

    }

}

From source file:org.openlegacy.terminal.utils.SimplePojoFieldAccessor.java

public SimplePojoFieldAccessor(Object target) {
    target = ProxyUtil.getTargetObject(target);
    directFieldAccessor = new DirectFieldAccessor(target);
    this.target = target;
}

From source file:org.openlegacy.terminal.utils.SimplePojoFieldAccessor.java

public DirectFieldAccessor getPartAccessor(String partName) {
    DirectFieldAccessor partAccessor = null;
    if (partAccessors != null) {
        partAccessor = partAccessors.get(partName);

    }/*from w w  w .j  a v a2  s .  c  o  m*/
    if (partAccessor == null) {
        DirectFieldAccessor parent = directFieldAccessor;
        if (partName.contains(".")) {
            parent = getPartAccessor(StringUtil.getNamespace(partName));
        }
        if (parent == null) {
            return null;
        }
        partName = StringUtil.removeNamespace(partName);
        if (!parent.isReadableProperty(partName)) {
            return directFieldAccessor;
        }
        Object object = parent.getPropertyValue(partName);
        if (object != null) {
            partAccessor = new DirectFieldAccessor(object);
            if (partAccessors == null) {
                partAccessors = new HashMap<String, DirectFieldAccessor>();
            }
            partAccessors.put(partName, partAccessor);
        } else {
            return null;
        }

    }
    return partAccessor;
}

From source file:org.openlegacy.utils.ProxyUtil.java

@SuppressWarnings("unchecked")
public static <T> T getTargetObject(Object proxy, boolean deep) {

    if (proxy == null) {
        return null;
    }/*from   ww w . ja v  a 2  s .  c o m*/

    while (proxy instanceof Advised) {
        try {
            if (deep) {
                // invoke all getters
                PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(proxy);
                for (PropertyDescriptor propertyDescriptor : properties) {
                    try {
                        Class<?> propertyType = propertyDescriptor.getPropertyType();
                        if (propertyType != null && !TypesUtil.isPrimitive(propertyType)) {
                            Method readMethod = propertyDescriptor.getReadMethod();
                            if (readMethod != null) {
                                readMethod.invoke(proxy);
                            }
                        }
                    } catch (Exception e) {
                        throw (new RuntimeException(e));
                    }
                }
            }
            proxy = ((Advised) proxy).getTargetSource().getTarget();
        } catch (Exception e) {
            throw (new IllegalStateException(e));
        }
    }

    if (deep) {
        DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(proxy);
        PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(proxy);
        for (PropertyDescriptor propertyDescriptor : properties) {
            try {
                Object value = propertyDescriptor.getReadMethod().invoke(proxy);
                Object afterValue = getTargetObject(value, false);
                if (value != afterValue) {
                    fieldAccessor.setPropertyValue(propertyDescriptor.getName(), afterValue);
                }
            } catch (Exception e) {
                throw (new RuntimeException(e));
            }
        }
    }
    return (T) proxy;
}

From source file:org.openlegacy.utils.XmlSerializationUtil.java

/**
 * This method purpose is to reduce the amount of XML written when serializing an object It reset member to null when the
 * default value matches the object value
 * /*  ww w  .  j  a va 2  s  . co  m*/
 * @param source
 */
private static void resetDefaultValues(Object source) {
    DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(source);
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(source);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String propertyName = propertyDescriptor.getName();
        Class<?> propertyType = fieldAccessor.getPropertyType(propertyName);
        if (propertyType == null || Collection.class.isAssignableFrom(propertyType)
                || Map.class.isAssignableFrom(propertyType)) {
            continue;
        }
        Object defaultValue = PropertyUtil.getPropertyDefaultValue(source.getClass(), propertyName);
        Object value = fieldAccessor.getPropertyValue(propertyName);
        if (fieldAccessor.isWritableProperty(propertyName) && ObjectUtils.equals(value, defaultValue)
                && !propertyType.isPrimitive()) {
            fieldAccessor.setPropertyValue(propertyName, null);
        }

    }
}

From source file:org.springframework.amqp.rabbit.connection.AbstractConnectionFactoryTests.java

@Test
public void testWithListener() throws Exception {

    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class);

    when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString()))
            .thenReturn(mockConnection);

    final AtomicInteger called = new AtomicInteger(0);
    AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory);
    connectionFactory.setConnectionListeners(Collections.singletonList(new ConnectionListener() {

        @Override//from   w w  w .j av a 2 s  .c  om
        public void onCreate(Connection connection) {
            called.incrementAndGet();
        }

        @Override
        public void onClose(Connection connection) {
            called.decrementAndGet();
        }

    }));

    Log logger = spy(TestUtils.getPropertyValue(connectionFactory, "logger", Log.class));
    doReturn(true).when(logger).isInfoEnabled();
    new DirectFieldAccessor(connectionFactory).setPropertyValue("logger", logger);
    Connection con = connectionFactory.createConnection();
    assertEquals(1, called.get());
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(logger).info(captor.capture());
    assertThat(captor.getValue(), containsString("Created new connection: SimpleConnection"));

    con.close();
    assertEquals(1, called.get());
    verify(mockConnection, never()).close(anyInt());

    connectionFactory.createConnection();
    assertEquals(1, called.get());

    connectionFactory.destroy();
    assertEquals(0, called.get());
    verify(mockConnection, atLeastOnce()).close(anyInt());

    verify(mockConnectionFactory, times(1)).newConnection(any(ExecutorService.class), anyString());

}

From source file:org.springframework.amqp.rabbit.connection.LocalizedQueueConnectionFactoryTests.java

@SuppressWarnings("unchecked")
@Test//from   w w w  . j a  v a 2s  .  c  o  m
public void testFailOver() throws Exception {
    ConnectionFactory defaultConnectionFactory = mockCF("localhost:1234", null);
    String rabbit1 = "localhost:1235";
    String rabbit2 = "localhost:1236";
    String[] addresses = new String[] { rabbit1, rabbit2 };
    String[] adminUris = new String[] { "http://localhost:11235", "http://localhost:11236" };
    String[] nodes = new String[] { "rabbit@foo", "rabbit@bar" };
    String vhost = "/";
    String username = "guest";
    String password = "guest";
    final AtomicBoolean firstServer = new AtomicBoolean(true);
    final Client client1 = doCreateClient(adminUris[0], username, password, nodes[0]);
    final Client client2 = doCreateClient(adminUris[1], username, password, nodes[1]);
    final Map<String, ConnectionFactory> mockCFs = new HashMap<String, ConnectionFactory>();
    CountDownLatch latch1 = new CountDownLatch(1);
    CountDownLatch latch2 = new CountDownLatch(1);
    mockCFs.put(rabbit1, mockCF(rabbit1, latch1));
    mockCFs.put(rabbit2, mockCF(rabbit2, latch2));
    LocalizedQueueConnectionFactory lqcf = new LocalizedQueueConnectionFactory(defaultConnectionFactory,
            addresses, adminUris, nodes, vhost, username, password, false, null) {

        @Override
        protected Client createClient(String adminUri, String username, String password)
                throws MalformedURLException, URISyntaxException {
            return firstServer.get() ? client1 : client2;
        }

        @Override
        protected ConnectionFactory createConnectionFactory(String address, String node) throws Exception {
            return mockCFs.get(address);
        }

    };
    Log logger = spy(TestUtils.getPropertyValue(lqcf, "logger", Log.class));
    doReturn(true).when(logger).isInfoEnabled();
    new DirectFieldAccessor(lqcf).setPropertyValue("logger", logger);
    doAnswer(new CallsRealMethods()).when(logger).debug(anyString());
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(lqcf);
    container.setQueueNames("q");
    container.afterPropertiesSet();
    container.start();
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    Channel channel = this.channels.get(rabbit1);
    assertNotNull(channel);
    verify(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(),
            Matchers.any(Consumer.class));
    verify(logger, atLeast(1)).info(captor.capture());
    assertTrue(assertLog(captor.getAllValues(), "Queue: q is on node: rabbit@foo at: localhost:1235"));

    // Fail rabbit1 and verify the container switches to rabbit2

    firstServer.set(false);
    this.consumers.get(rabbit1).handleCancel(consumerTags.get(rabbit1));
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    channel = this.channels.get(rabbit2);
    assertNotNull(channel);
    verify(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(),
            Matchers.any(Consumer.class));
    container.stop();
    verify(logger, atLeast(1)).info(captor.capture());
    assertTrue(assertLog(captor.getAllValues(), "Queue: q is on node: rabbit@bar at: localhost:1236"));
}

From source file:org.springframework.amqp.rabbit.connection.SSLConnectionTests.java

@Test
public void testAlgNoProps() throws Exception {
    RabbitConnectionFactoryBean fb = new RabbitConnectionFactoryBean();
    ConnectionFactory rabbitCf = spy(//from   w w w.j ava 2  s  . c o m
            TestUtils.getPropertyValue(fb, "connectionFactory", ConnectionFactory.class));
    new DirectFieldAccessor(fb).setPropertyValue("connectionFactory", rabbitCf);
    fb.setUseSSL(true);
    fb.setSslAlgorithm("TLSv1.2");
    fb.afterPropertiesSet();
    fb.getObject();
    verify(rabbitCf).useSslProtocol("TLSv1.2");
}

From source file:org.springframework.amqp.rabbit.connection.SSLConnectionTests.java

@Test
public void testNoAlgNoProps() throws Exception {
    RabbitConnectionFactoryBean fb = new RabbitConnectionFactoryBean();
    ConnectionFactory rabbitCf = spy(//from w  w  w .ja  v  a2 s  .co  m
            TestUtils.getPropertyValue(fb, "connectionFactory", ConnectionFactory.class));
    new DirectFieldAccessor(fb).setPropertyValue("connectionFactory", rabbitCf);
    fb.setUseSSL(true);
    fb.afterPropertiesSet();
    fb.getObject();
    verify(rabbitCf).useSslProtocol();
}

From source file:org.springframework.amqp.rabbit.connection.SSLConnectionTests.java

@Test
public void testKSTS() throws Exception {
    RabbitConnectionFactoryBean fb = new RabbitConnectionFactoryBean();
    Log logger = spy(TestUtils.getPropertyValue(fb, "logger", Log.class));
    given(logger.isDebugEnabled()).willReturn(true);
    new DirectFieldAccessor(fb).setPropertyValue("logger", logger);
    fb.setUseSSL(true);/*www.j  a va  2  s  .co m*/
    fb.setKeyStoreType("JKS");
    fb.setKeyStoreResource(new ClassPathResource("test.ks"));
    fb.setKeyStorePassphrase("secret");
    fb.setTrustStoreResource(new ClassPathResource("test.truststore.ks"));
    fb.setKeyStorePassphrase("secret");
    fb.setSecureRandom(SecureRandom.getInstanceStrong());
    fb.afterPropertiesSet();
    fb.getObject();
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(logger).debug(captor.capture());
    final String log = captor.getValue();
    assertThat(log, allOf(containsString("KM: ["), containsString("TM: ["), containsString("random: java.")));
}