List of usage examples for org.springframework.beans DirectFieldAccessor setPropertyValue
@Override public void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException
From source file:org.opencredo.cloud.storage.s3.JetS3TemplateTest.java
@Before public void before() { template = new JetS3Template(credentials, TestPropertiesAccessor.getDefaultContainerName()); s3Service = mock(S3Service.class); DirectFieldAccessor accessor = new DirectFieldAccessor(template); accessor.setPropertyValue("s3Service", s3Service); }
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); }// w w w . jav a 2 s .co 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
@Override public void setFieldValue(String fieldName, Object value) { try {//from w w w .j a v a2s. com if (fieldName.contains(".")) { DirectFieldAccessor partAccesor = getPartAccessor(StringUtil.getNamespace(fieldName)); partAccesor.setPropertyValue(getFieldPojoName(fieldName), value); } else { directFieldAccessor.setPropertyValue(getFieldPojoName(fieldName), value); } if (logger.isDebugEnabled()) { String message = MessageFormat.format("Field {0} was set with value \"{1}\"", fieldName, value); logger.trace(message); } } catch (Exception e) { logger.fatal(MessageFormat.format("Unable to update entity field: {0}.{1}", target.getClass().getSimpleName(), fieldName, e)); return; } }
From source file:org.openlegacy.terminal.utils.SimplePojoFieldAccessor.java
public void setPartFieldValue(String nameSpace, String fieldName, Object value) { if (nameSpace.contains(".")) { String parentFullPath = StringUtil.getNamespace(nameSpace); DirectFieldAccessor partAccessor = getPartAccessor(parentFullPath); try {//from www .j ava2 s. c o m partAccessor.setPropertyValue(fieldName, value); } catch (Exception e) { logger.error(MessageFormat.format("Unable to update entity part {2} field: {0}.{1}", target.getClass().getSimpleName(), fieldName, nameSpace, e)); return; } if (logger.isDebugEnabled()) { if (value instanceof String) { String message = MessageFormat.format("Field {0} was set with value \"{1}\"", fieldName, value); if (!StringUtils.isEmpty(((String) value))) { logger.debug(message); } else { // print empty value assignment only in trace mode logger.trace(message); } } else { String message = MessageFormat.format("Field {0} was set with value \"{1}\"", fieldName, value); logger.debug(message); } } } else { setFieldValue(fieldName, value); } }
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 .j av a 2s . 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 v a2s. c o 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.listener.SimpleMessageListenerContainerIntegration2Tests.java
@Test public void testDeleteOneQueue() throws Exception { CountDownLatch latch = new CountDownLatch(20); container = createContainer(new MessageListenerAdapter(new PojoListener(latch)), queue.getName(), queue1.getName());/*from w ww.ja va2s. co m*/ container.setFailedDeclarationRetryInterval(100); ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); container.setApplicationEventPublisher(publisher); for (int i = 0; i < 10; i++) { template.convertAndSend(queue.getName(), i + "foo"); template.convertAndSend(queue1.getName(), i + "foo"); } boolean waited = latch.await(10, TimeUnit.SECONDS); assertTrue("Timed out waiting for message", waited); Map<?, ?> consumers = TestUtils.getPropertyValue(container, "consumers", Map.class); BlockingQueueConsumer consumer = (BlockingQueueConsumer) consumers.keySet().iterator().next(); admin.deleteQueue(queue1.getName()); latch = new CountDownLatch(10); container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch))); for (int i = 0; i < 10; i++) { template.convertAndSend(queue.getName(), i + "foo"); } waited = latch.await(10, TimeUnit.SECONDS); assertTrue("Timed out waiting for message", waited); BlockingQueueConsumer newConsumer = consumer; int n = 0; while (n++ < 100 && newConsumer == consumer) { try { newConsumer = (BlockingQueueConsumer) consumers.keySet().iterator().next(); if (newConsumer == consumer) { break; } } catch (NoSuchElementException e) { // race; hasNext() won't help } Thread.sleep(100); } assertTrue("Failed to restart consumer", n < 100); Set<?> missingQueues = TestUtils.getPropertyValue(newConsumer, "missingQueues", Set.class); n = 0; while (n++ < 100 && missingQueues.size() == 0) { Thread.sleep(200); } assertTrue("Failed to detect missing queue", n < 100); ArgumentCaptor<ListenerContainerConsumerFailedEvent> captor = ArgumentCaptor .forClass(ListenerContainerConsumerFailedEvent.class); verify(publisher).publishEvent(captor.capture()); ListenerContainerConsumerFailedEvent event = captor.getValue(); assertThat(event.getThrowable(), instanceOf(ConsumerCancelledException.class)); assertFalse(event.isFatal()); DirectFieldAccessor dfa = new DirectFieldAccessor(newConsumer); dfa.setPropertyValue("lastRetryDeclaration", 0); dfa.setPropertyValue("retryDeclarationInterval", 100); admin.declareQueue(queue1); n = 0; while (n++ < 100 && missingQueues.size() > 0) { Thread.sleep(100); } assertTrue("Failed to redeclare missing queue", n < 100); latch = new CountDownLatch(20); container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch))); for (int i = 0; i < 10; i++) { template.convertAndSend(queue.getName(), i + "foo"); template.convertAndSend(queue1.getName(), i + "foo"); } waited = latch.await(10, TimeUnit.SECONDS); assertTrue("Timed out waiting for message", waited); assertNull(template.receiveAndConvert(queue.getName())); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerIntegration2Tests.java
@Test public void testRestartConsumerOnBasicQosIoException() throws Exception { this.template.convertAndSend(queue.getName(), "foo"); ConnectionFactory connectionFactory = new SingleConnectionFactory("localhost", BrokerTestUtils.getPort()); final AtomicBoolean networkGlitch = new AtomicBoolean(); class MockChannel extends PublisherCallbackChannelImpl { MockChannel(Channel delegate) { super(delegate); }// www . ja v a 2s . c o m @Override public void basicQos(int prefetchCount) throws IOException { if (networkGlitch.compareAndSet(false, true)) { throw new IOException("Intentional connection reset"); } super.basicQos(prefetchCount); } } Connection connection = spy(connectionFactory.createConnection()); when(connection.createChannel(anyBoolean())) .then(invocation -> new MockChannel((Channel) invocation.callRealMethod())); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); dfa.setPropertyValue("connection", connection); CountDownLatch latch = new CountDownLatch(1); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch))); container.setQueueNames(queue.getName()); container.setRecoveryInterval(500); container.afterPropertiesSet(); container.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertTrue(networkGlitch.get()); container.stop(); ((DisposableBean) connectionFactory).destroy(); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerIntegration2Tests.java
@Test public void testRestartConsumerOnConnectionLossDuringQueueDeclare() throws Exception { this.template.convertAndSend(queue.getName(), "foo"); ConnectionFactory connectionFactory = new CachingConnectionFactory("localhost", BrokerTestUtils.getPort()); final AtomicBoolean networkGlitch = new AtomicBoolean(); class MockChannel extends PublisherCallbackChannelImpl { MockChannel(Channel delegate) { super(delegate); }/*from w ww .ja va 2 s .c o m*/ @Override public DeclareOk queueDeclarePassive(String queue) throws IOException { if (networkGlitch.compareAndSet(false, true)) { getConnection().close(); throw new IOException("Intentional connection reset"); } return super.queueDeclarePassive(queue); } } Connection connection = spy(connectionFactory.createConnection()); when(connection.createChannel(anyBoolean())) .then(invocation -> new MockChannel((Channel) invocation.callRealMethod())); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); dfa.setPropertyValue("connection", connection); CountDownLatch latch = new CountDownLatch(1); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); container.setMessageListener(new MessageListenerAdapter(new PojoListener(latch))); container.setQueueNames(queue.getName()); container.setRecoveryInterval(500); container.afterPropertiesSet(); container.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertTrue(networkGlitch.get()); container.stop(); ((DisposableBean) connectionFactory).destroy(); }
From source file:org.springframework.data.solr.test.util.EmbeddedSolrServer.java
@SuppressWarnings("serial") public SolrClient getSolrClient(String collectionName) { if (ClientCache.ENABLED.equals(clientCache) && cachedClients.containsKey(collectionName)) { return cachedClients.get(collectionName); }/*ww w. ja va 2 s . c o m*/ org.apache.solr.client.solrj.embedded.EmbeddedSolrServer solrServer = new org.apache.solr.client.solrj.embedded.EmbeddedSolrServer( coreContainer, collectionName) { public void shutdown() { // ignore close at this point. CoreContainer will be shut down on its own. } @Override public void close() { shutdown(); } }; final DirectFieldAccessor dfa = new DirectFieldAccessor(solrServer); dfa.setPropertyValue("_parser", new HttpMethodGuessingSolrRequestParsers()); if (ClientCache.ENABLED.equals(clientCache)) { cachedClients.put(collectionName, solrServer); } return solrServer; }