@Test public void targetOnly() { String beanName = "outboundWithImplicitChannel"; Object channel = this.applicationContext.getBean(beanName); assertTrue(channel instanceof DirectChannel); BeanFactoryChannelResolver channelResolver = new BeanFactoryChannelResolver(this.applicationContext); assertNotNull(channelResolver.resolveDestination(beanName)); Object adapter = this.applicationContext.getBean(beanName + ".adapter"); assertNotNull(adapter); assertTrue(adapter instanceof EventDrivenConsumer); assertFalse(((EventDrivenConsumer) adapter).isAutoStartup()); assertEquals(-1, ((EventDrivenConsumer) adapter).getPhase()); TestConsumer consumer = (TestConsumer) this.applicationContext.getBean("consumer"); assertNull(consumer.getLastMessage()); Message<?> message = new GenericMessage<String>("test"); try { ((MessageChannel) channel).send(message); fail("MessageDispatchingException is expected."); } catch (Exception e) { assertThat(e, Matchers.instanceOf(MessageDeliveryException.class)); assertThat(e.getCause(), Matchers.instanceOf(MessageDispatchingException.class)); } ((EventDrivenConsumer) adapter).start(); ((MessageChannel) channel).send(message); assertNotNull(consumer.getLastMessage()); assertEquals(message, consumer.getLastMessage()); }
@Test public void sockJsAttributesSupport() { loadBeanDefinitions("websocket-config-handlers-sockjs-attributes.xml"); SimpleUrlHandlerMapping handlerMapping = appContext.getBean(SimpleUrlHandlerMapping.class); assertNotNull(handlerMapping); SockJsHttpRequestHandler handler = (SockJsHttpRequestHandler) handlerMapping.getUrlMap().get("/test/**"); assertNotNull(handler); checkDelegateHandlerType(handler.getWebSocketHandler(), TestWebSocketHandler.class); SockJsService sockJsService = handler.getSockJsService(); assertNotNull(sockJsService); assertThat(sockJsService, Matchers.instanceOf(TransportHandlingSockJsService.class)); TransportHandlingSockJsService defaultSockJsService = (TransportHandlingSockJsService) sockJsService; assertThat( defaultSockJsService.getTaskScheduler(), Matchers.instanceOf(TestTaskScheduler.class)); assertThat( defaultSockJsService.getTransportHandlers().values(), Matchers.containsInAnyOrder( Matchers.instanceOf(XhrPollingTransportHandler.class), Matchers.instanceOf(XhrStreamingTransportHandler.class))); assertEquals("testSockJsService", defaultSockJsService.getName()); assertFalse(defaultSockJsService.isWebSocketEnabled()); assertFalse(defaultSockJsService.isSessionCookieNeeded()); assertEquals(2048, defaultSockJsService.getStreamBytesLimit()); assertEquals(256, defaultSockJsService.getDisconnectDelay()); assertEquals(1024, defaultSockJsService.getHttpMessageCacheSize()); assertEquals(20, defaultSockJsService.getHeartbeatTime()); }
@Test @RedisAvailable @SuppressWarnings("unchecked") public void testInt3014ExpectMessageTrue() throws Exception { final String queueName = "si.test.redisQueueInboundChannelAdapterTests2"; RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); redisTemplate.setConnectionFactory(this.connectionFactory); redisTemplate.setEnableDefaultSerializer(false); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); redisTemplate.afterPropertiesSet(); Message<?> message = MessageBuilder.withPayload("testing").build(); redisTemplate.boundListOps(queueName).leftPush(message); redisTemplate.boundListOps(queueName).leftPush("test"); PollableChannel channel = new QueueChannel(); PollableChannel errorChannel = new QueueChannel(); RedisQueueMessageDrivenEndpoint endpoint = new RedisQueueMessageDrivenEndpoint(queueName, this.connectionFactory); endpoint.setBeanFactory(Mockito.mock(BeanFactory.class)); endpoint.setExpectMessage(true); endpoint.setOutputChannel(channel); endpoint.setErrorChannel(errorChannel); endpoint.setReceiveTimeout(1000); endpoint.afterPropertiesSet(); endpoint.start(); Message<Object> receive = (Message<Object>) channel.receive(2000); assertNotNull(receive); assertEquals(message, receive); receive = (Message<Object>) errorChannel.receive(2000); assertNotNull(receive); assertThat(receive, Matchers.instanceOf(ErrorMessage.class)); assertThat(receive.getPayload(), Matchers.instanceOf(MessagingException.class)); assertThat( ((Exception) receive.getPayload()).getMessage(), Matchers.containsString("Deserialization of Message failed.")); assertThat( ((Exception) receive.getPayload()).getCause(), Matchers.instanceOf(ClassCastException.class)); assertThat( ((Exception) receive.getPayload()).getCause().getMessage(), Matchers.containsString( "java.lang.String cannot be cast to org.springframework.messaging.Message")); endpoint.stop(); }
@Test public void testPathMatchingConfiguration() { loadBeanDefinitions("mvc-config-path-matching.xml"); RequestMappingHandlerMapping hm = appContext.getBean(RequestMappingHandlerMapping.class); assertNotNull(hm); assertTrue(hm.useSuffixPatternMatch()); assertFalse(hm.useTrailingSlashMatch()); assertTrue(hm.useRegisteredSuffixPatternMatch()); assertThat(hm.getUrlPathHelper(), Matchers.instanceOf(TestPathHelper.class)); assertThat(hm.getPathMatcher(), Matchers.instanceOf(TestPathMatcher.class)); List<String> fileExtensions = hm.getContentNegotiationManager().getAllFileExtensions(); assertThat(fileExtensions, Matchers.contains("xml")); assertThat(fileExtensions, Matchers.hasSize(1)); }
@Test public void testFailOnDoubleReference() { try { new ClassPathXmlApplicationContext( this.getClass().getSimpleName() + "-fail-context.xml", this.getClass()); fail("Expected exception due to 2 endpoints referencing the same bean"); } catch (Exception e) { assertThat(e, Matchers.instanceOf(BeanCreationException.class)); assertThat(e.getCause(), Matchers.instanceOf(BeanCreationException.class)); assertThat(e.getCause().getCause(), Matchers.instanceOf(IllegalArgumentException.class)); assertThat( e.getCause().getCause().getMessage(), Matchers.containsString( "An AbstractReplyProducingMessageHandler may only be referenced once")); } }
@Test public void test() throws Exception { assertThat(this.connectionFactory, Matchers.instanceOf(TcpNetClientConnectionFactory.class)); assertEquals("foo", this.connectionFactory.getHost()); assertFalse(TestUtils.getPropertyValue(this.connectionFactory, "lookupHost", Boolean.class)); assertEquals(120000, TestUtils.getPropertyValue(this.connectionFactory, "soTimeout")); }
@Test public void testGateway1() { FtpOutboundGateway gateway = TestUtils.getPropertyValue(gateway1, "handler", FtpOutboundGateway.class); assertEquals( "X", TestUtils.getPropertyValue(gateway, "remoteFileTemplate.remoteFileSeparator")); assertNotNull(TestUtils.getPropertyValue(gateway, "remoteFileTemplate.sessionFactory")); assertNotNull(TestUtils.getPropertyValue(gateway, "outputChannel")); assertEquals( "local-test-dir", TestUtils.getPropertyValue(gateway, "localDirectoryExpression.literalValue")); assertFalse((Boolean) TestUtils.getPropertyValue(gateway, "autoCreateLocalDirectory")); assertNotNull(TestUtils.getPropertyValue(gateway, "filter")); assertEquals(Command.LS, TestUtils.getPropertyValue(gateway, "command")); @SuppressWarnings("unchecked") Set<Option> options = TestUtils.getPropertyValue(gateway, "options", Set.class); assertTrue(options.contains(Option.NAME_ONLY)); assertTrue(options.contains(Option.NOSORT)); Long sendTimeout = TestUtils.getPropertyValue(gateway, "messagingTemplate.sendTimeout", Long.class); assertEquals(Long.valueOf(777), sendTimeout); assertTrue(TestUtils.getPropertyValue(gateway, "requiresReply", Boolean.class)); assertThat( TestUtils.getPropertyValue(gateway, "mputFilter"), Matchers.instanceOf(RegexPatternFileListFilter.class)); }
public void testAutoBoost() throws Exception { for (boolean boost : new boolean[] {false, true}) { String index = "test_" + boost; IndexService indexService = createIndex( index, client() .admin() .indices() .prepareCreate(index) .addMapping("type", "foo", "type=string" + (boost ? ",boost=2" : ""))); client().prepareIndex(index, "type").setSource("foo", "bar").get(); client().admin().indices().prepareRefresh(index).get(); Query query = indexService .mapperService() .documentMapper("type") .allFieldMapper() .fieldType() .termQuery("bar", null); try (Searcher searcher = indexService.getShardOrNull(0).acquireSearcher("tests")) { query = searcher.searcher().rewrite(query); final Class<?> expected = boost ? AllTermQuery.class : TermQuery.class; assertThat(query, Matchers.instanceOf(expected)); } } }
@Test public void testGatewayMPut() { FtpOutboundGateway gateway = TestUtils.getPropertyValue(gateway4, "handler", FtpOutboundGateway.class); assertNotNull(TestUtils.getPropertyValue(gateway, "remoteFileTemplate.sessionFactory")); assertNotNull(TestUtils.getPropertyValue(gateway, "outputChannel")); assertEquals(Command.MPUT, TestUtils.getPropertyValue(gateway, "command")); assertEquals( "'foo'", TestUtils.getPropertyValue(gateway, "renameProcessor.expression.expression")); assertThat( TestUtils.getPropertyValue(gateway, "mputFilter"), Matchers.instanceOf(RegexPatternFileListFilter.class)); assertSame( generator, TestUtils.getPropertyValue(gateway, "remoteFileTemplate.fileNameGenerator")); assertEquals( "/foo", TestUtils.getPropertyValue( gateway, "remoteFileTemplate.directoryExpressionProcessor.expression", Expression.class) .getExpressionString()); assertEquals( "/bar", TestUtils.getPropertyValue( gateway, "remoteFileTemplate.temporaryDirectoryExpressionProcessor.expression", Expression.class) .getExpressionString()); }
/** active() factory method returns expected condition. */ @Test public void active() { final NexusIsActiveCondition nexusIsActiveCondition = mock(NexusIsActiveCondition.class); final NexusConditions underTest = new NexusConditions(nexusIsActiveCondition); assertThat( underTest.active(), is(Matchers.<Condition>instanceOf(NexusIsActiveCondition.class))); }
// https://github.com/elasticsearch/elasticsearch/issues/7240 public void testEmptyBooleanQuery() throws Exception { XContentBuilder contentBuilder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); BytesReference query = contentBuilder.startObject().startObject("bool").endObject().endObject().bytes(); Query parsedQuery = parseQuery(query).toQuery(createShardContext()); assertThat(parsedQuery, Matchers.instanceOf(MatchAllDocsQuery.class)); }
@Test @SuppressWarnings("unchecked") public void websocketHandlersAttributes() { loadBeanDefinitions("websocket-config-handlers-attributes.xml"); HandlerMapping handlerMapping = appContext.getBean(HandlerMapping.class); assertNotNull(handlerMapping); assertTrue(handlerMapping instanceof SimpleUrlHandlerMapping); SimpleUrlHandlerMapping urlHandlerMapping = (SimpleUrlHandlerMapping) handlerMapping; assertEquals(2, urlHandlerMapping.getOrder()); WebSocketHttpRequestHandler handler = (WebSocketHttpRequestHandler) urlHandlerMapping.getUrlMap().get("/foo"); assertNotNull(handler); checkDelegateHandlerType(handler.getWebSocketHandler(), FooWebSocketHandler.class); HandshakeHandler handshakeHandler = (HandshakeHandler) new DirectFieldAccessor(handler).getPropertyValue("handshakeHandler"); assertNotNull(handshakeHandler); assertTrue(handshakeHandler instanceof TestHandshakeHandler); List<HandshakeInterceptor> handshakeInterceptorList = (List<HandshakeInterceptor>) new DirectFieldAccessor(handler).getPropertyValue("interceptors"); assertNotNull(handshakeInterceptorList); assertThat( handshakeInterceptorList, Matchers.contains( Matchers.instanceOf(FooTestInterceptor.class), Matchers.instanceOf(BarTestInterceptor.class))); handler = (WebSocketHttpRequestHandler) urlHandlerMapping.getUrlMap().get("/test"); assertNotNull(handler); checkDelegateHandlerType(handler.getWebSocketHandler(), TestWebSocketHandler.class); handshakeHandler = (HandshakeHandler) new DirectFieldAccessor(handler).getPropertyValue("handshakeHandler"); assertNotNull(handshakeHandler); assertTrue(handshakeHandler instanceof TestHandshakeHandler); handshakeInterceptorList = (List<HandshakeInterceptor>) new DirectFieldAccessor(handler).getPropertyValue("interceptors"); assertNotNull(handshakeInterceptorList); assertThat( handshakeInterceptorList, Matchers.contains( Matchers.instanceOf(FooTestInterceptor.class), Matchers.instanceOf(BarTestInterceptor.class))); }
public void testExecuteWithUnspecifiedTestResultsDir() { setUpMocks(test); test.setTestResultsDir(null); try { test.execute(); fail(); } catch (Exception e) { assertThat(e.getCause(), Matchers.instanceOf(InvalidUserDataException.class)); } }
@Test public void test() throws Exception { assertThat(this.connectionFactory, Matchers.instanceOf(TcpNioClientConnectionFactory.class)); assertEquals("foo", this.connectionFactory.getHost()); assertTrue(TestUtils.getPropertyValue(this.connectionFactory, "lookupHost", Boolean.class)); assertTrue( TestUtils.getPropertyValue(this.connectionFactory, "usingDirectBuffers", Boolean.class)); assertEquals(123, TestUtils.getPropertyValue(this.connectionFactory, "soTimeout")); assertTrue(this.connectionFactory.isSingleUse()); assertEquals("bar", TestUtils.getPropertyValue(this.connectionFactory, "mapper.charset")); }
@Test public void annotationMethodMessageHandler() { loadBeanDefinitions("websocket-config-broker-simple.xml"); SimpAnnotationMethodMessageHandler annotationMethodMessageHandler = this.appContext.getBean(SimpAnnotationMethodMessageHandler.class); assertNotNull(annotationMethodMessageHandler); MessageConverter messageConverter = annotationMethodMessageHandler.getMessageConverter(); assertNotNull(messageConverter); assertTrue(messageConverter instanceof CompositeMessageConverter); CompositeMessageConverter compositeMessageConverter = this.appContext.getBean(CompositeMessageConverter.class); assertNotNull(compositeMessageConverter); SimpMessagingTemplate simpMessagingTemplate = this.appContext.getBean(SimpMessagingTemplate.class); assertNotNull(simpMessagingTemplate); assertEquals("/personal/", simpMessagingTemplate.getUserDestinationPrefix()); List<MessageConverter> converters = compositeMessageConverter.getConverters(); assertThat(converters.size(), Matchers.is(3)); assertThat(converters.get(0), Matchers.instanceOf(StringMessageConverter.class)); assertThat(converters.get(1), Matchers.instanceOf(ByteArrayMessageConverter.class)); assertThat(converters.get(2), Matchers.instanceOf(MappingJackson2MessageConverter.class)); ContentTypeResolver resolver = ((MappingJackson2MessageConverter) converters.get(2)).getContentTypeResolver(); assertEquals( MimeTypeUtils.APPLICATION_JSON, ((DefaultContentTypeResolver) resolver).getDefaultMimeType()); DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(annotationMethodMessageHandler); String pathSeparator = (String) new DirectFieldAccessor(handlerAccessor.getPropertyValue("pathMatcher")) .getPropertyValue("pathSeparator"); assertEquals(".", pathSeparator); }
@Test public void testIdleTimeout() throws Throwable { long timeout = 1000; start(new TimeoutHandler(2 * timeout)); client.stop(); final AtomicBoolean sslIdle = new AtomicBoolean(); client = new HttpClient( new HttpClientTransportOverHTTP() { @Override public HttpDestination newHttpDestination(Origin origin) { return new HttpDestinationOverHTTP(getHttpClient(), origin) { @Override protected ClientConnectionFactory newSslClientConnectionFactory( ClientConnectionFactory connectionFactory) { HttpClient client = getHttpClient(); return new SslClientConnectionFactory( client.getSslContextFactory(), client.getByteBufferPool(), client.getExecutor(), connectionFactory) { @Override protected SslConnection newSslConnection( ByteBufferPool byteBufferPool, Executor executor, EndPoint endPoint, SSLEngine engine) { return new SslConnection(byteBufferPool, executor, endPoint, engine) { @Override protected boolean onReadTimeout() { sslIdle.set(true); return super.onReadTimeout(); } }; } }; } }; } }, sslContextFactory); client.setIdleTimeout(timeout); client.start(); try { client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).send(); Assert.fail(); } catch (Exception x) { Assert.assertFalse(sslIdle.get()); Assert.assertThat(x.getCause(), Matchers.instanceOf(TimeoutException.class)); } }
// #6187: if no fields were boosted, we shouldn't use AllTokenStream public void testNoBoost() throws Exception { String mapping = copyToStringFromClasspath("/org/elasticsearch/index/mapper/all/noboost-mapping.json"); DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse(mapping); byte[] json = copyToBytesFromClasspath("/org/elasticsearch/index/mapper/all/test1.json"); Document doc = docMapper.parse("test", "person", "1", new BytesArray(json)).rootDoc(); AllField field = (AllField) doc.getField("_all"); // no fields have boost, so we should not see AllTokenStream: assertThat( field.tokenStream(docMapper.mappers().indexAnalyzer(), null), Matchers.not(Matchers.instanceOf(AllTokenStream.class))); }
public void testSimpleAllMappers() throws Exception { String mapping = copyToStringFromClasspath("/org/elasticsearch/index/mapper/all/mapping.json"); DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse(mapping); byte[] json = copyToBytesFromClasspath("/org/elasticsearch/index/mapper/all/test1.json"); Document doc = docMapper.parse("test", "person", "1", new BytesArray(json)).rootDoc(); AllField field = (AllField) doc.getField("_all"); // One field is boosted so we should see AllTokenStream used: assertThat( field.tokenStream(docMapper.mappers().indexAnalyzer(), null), Matchers.instanceOf(AllTokenStream.class)); AllEntries allEntries = field.getAllEntries(); assertThat(allEntries.fields().size(), equalTo(3)); assertThat(allEntries.fields().contains("address.last.location"), equalTo(true)); assertThat(allEntries.fields().contains("name.last"), equalTo(true)); assertThat(allEntries.fields().contains("simple1"), equalTo(true)); AllFieldMapper mapper = docMapper.allFieldMapper(); assertThat(field.fieldType().omitNorms(), equalTo(true)); assertThat( mapper.fieldType().queryStringTermQuery(new Term("_all", "foobar")), Matchers.instanceOf(AllTermQuery.class)); }
@Test public void sockJsSupport() { loadBeanDefinitions("websocket-config-handlers-sockjs.xml"); SimpleUrlHandlerMapping handlerMapping = appContext.getBean(SimpleUrlHandlerMapping.class); assertNotNull(handlerMapping); SockJsHttpRequestHandler testHandler = (SockJsHttpRequestHandler) handlerMapping.getUrlMap().get("/test/**"); assertNotNull(testHandler); checkDelegateHandlerType(testHandler.getWebSocketHandler(), TestWebSocketHandler.class); SockJsService testSockJsService = testHandler.getSockJsService(); SockJsHttpRequestHandler fooHandler = (SockJsHttpRequestHandler) handlerMapping.getUrlMap().get("/foo/**"); assertNotNull(fooHandler); checkDelegateHandlerType(fooHandler.getWebSocketHandler(), FooWebSocketHandler.class); SockJsService sockJsService = fooHandler.getSockJsService(); assertNotNull(sockJsService); assertEquals(testSockJsService, sockJsService); assertThat(sockJsService, Matchers.instanceOf(DefaultSockJsService.class)); DefaultSockJsService defaultSockJsService = (DefaultSockJsService) sockJsService; assertThat( defaultSockJsService.getTaskScheduler(), Matchers.instanceOf(ThreadPoolTaskScheduler.class)); assertThat( defaultSockJsService.getTransportHandlers().values(), Matchers.containsInAnyOrder( Matchers.instanceOf(XhrPollingTransportHandler.class), Matchers.instanceOf(XhrReceivingTransportHandler.class), Matchers.instanceOf(JsonpPollingTransportHandler.class), Matchers.instanceOf(JsonpReceivingTransportHandler.class), Matchers.instanceOf(XhrStreamingTransportHandler.class), Matchers.instanceOf(EventSourceTransportHandler.class), Matchers.instanceOf(HtmlFileTransportHandler.class), Matchers.instanceOf(WebSocketTransportHandler.class))); }
@Test // SPR-13883 public void shouldConfigureFixedPrefixAutomatically() throws Exception { this.resolver.addFixedVersionStrategy( "fixedversion", "/js/**", "/css/**", "/fixedversion/css/**"); assertThat(this.resolver.getStrategyMap().size(), is(4)); assertThat( this.resolver.getStrategyForPath("js/something.js"), Matchers.instanceOf(FixedVersionStrategy.class)); assertThat( this.resolver.getStrategyForPath("fixedversion/js/something.js"), Matchers.instanceOf(FixedVersionStrategy.class)); assertThat( this.resolver.getStrategyForPath("css/something.css"), Matchers.instanceOf(FixedVersionStrategy.class)); assertThat( this.resolver.getStrategyForPath("fixedversion/css/something.css"), Matchers.instanceOf(FixedVersionStrategy.class)); }
// #6187: if _all doesn't index positions then we never use AllTokenStream, even if some fields // have boost public void testBoostWithOmitPositions() throws Exception { String mapping = copyToStringFromClasspath( "/org/elasticsearch/index/mapper/all/mapping_boost_omit_positions_on_all.json"); DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser().parse(mapping); byte[] json = copyToBytesFromClasspath("/org/elasticsearch/index/mapper/all/test1.json"); Document doc = docMapper.parse("test", "person", "1", new BytesArray(json)).rootDoc(); AllField field = (AllField) doc.getField("_all"); // _all field omits positions, so we should not get AllTokenStream even though fields are // boosted assertThat( field.tokenStream(docMapper.mappers().indexAnalyzer(), null), Matchers.not(Matchers.instanceOf(AllTokenStream.class))); }
@Test public void testReporterQuery() throws Exception { Optional<ScheduledReporter> reporter; reporter = new MetricReportHandlerConsole() .select(mediator(), provider, URI.create("console://stdout?rate=m&duration=h")); assertThat(reporter.get(), Matchers.instanceOf(ConsoleReporter.class)); assertReporter(reporter.get(), registry, "minute", "hours"); ConsoleReporter console = (ConsoleReporter) reporter.get(); assertThat( field(ConsoleReporter.class, "output", PrintStream.class, console), Matchers.equalTo(System.out)); }
/** * {@link DyRepo#memo}. * * @throws IOException In case of error. */ @Test public void memo() throws IOException { final Region region = new MkRegion( new H2Data() .with( DyRepo.TBL, new String[] {DyRepo.ATTR_MEMO}, new String[] {DyRepo.ATTR_UPDATED})); final Table table = region.table(DyRepo.TBL); table.put( new Attributes() .with(DyRepo.ATTR_MEMO, "<memo></memo>") .with(DyRepo.ATTR_UPDATED, System.currentTimeMillis())); MatcherAssert.assertThat( new DyRepo(table.frame().iterator().next()).memo(), Matchers.instanceOf(DyMemo.class)); }
@Test public void testGateway2() throws Exception { FtpOutboundGateway gateway = TestUtils.getPropertyValue(gateway2, "handler", FtpOutboundGateway.class); assertEquals( "X", TestUtils.getPropertyValue(gateway, "remoteFileTemplate.remoteFileSeparator")); assertNotNull(TestUtils.getPropertyValue(gateway, "remoteFileTemplate.sessionFactory")); assertTrue( TestUtils.getPropertyValue(gateway, "remoteFileTemplate.sessionFactory") instanceof CachingSessionFactory); assertNotNull(TestUtils.getPropertyValue(gateway, "outputChannel")); assertEquals( "local-test-dir", TestUtils.getPropertyValue(gateway, "localDirectoryExpression.literalValue")); assertFalse((Boolean) TestUtils.getPropertyValue(gateway, "autoCreateLocalDirectory")); assertEquals(Command.GET, TestUtils.getPropertyValue(gateway, "command")); @SuppressWarnings("unchecked") Set<String> options = TestUtils.getPropertyValue(gateway, "options", Set.class); assertTrue(options.contains(Option.PRESERVE_TIMESTAMP)); gateway.handleMessage(new GenericMessage<String>("foo")); assertFalse(TestUtils.getPropertyValue(gateway, "requiresReply", Boolean.class)); assertEquals(1, adviceCalled); // INT-3129 assertNotNull(TestUtils.getPropertyValue(gateway, "localFilenameGeneratorExpression")); final AtomicReference<Method> genMethod = new AtomicReference<Method>(); ReflectionUtils.doWithMethods( FtpOutboundGateway.class, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { if ("generateLocalFileName".equals(method.getName())) { method.setAccessible(true); genMethod.set(method); } } }); assertEquals( "FOO.afoo", genMethod.get().invoke(gateway, new GenericMessage<String>(""), "foo")); assertThat( TestUtils.getPropertyValue(gateway, "mputFilter"), Matchers.instanceOf(SimplePatternFileListFilter.class)); }
@Test public void testProxyDown() throws Exception { prepareProxy(); prepareServer(new EmptyHttpServlet()); // Shutdown the proxy proxy.stop(); try { client .newRequest("localhost", serverConnector.getLocalPort()) .timeout(5, TimeUnit.SECONDS) .send(); Assert.fail(); } catch (ExecutionException x) { Assert.assertThat(x.getCause(), Matchers.instanceOf(ConnectException.class)); } }
@Test public void testSimpleAllMappers() throws Exception { String mapping = copyToStringFromClasspath("/org/elasticsearch/index/mapper/all/mapping.json"); DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping); byte[] json = copyToBytesFromClasspath("/org/elasticsearch/index/mapper/all/test1.json"); Document doc = docMapper.parse(new BytesArray(json)).rootDoc(); AllField field = (AllField) doc.getField("_all"); AllEntries allEntries = ((AllTokenStream) field.tokenStream(docMapper.mappers().indexAnalyzer())).allEntries(); assertThat(allEntries.fields().size(), equalTo(3)); assertThat(allEntries.fields().contains("address.last.location"), equalTo(true)); assertThat(allEntries.fields().contains("name.last"), equalTo(true)); assertThat(allEntries.fields().contains("simple1"), equalTo(true)); FieldMapper mapper = docMapper.mappers().smartNameFieldMapper("_all"); assertThat(field.fieldType().omitNorms(), equalTo(true)); assertThat( mapper.queryStringTermQuery(new Term("_all", "foobar")), Matchers.instanceOf(AllTermQuery.class)); }
@Test public void testReporterNotFound() throws Exception { Optional<ScheduledReporter> reporter; reporter = new MetricReportHandlerConsole() .select(mediator(), provider, URI.create("console://" + anytext(UUID.randomUUID()))); assertThat(reporter.get(), Matchers.instanceOf(ConsoleReporter.class)); assertReporter(reporter.get(), registry, "millisecond", "seconds"); ConsoleReporter console = (ConsoleReporter) reporter.get(); PrintStream stream = field(ConsoleReporter.class, "output", PrintStream.class, console); MatcherAssert.assertThat(stream, Matchers.not(Matchers.equalTo(System.out))); MatcherAssert.assertThat(stream, Matchers.not(Matchers.equalTo(System.err))); MatcherAssert.assertThat(stream, Matchers.notNullValue()); }
@Test // SPR-13592 @SuppressWarnings("unchecked") public void converterThrowsIOException() throws IOException { HttpMessageConverter<String> converter = mock(HttpMessageConverter.class); HttpHeaders responseHeaders = new HttpHeaders(); MediaType contentType = MediaType.TEXT_PLAIN; responseHeaders.setContentType(contentType); extractor = new HttpMessageConverterExtractor<>(String.class, createConverterList(converter)); given(response.getStatusCode()).willReturn(HttpStatus.OK); given(response.getHeaders()).willReturn(responseHeaders); given(response.getBody()).willReturn(new ByteArrayInputStream("Foobar".getBytes())); given(converter.canRead(String.class, contentType)).willThrow(IOException.class); exception.expect(RestClientException.class); exception.expectMessage( "Error while extracting response for type " + "[class java.lang.String] and content type [text/plain]"); exception.expectCause(Matchers.instanceOf(IOException.class)); extractor.extractData(response); }
@Test public void testInt3017DefaultConfig() throws Exception { assertSame( this.connectionFactory, TestUtils.getPropertyValue(this.defaultAdapter, "template.connectionFactory")); assertEquals( "foo", TestUtils.getPropertyValue(this.defaultAdapter, "queueNameExpression", Expression.class) .getExpressionString()); assertTrue(TestUtils.getPropertyValue(this.defaultAdapter, "extractPayload", Boolean.class)); assertFalse( TestUtils.getPropertyValue(this.defaultAdapter, "serializerExplicitlySet", Boolean.class)); Object handler = TestUtils.getPropertyValue(this.defaultEndpoint, "handler"); assertTrue(AopUtils.isAopProxy(handler)); assertSame(((Advised) handler).getTargetSource().getTarget(), this.defaultAdapter); assertThat( TestUtils.getPropertyValue(handler, "h.advised.advisors.first.item.advice"), Matchers.instanceOf(RequestHandlerRetryAdvice.class)); }
@Test @RedisAvailable @SuppressWarnings("unchecked") @Ignore // JedisConnectionFactory doesn't support proper 'destroy()' and allows to create new fresh Redis // connection public void testInt3196Recovery() throws Exception { String queueName = "test.si.Int3196Recovery"; QueueChannel channel = new QueueChannel(); final List<ApplicationEvent> exceptionEvents = new ArrayList<ApplicationEvent>(); final CountDownLatch exceptionsLatch = new CountDownLatch(2); RedisQueueMessageDrivenEndpoint endpoint = new RedisQueueMessageDrivenEndpoint(queueName, this.connectionFactory); endpoint.setBeanFactory(Mockito.mock(BeanFactory.class)); endpoint.setApplicationEventPublisher( new ApplicationEventPublisher() { @Override public void publishEvent(ApplicationEvent event) { exceptionEvents.add(event); exceptionsLatch.countDown(); } }); endpoint.setOutputChannel(channel); endpoint.setReceiveTimeout(100); endpoint.setRecoveryInterval(200); endpoint.afterPropertiesSet(); endpoint.start(); int n = 0; do { n++; if (n == 100) { break; } Thread.sleep(100); } while (!endpoint.isListening()); assertTrue(n < 100); ((DisposableBean) this.connectionFactory).destroy(); assertTrue(exceptionsLatch.await(10, TimeUnit.SECONDS)); for (ApplicationEvent exceptionEvent : exceptionEvents) { assertThat(exceptionEvent, Matchers.instanceOf(RedisExceptionEvent.class)); assertSame(endpoint, exceptionEvent.getSource()); assertThat( ((IntegrationEvent) exceptionEvent).getCause().getClass(), Matchers.isIn( Arrays.<Class<? extends Throwable>>asList( RedisSystemException.class, RedisConnectionFailureException.class))); } ((InitializingBean) this.connectionFactory).afterPropertiesSet(); RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); redisTemplate.setConnectionFactory(this.getConnectionFactoryForTest()); redisTemplate.setEnableDefaultSerializer(false); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); redisTemplate.afterPropertiesSet(); String payload = "testing"; redisTemplate.boundListOps(queueName).leftPush(payload); Message<?> receive = channel.receive(1000); assertNotNull(receive); assertEquals(payload, receive.getPayload()); endpoint.stop(); }