List of usage examples for org.springframework.util ReflectionUtils setField
public static void setField(Field field, @Nullable Object target, @Nullable Object value)
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
@Test(expected = IllegalArgumentException.class) public void getTokenEndpoint_Fails_If_Issuer_Is_Wrong() throws Exception { Field field = UaaTokenServices.class.getDeclaredField("issuer"); field.setAccessible(true);/*from w w w .j a v a2 s.co m*/ ReflectionUtils.setField(field, tokenServices, "adasdas"); tokenServices.getTokenEndpoint(); }
From source file:org.orcid.api.common.writer.citeproc.WorkToCiteprocTranslator.java
/** * Extract the bibtex and turn into CSL Adds in DOI and URL from metadata if * missing Horrible use of reflection to shorten hyperauthorship. It will * strip anything above 20 authors down to the primary author and 'et all'. * //w w w.jav a2 s . c o m * @param work * @param abreviate * @return */ private CSLItemData translateFromBibtexCitation(Work work, boolean abreviate) { try { System.out.println("----"); System.out.println(work.getWorkCitation().getCitation()); System.out.println("----"); BibTeXConverter conv = new BibTeXConverter(); BibTeXDatabase db = conv.loadDatabase(IOUtils.toInputStream(work.getWorkCitation().getCitation())); Map<String, CSLItemData> cids = conv.toItemData(db); if (cids.size() == 1) { CSLItemData item = cids.values().iterator().next(); // FOR REASONS UNKNOWN, CITEPROC WILL SOMETIMES generate // multiple authors not a literal. if (abreviate) { if (item.getAuthor().length > 20) { CSLName[] abrev = Arrays.copyOf(item.getAuthor(), 1); abrev[0] = new CSLNameBuilder() .literal(abrev[0].getGiven() + " " + abrev[0].getFamily() + " " + "et all.") .build(); ReflectionUtils.makeAccessible(authorField); ReflectionUtils.setField(authorField, item, abrev); } for (int i = 0; i < item.getAuthor().length; i++) { if (item.getAuthor()[i].getLiteral() != null && item.getAuthor()[i].getLiteral().length() > 200) { ReflectionUtils.makeAccessible(literalField); ReflectionUtils.setField(literalField, item.getAuthor()[i], StringUtils.abbreviate(item.getAuthor()[i].getLiteral(), 200)); } } } if (item.getDOI() == null) { String doi = extractID(work, WorkExternalIdentifierType.DOI); if (doi != null) { ReflectionUtils.makeAccessible(doiField); ReflectionUtils.setField(doiField, item, doi); } } if (item.getURL() == null) { if (extractID(work, WorkExternalIdentifierType.URI) != null) { ReflectionUtils.makeAccessible(urlField); ReflectionUtils.setField(urlField, item, extractID(work, WorkExternalIdentifierType.URI)); } else if (item.getDOI() != null) { ReflectionUtils.makeAccessible(urlField); ReflectionUtils.setField(urlField, item, item.getDOI()); } else if (extractID(work, WorkExternalIdentifierType.HANDLE) != null) { ReflectionUtils.makeAccessible(urlField); ReflectionUtils.setField(urlField, item, extractID(work, WorkExternalIdentifierType.HANDLE)); } } return item; } else throw new ParseException("Invalid Citation count"); } catch (IOException | ParseException e) { return null; } }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java
@Test public void testAtomicSendAndReceiveExternalExecutor() throws Exception { CachingConnectionFactory connectionFactory = new CachingConnectionFactory(); ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor(); final String execName = "make-sure-exec-passed-in"; exec.setBeanName(execName);/* w ww . j a v a2s . c om*/ exec.afterPropertiesSet(); connectionFactory.setExecutor(exec); final Field[] fields = new Field[1]; ReflectionUtils.doWithFields(RabbitTemplate.class, new FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { field.setAccessible(true); fields[0] = field; } }, new FieldFilter() { public boolean matches(Field field) { return field.getName().equals("logger"); } }); Log logger = Mockito.mock(Log.class); when(logger.isTraceEnabled()).thenReturn(true); final AtomicBoolean execConfiguredOk = new AtomicBoolean(); doAnswer(new Answer<Object>() { public Object answer(InvocationOnMock invocation) throws Throwable { String log = (String) invocation.getArguments()[0]; if (log.startsWith("Message received") && Thread.currentThread().getName().startsWith(execName)) { execConfiguredOk.set(true); } return null; } }).when(logger).trace(Mockito.anyString()); final RabbitTemplate template = new RabbitTemplate(connectionFactory); ReflectionUtils.setField(fields[0], template, logger); template.setRoutingKey(ROUTE); template.setQueue(ROUTE); ExecutorService executor = Executors.newFixedThreadPool(1); // Set up a consumer to respond to our producer Future<Message> received = executor.submit(new Callable<Message>() { public Message call() throws Exception { Message message = null; for (int i = 0; i < 10; i++) { message = template.receive(); if (message != null) { break; } Thread.sleep(100L); } assertNotNull("No message received", message); template.send(message.getMessageProperties().getReplyTo(), message); return message; } }); Message message = new Message("test-message".getBytes(), new MessageProperties()); Message reply = template.sendAndReceive(message); assertEquals(new String(message.getBody()), new String(received.get(1000, TimeUnit.MILLISECONDS).getBody())); assertNotNull("Reply is expected", reply); assertEquals(new String(message.getBody()), new String(reply.getBody())); // Message was consumed so nothing left on queue reply = template.receive(); assertEquals(null, reply); assertTrue(execConfiguredOk.get()); }
From source file:org.springframework.boot.devtools.autoconfigure.HateoasObjenesisCacheDisabler.java
private void removeObjenesisCache(Class<?> dummyInvocationUtils) { try {//w ww . j a v a 2 s . c o m Field objenesisField = ReflectionUtils.findField(dummyInvocationUtils, "OBJENESIS"); if (objenesisField != null) { ReflectionUtils.makeAccessible(objenesisField); Object objenesis = ReflectionUtils.getField(objenesisField, null); Field cacheField = ReflectionUtils.findField(objenesis.getClass(), "cache"); ReflectionUtils.makeAccessible(cacheField); ReflectionUtils.setField(cacheField, objenesis, null); } } catch (Exception ex) { logger.warn("Failed to disable Spring HATEOAS's Objenesis cache. ClassCastExceptions may occur", ex); } }
From source file:org.springframework.cloud.deployer.thin.ThinJarAppWrapper.java
private void setField(Class<?> type, String name, Object value) { Field field = ReflectionUtils.findField(type, name); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, null, value); }
From source file:org.springframework.integration.amqp.config.AmqpOutboundChannelAdapterParserTests.java
@Test public void withHeaderMapperCustomHeaders() { Object eventDrivenConsumer = context.getBean("withHeaderMapperCustomHeaders"); AmqpOutboundEndpoint endpoint = TestUtils.getPropertyValue(eventDrivenConsumer, "handler", AmqpOutboundEndpoint.class); assertNotNull(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")); assertFalse(TestUtils.getPropertyValue(endpoint, "lazyConnect", Boolean.class)); assertEquals("42", TestUtils .getPropertyValue(endpoint, "delayExpression", org.springframework.expression.Expression.class) .getExpressionString());/*from w w w. ja v a 2 s .co m*/ Field amqpTemplateField = ReflectionUtils.findField(AmqpOutboundEndpoint.class, "amqpTemplate"); amqpTemplateField.setAccessible(true); RabbitTemplate amqpTemplate = TestUtils.getPropertyValue(endpoint, "amqpTemplate", RabbitTemplate.class); amqpTemplate = Mockito.spy(amqpTemplate); final AtomicBoolean shouldBePersistent = new AtomicBoolean(); Mockito.doAnswer(invocation -> { Object[] args = invocation.getArguments(); org.springframework.amqp.core.Message amqpMessage = (org.springframework.amqp.core.Message) args[2]; MessageProperties properties = amqpMessage.getMessageProperties(); assertEquals("foo", properties.getHeaders().get("foo")); assertEquals("foobar", properties.getHeaders().get("foobar")); assertNull(properties.getHeaders().get("bar")); assertEquals( shouldBePersistent.get() ? MessageDeliveryMode.PERSISTENT : MessageDeliveryMode.NON_PERSISTENT, properties.getDeliveryMode()); return null; }).when(amqpTemplate).send(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(org.springframework.amqp.core.Message.class), Mockito.any(CorrelationData.class)); ReflectionUtils.setField(amqpTemplateField, endpoint, amqpTemplate); MessageChannel requestChannel = context.getBean("requestChannel", MessageChannel.class); Message<?> message = MessageBuilder.withPayload("hello").setHeader("foo", "foo").setHeader("bar", "bar") .setHeader("foobar", "foobar").build(); requestChannel.send(message); Mockito.verify(amqpTemplate, Mockito.times(1)).send(anyString(), isNull(), Mockito.any(org.springframework.amqp.core.Message.class), isNull()); shouldBePersistent.set(true); message = MessageBuilder.withPayload("hello").setHeader("foo", "foo").setHeader("bar", "bar") .setHeader("foobar", "foobar").setHeader(AmqpHeaders.DELIVERY_MODE, MessageDeliveryMode.PERSISTENT) .build(); requestChannel.send(message); }
From source file:org.springframework.integration.amqp.config.AmqpOutboundChannelAdapterParserTests.java
@SuppressWarnings("rawtypes") @Test//from w w w.j a v a2 s . c om public void amqpOutboundChannelAdapterWithinChain() { Object eventDrivenConsumer = context.getBean("chainWithRabbitOutbound"); List chainHandlers = TestUtils.getPropertyValue(eventDrivenConsumer, "handler.handlers", List.class); AmqpOutboundEndpoint endpoint = (AmqpOutboundEndpoint) chainHandlers.get(0); assertNull(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")); Field amqpTemplateField = ReflectionUtils.findField(AmqpOutboundEndpoint.class, "amqpTemplate"); amqpTemplateField.setAccessible(true); RabbitTemplate amqpTemplate = TestUtils.getPropertyValue(endpoint, "amqpTemplate", RabbitTemplate.class); amqpTemplate = Mockito.spy(amqpTemplate); Mockito.doAnswer(invocation -> { Object[] args = invocation.getArguments(); org.springframework.amqp.core.Message amqpMessage = (org.springframework.amqp.core.Message) args[2]; MessageProperties properties = amqpMessage.getMessageProperties(); assertEquals("hello", new String(amqpMessage.getBody())); assertEquals(MessageDeliveryMode.PERSISTENT, properties.getDeliveryMode()); return null; }).when(amqpTemplate).send(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(org.springframework.amqp.core.Message.class), Mockito.any(CorrelationData.class)); ReflectionUtils.setField(amqpTemplateField, endpoint, amqpTemplate); MessageChannel requestChannel = context.getBean("amqpOutboundChannelAdapterWithinChain", MessageChannel.class); Message<?> message = MessageBuilder.withPayload("hello").build(); requestChannel.send(message); Mockito.verify(amqpTemplate, Mockito.times(1)).send(Mockito.any(String.class), isNull(), Mockito.any(org.springframework.amqp.core.Message.class), isNull()); }
From source file:org.springframework.integration.config.IdGeneratorConfigurer.java
private boolean setIdGenerator(ApplicationContext context) { try {/* w w w . j ava 2s.c om*/ IdGenerator idGeneratorBean = context.getBean(IdGenerator.class); if (logger.isDebugEnabled()) { logger.debug("using custom MessageHeaders.IdGenerator [" + idGeneratorBean.getClass() + "]"); } Field idGeneratorField = ReflectionUtils.findField(MessageHeaders.class, "idGenerator"); ReflectionUtils.makeAccessible(idGeneratorField); IdGenerator currentIdGenerator = (IdGenerator) ReflectionUtils.getField(idGeneratorField, null); if (currentIdGenerator != null) { if (currentIdGenerator.equals(idGeneratorBean)) { // same instance is already set, nothing needs to be done return false; } else { if (IdGeneratorConfigurer.theIdGenerator.getClass() == idGeneratorBean.getClass()) { if (logger.isWarnEnabled()) { logger.warn("Another instance of " + idGeneratorBean.getClass() + " has already been established; ignoring"); } return true; } else { // different instance has been set, not legal throw new BeanDefinitionStoreException( "'MessageHeaders.idGenerator' has already been set and can not be set again"); } } } if (logger.isInfoEnabled()) { logger.info("Message IDs will be generated using custom IdGenerator [" + idGeneratorBean.getClass() + "]"); } ReflectionUtils.setField(idGeneratorField, null, idGeneratorBean); IdGeneratorConfigurer.theIdGenerator = idGeneratorBean; } catch (NoSuchBeanDefinitionException e) { // No custom IdGenerator. We will use the default. int idBeans = context.getBeansOfType(IdGenerator.class).size(); if (idBeans > 1 && logger.isWarnEnabled()) { logger.warn("Found too many 'IdGenerator' beans (" + idBeans + ") " + "Will use the existing UUID strategy."); } else if (logger.isDebugEnabled()) { logger.debug("Unable to locate MessageHeaders.IdGenerator. Will use the existing UUID strategy."); } return false; } catch (IllegalStateException e) { // thrown from ReflectionUtils if (logger.isWarnEnabled()) { logger.warn("Unexpected exception occurred while accessing idGenerator of MessageHeaders." + " Will use the existing UUID strategy.", e); } return false; } return true; }
From source file:org.springframework.integration.core.MessageIdGenerationTests.java
@Test @Ignore//from www. j av a 2 s . co m public void performanceTest() { int times = 1000000; StopWatch watch = new StopWatch(); watch.start(); for (int i = 0; i < times; i++) { new GenericMessage<Integer>(0); } watch.stop(); double defaultGeneratorElapsedTime = watch.getTotalTimeSeconds(); Field idGeneratorField = ReflectionUtils.findField(MessageHeaders.class, "idGenerator"); ReflectionUtils.makeAccessible(idGeneratorField); ReflectionUtils.setField(idGeneratorField, null, (IdGenerator) () -> TimeBasedUUIDGenerator.generateId()); watch = new StopWatch(); watch.start(); for (int i = 0; i < times; i++) { new GenericMessage<Integer>(0); } watch.stop(); double timebasedGeneratorElapsedTime = watch.getTotalTimeSeconds(); logger.info("Generated " + times + " messages using default UUID generator " + "in " + defaultGeneratorElapsedTime + " seconds"); logger.info("Generated " + times + " messages using Timebased UUID generator " + "in " + timebasedGeneratorElapsedTime + " seconds"); logger.info("Time-based ID generator is " + defaultGeneratorElapsedTime / timebasedGeneratorElapsedTime + " times faster"); }
From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java
@Test public void testCleanup() throws Exception { TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost", 0); factory.setApplicationEventPublisher(nullPublisher); factory.setNioHarvestInterval(100);// ww w . j av a2 s. c om Map<SocketChannel, TcpNioConnection> connections = new HashMap<SocketChannel, TcpNioConnection>(); SocketChannel chan1 = mock(SocketChannel.class); SocketChannel chan2 = mock(SocketChannel.class); SocketChannel chan3 = mock(SocketChannel.class); TcpNioConnection conn1 = mock(TcpNioConnection.class); TcpNioConnection conn2 = mock(TcpNioConnection.class); TcpNioConnection conn3 = mock(TcpNioConnection.class); connections.put(chan1, conn1); connections.put(chan2, conn2); connections.put(chan3, conn3); final List<Field> fields = new ArrayList<Field>(); ReflectionUtils.doWithFields(SocketChannel.class, field -> { field.setAccessible(true); fields.add(field); }, field -> field.getName().equals("open")); Field field = fields.get(0); // Can't use Mockito because isOpen() is final ReflectionUtils.setField(field, chan1, true); ReflectionUtils.setField(field, chan2, true); ReflectionUtils.setField(field, chan3, true); Selector selector = mock(Selector.class); HashSet<SelectionKey> keys = new HashSet<SelectionKey>(); when(selector.selectedKeys()).thenReturn(keys); factory.processNioSelections(1, selector, null, connections); assertEquals(3, connections.size()); // all open ReflectionUtils.setField(field, chan1, false); factory.processNioSelections(1, selector, null, connections); assertEquals(3, connections.size()); // interval didn't pass Thread.sleep(110); factory.processNioSelections(1, selector, null, connections); assertEquals(2, connections.size()); // first is closed ReflectionUtils.setField(field, chan2, false); factory.processNioSelections(1, selector, null, connections); assertEquals(2, connections.size()); // interval didn't pass Thread.sleep(110); factory.processNioSelections(1, selector, null, connections); assertEquals(1, connections.size()); // second is closed ReflectionUtils.setField(field, chan3, false); factory.processNioSelections(1, selector, null, connections); assertEquals(1, connections.size()); // interval didn't pass Thread.sleep(110); factory.processNioSelections(1, selector, null, connections); assertEquals(0, connections.size()); // third is closed assertEquals(0, TestUtils.getPropertyValue(factory, "connections", Map.class).size()); }