### Example: Testing Server Health with PING/PONG Source: https://docs.spring.io/spring-integration/reference/ip/testing-connections.html This example demonstrates how to configure a connection test. It sends a 'PING' message and expects a 'PONG' reply to determine if the server is healthy. If the test fails, the connection is closed, potentially triggering a failover. ```java Message ping = new GenericMessage<>("PING"); byte[] pong = "PONG".getBytes(); clientFactory.setConnectionTest(conn -> { CountDownLatch latch = new CountDownLatch(1); AtomicBoolean result = new AtomicBoolean(); conn.registerTestListener(msg -> { if (Arrays.equals(pong, (byte[]) msg.getPayload())) { result.set(true); } latch.countDown(); return false; }); conn.send(ping); try { latch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return result.get(); }); ``` -------------------------------- ### Create LettuceConnectionFactory in Java Source: https://docs.spring.io/spring-integration/reference/redis.html Example of instantiating a LettuceConnectionFactory in Java. Ensure the factory is initialized using afterPropertiesSet(). ```java LettuceConnectionFactory cf = new LettuceConnectionFactory(); cf.afterPropertiesSet(); ``` -------------------------------- ### File System Event Examples Source: https://docs.spring.io/spring-integration/reference/file/reading.html Examples of file system events that can be published by file tailing message producers. ```text [message=tail: cannot open '/tmp/somefile' for reading: No such file or directory, file=/tmp/somefile] [message=tail: '/tmp/somefile' has become accessible, file=/tmp/somefile] [message=tail: '/tmp/somefile' has become inaccessible: No such file or directory, file=/tmp/somefile] [message=tail: '/tmp/somefile' has appeared; following end of new file, file=/tmp/somefile] ``` -------------------------------- ### Starting an Integration Flow from Another Flow's Output Source: https://docs.spring.io/spring-integration/reference/dsl/integration-flows-composition.html Use the `IntegrationFlow.from(IntegrationFlow)` factory method to start the current flow from the output of an existing flow. This abstracts away `MessageChannel` details. ```java @Bean IntegrationFlow templateSourceFlow() { return IntegrationFlow.fromSupplier(() -> "test data") .channel("sourceChannel") .get(); } @Bean IntegrationFlow compositionMainFlow(IntegrationFlow templateSourceFlow) { return IntegrationFlow.from(templateSourceFlow) .transform(String::toUpperCase) .channel(c -> c.queue("compositionMainFlowResult")) .get(); ``` -------------------------------- ### Protocol Buffers IDL Example Source: https://docs.spring.io/spring-integration/reference/transformer.html Example of a Protocol Buffers IDL file used to generate Java classes. ```protobuf syntax = "proto2"; package tutorial; option java_multiple_files = true; option java_package = "org.example"; option java_outer_classname = "MyProtos"; message MyMessageClass { optional string foo = 1; optional string bar = 2; } ``` -------------------------------- ### Configure PriorityChannel with Capacity Source: https://docs.spring.io/spring-integration/reference/channel/configuration.html Use the `` sub-element to create a PriorityChannel with a specified capacity. This example sets the capacity to 20. ```java @Bean public PollableChannel priorityChannel() { return new PriorityChannel(20); } ``` -------------------------------- ### Configure RateLimiterRequestHandlerAdvice Source: https://docs.spring.io/spring-integration/reference/handler-advice/classes.html This example shows how to configure RateLimiterRequestHandlerAdvice to limit requests to one per second. It requires injecting a RateLimiterConfig. ```java @Bean public RateLimiterRequestHandlerAdvice rateLimiterRequestHandlerAdvice() { return new RateLimiterRequestHandlerAdvice(RateLimiterConfig.custom() .limitRefreshPeriod(Duration.ofSeconds(1)) .limitForPeriod(1) .build()); } @ServiceActivator(inputChannel = "requestChannel", outputChannel = "resultChannel", adviceChain = "rateLimiterRequestHandlerAdvice") public String handleRequest(String payload) { ... } ``` -------------------------------- ### STOMP Frame Structure Example Source: https://docs.spring.io/spring-integration/reference/stomp.html Illustrates the general format of a STOMP frame, including command, headers, and body. ```text .... COMMAND header1:value1 header2:value2 Body^@ .... ``` -------------------------------- ### Configure PriorityChannel with Comparator and Datatype Source: https://docs.spring.io/spring-integration/reference/channel/configuration.html This Java example configures a PriorityChannel with a specific capacity, a custom comparator, and sets the supported datatypes. ```java @Bean public PollableChannel priorityChannel() { PriorityChannel channel = new PriorityChannel(20, widgetComparator()); channel.setDatatypes(example.Widget.class); return channel; } ``` -------------------------------- ### Sample Message History Output Source: https://docs.spring.io/spring-integration/reference/message-history.html An example of the message history structure generated by the framework, showing tracked components and timestamps. ```text [{name=sampleGateway, type=gateway, timestamp=1283281668091}, {name=sampleEnricher, type=header-enricher, timestamp=1283281668094}] ``` -------------------------------- ### Control Bus Commands Response Example Source: https://docs.spring.io/spring-integration/reference/http/control-bus-controller.html This JSON shows the structure of the response when querying available control bus commands via a GET request to /control-bus. It lists beans and their eligible methods with parameter types. ```json [ { "beanName": "errorChannel", "commands": [ { "command": "errorChannel.setShouldTrack", "description": "setShouldTrack", "parameterTypes": [ "boolean" ] }, { "command": "errorChannel.setLoggingEnabled", "description": "Use to disable debug logging during normal message flow", "parameterTypes": [ "boolean" ] }, { "command": "errorChannel.isLoggingEnabled", "description": "isLoggingEnabled", "parameterTypes": [] } ] }, { "beanName": "testManagementComponent", "commands": [ { "command": "testManagementComponent.operation2", "description": "operation2", "parameterTypes": [] }, { "command": "testManagementComponent.operation", "description": "operation", "parameterTypes": [] }, { "command": "testManagementComponent.operation", "description": "operation", "parameterTypes": [ "int", "java.lang.String" ] }, { "command": "testManagementComponent.operation", "description": "operation", "parameterTypes": [ "int" ] } ] } ] ``` -------------------------------- ### Java DSL Configuration for Reactive Outbound Gateway Source: https://docs.spring.io/spring-integration/reference/webflux.html Configure a reactive outbound gateway using Java DSL. This example sets up a GET request to 'http://localhost:8080/foo' with query parameters derived from the payload and expects a String response. ```java @Bean public IntegrationFlow outboundReactive() { return f -> f .handle(WebFlux.>outboundGateway(m -> UriComponentsBuilder.fromUriString("http://localhost:8080/foo") .queryParams(m.getPayload()) .build() .toUri()) .httpMethod(HttpMethod.GET) .expectedResponseType(String.class)); } ``` -------------------------------- ### Configure SMB Outbound Adapter with Spring Boot and Java DSL Source: https://docs.spring.io/spring-integration/reference/smb.html An example Spring Boot application demonstrating Java DSL configuration for an SMB outbound adapter. Includes setting up SmbSessionFactory and an IntegrationFlow. ```java @SpringBootApplication @IntegrationComponentScan public class SmbJavaApplication { public static void main(String[] args) { ConfigurableApplicationContext context = new SpringApplicationBuilder(SmbJavaApplication.class) .web(false) .run(args); MyGateway gateway = context.getBean(MyGateway.class); gateway.sendToSmb(new File("/foo/bar.txt")); } @Bean public SmbSessionFactory smbSessionFactory() { SmbSessionFactory smbSession = new SmbSessionFactory(); smbSession.setHost("myHost"); smbSession.setPort(445); smbSession.setDomain("myDomain"); smbSession.setUsername("myUser"); smbSession.setPassword("myPassword"); smbSession.setShareAndDir("myShareAndDir"); smbSession.setSmbMinVersion(DialectVersion.SMB210); smbSession.setSmbMaxVersion(DialectVersion.SMB311); return smbSession; } @Bean public IntegrationFlow smbOutboundFlow() { return IntegrationFlow.from("toSmbChannel") .handle(Smb.outboundAdapter(smbSessionFactory(), FileExistsMode.REPLACE) .useTemporaryFileName(false) .fileNameExpression("headers['" + FileHeaders.FILENAME + "']") .remoteDirectory("smbTarget") ).get(); } @MessagingGateway public interface MyGateway { @Gateway(requestChannel = "toSmbChannel") void sendToSmb(File file); } } ``` -------------------------------- ### Inbound File Channel Adapter Examples Source: https://docs.spring.io/spring-integration/reference/file/reading.html Demonstrates various configurations for inbound file channel adapters using the file namespace, including default filters, custom filters, filename patterns, and regex. ```xml ``` ```xml ``` ```xml ``` ```xml ``` -------------------------------- ### FileTailingIdleEvent Example Source: https://docs.spring.io/spring-integration/reference/file/reading.html An example of a FileTailingIdleEvent, which is emitted when there is no data in the file during idleEventInterval. ```text [message=Idle timeout, file=/tmp/somefile] [idle time=5438] ``` -------------------------------- ### Failing Service Example Source: https://docs.spring.io/spring-integration/reference/handler-advice/classes.html An example `@ServiceActivator` that always throws a RuntimeException, used to demonstrate retry advice. ```java public class FailingService { @ServiceActivator(inputChannel = "input", adviceChain = "retryAdvice") public void service(String message) { throw new RuntimeException("error"); } } ``` -------------------------------- ### Configure SMB Outbound Gateway with Java DSL Source: https://docs.spring.io/spring-integration/reference/smb.html Utilize the Java DSL for a more declarative approach to configuring the SMB outbound gateway. This example demonstrates setting up an MGET command with specific file filtering and local path mapping. ```java @SpringBootApplication public class SmbJavaApplication { public static void main(String[] args) { new SpringApplicationBuilder(SmbJavaApplication.class) .web(false) .run(args); } @Bean public SmbSessionFactory smbSessionFactory() { SmbSessionFactory smbSession = new SmbSessionFactory(); smbSession.setHost("myHost"); smbSession.setPort(445); smbSession.setDomain("myDomain"); smbSession.setUsername("myUser"); smbSession.setPassword("myPassword"); smbSession.setShareAndDir("myShareAndDir"); smbSession.setSmbMinVersion(DialectVersion.SMB210); smbSession.setSmbMaxVersion(DialectVersion.SMB311); return smbSession; } @Bean public SmbOutboundGatewaySpec smbOutboundGateway() { return Smb.outboundGateway(smbSessionFactory(), AbstractRemoteFileOutboundGateway.Command.MGET, "payload") .options(AbstractRemoteFileOutboundGateway.Option.RECURSIVE) .regexFileNameFilter("(subSmbSource|.*.txt)") .localDirectoryExpression("'localDirectory/' + #remoteDirectory") .localFilenameExpression("#remoteFileName.replaceFirst('smbSource', 'localTarget')"); } @Bean public IntegrationFlow smbFlow(AbstractRemoteFileOutboundGateway smbOutboundGateway) { return f -> f .handle(smbOutboundGateway) .channel(c -> c.queue("remoteFileOutputChannel")); } } ``` -------------------------------- ### Sample Gateway and Header Enricher Configuration (Java) Source: https://docs.spring.io/spring-integration/reference/message-history.html Example Java configuration for a messaging gateway and a header enricher, which will be tracked for message history. ```java @MessagingGateway(defaultRequestChannel = "bridgeInChannel") public interface SampleGateway { ... } @Bean @Transformer(inputChannel = "enricherChannel", outputChannel="filterChannel") HeaderEnricher sampleEnricher() { HeaderEnricher enricher = new HeaderEnricher(Collections.singletonMap("baz", new StaticHeaderValueMessageProcessor("baz"))); return enricher; } ``` -------------------------------- ### Configure PriorityChannel Source: https://docs.spring.io/spring-integration/reference/dsl/java-channels.html Demonstrates how to configure a `PriorityChannel` using `MessageChannels.priority()`. Requires a `MessageChannel` store and a channel name. ```java @Bean public PriorityChannelSpec priorityChannel() { return MessageChannels.priority(this.mongoDbChannelMessageStore, "priorityGroup") .interceptor(wireTap()); } ``` -------------------------------- ### SpelEvaluationException Example Source: https://docs.spring.io/spring-integration/reference/delayer.html This example demonstrates a SpelEvaluationException that can occur if a header is missing when using dot accessor syntax for SpEL expressions. ```java org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 8): Field or property 'delay' cannot be found on object of type 'org.springframework.messaging.MessageHeaders' ``` -------------------------------- ### Example of Request Handler Advice Chain Configuration Source: https://docs.spring.io/spring-integration/reference/handler-advice/handle-message.html This XML configuration demonstrates how to apply transaction advice and a custom HandleMessageAdvice to a reply-producing endpoint. Note the differing application points of tx:advice and myHandleMessageAdvice. ```xml \n \n \n \n \n ``` -------------------------------- ### XPath Filter Configuration Example Source: https://docs.spring.io/spring-integration/reference/xml/xpath-filter.html This example demonstrates the full configuration of the xpath-filter element, including all available attributes and child elements. ```xml ``` -------------------------------- ### Configure Reactive MongoDatabaseFactory (Java) Source: https://docs.spring.io/spring-integration/reference/mongodb.html Example of creating a `SimpleReactiveMongoDatabaseFactory` for reactive MongoDB access. It requires a reactive `MongoClient` instance and a database name. ```java ReactiveMongoDatabaseFactory mongoDbFactory = new SimpleReactiveMongoDatabaseFactory(com.mongodb.reactivestreams.client.MongoClients.create(), "test"); ``` -------------------------------- ### Configure DirectChannel (Java) Source: https://docs.spring.io/spring-integration/reference/channel/configuration.html Use this Java configuration to create a default DirectChannel instance. ```java @Bean public MessageChannel exampleChannel() { return new DirectChannel(); } ``` -------------------------------- ### JdbcPollingChannelAdapter Configuration Source: https://docs.spring.io/spring-integration/reference/overview.html Example of configuring a JdbcPollingChannelAdapter with a DataSource and a SQL query. ```java return new JdbcPollingChannelAdapter(dataSource, "SELECT * FROM foo where status = 0"); ``` -------------------------------- ### Getting Managed Roles Source: https://docs.spring.io/spring-integration/reference/endpoint-roles.html Retrieves a collection of all roles currently being managed by the `SmartLifecycleRoleController`. ```java public Collection getRoles() ``` -------------------------------- ### Java Configuration for Async AMQP Outbound Gateway Source: https://docs.spring.io/spring-integration/reference/amqp/async-outbound-gateway.html Sets up an AsyncAmqpOutboundGateway using Java configuration. This involves defining the gateway bean, an AsyncRabbitTemplate, and a SimpleMessageListenerContainer for replies. ```java @Configuration public class AmqpAsyncConfig { @Bean @ServiceActivator(inputChannel = "amqpOutboundChannel") public AsyncAmqpOutboundGateway amqpOutbound(AsyncRabbitTemplate asyncTemplate) { AsyncAmqpOutboundGateway outbound = new AsyncAmqpOutboundGateway(asyncTemplate); outbound.setRoutingKey("foo"); // default exchange - route to queue 'foo' return outbound; } @Bean public AsyncRabbitTemplate asyncTemplate(RabbitTemplate rabbitTemplate, SimpleMessageListenerContainer replyContainer) { return new AsyncRabbitTemplate(rabbitTemplate, replyContainer); } @Bean public SimpleMessageListenerContainer replyContainer() { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(ccf); container.setQueueNames("asyncRQ1"); return container; } @Bean public MessageChannel amqpOutboundChannel() { return new DirectChannel(); } } ``` -------------------------------- ### Add MQTT v5 Adapter at Runtime Source: https://docs.spring.io/spring-integration/reference/mqtt.html Demonstrates how to dynamically register a new MQTT v5 inbound message-driven channel adapter for a given topic and message channel using `IntegrationFlowContext`. ```java private void addAddRuntimeAdapter(IntegrationFlowContext flowContext, Mqttv5ClientManager clientManager, String topic, MessageChannel channel) { flowContext .registration( IntegrationFlow .from(new Mqttv5PahoMessageDrivenChannelAdapter(clientManager, topic)) .channel(channel) .get()) .register(); } ``` -------------------------------- ### PojoCorrelationStrategy Implementation Source: https://docs.spring.io/spring-integration/reference/aggregator.html Example implementation of a correlation strategy that groups numbers by their last digit. ```java public class PojoCorrelationStrategy { ... public Long groupNumbersByLastDigit(Long number) { return number % 10; } } ``` -------------------------------- ### PojoAggregator Implementation Source: https://docs.spring.io/spring-integration/reference/aggregator.html Example implementation of a POJO aggregator that sums a list of Long values. ```java public class PojoAggregator { public Long add(List results) { long total = 0l; for (long partialResult: results) { total += partialResult; } return total; } } ``` -------------------------------- ### Configure Scoped Channel Source: https://docs.spring.io/spring-integration/reference/channel/configuration.html Any channel can be configured with a scope attribute. This example sets the scope to 'thread'. ```xml ``` -------------------------------- ### Configure TCP Thread Affinity Connection Factory Source: https://docs.spring.io/spring-integration/reference/ip/tcp-connection-factories.html This example demonstrates the configuration of a TCP client connection factory and a thread affinity client connection factory. It also shows how to set up an outbound gateway to use these factories for sending messages over TCP. ```java @Bean public TcpNetClientConnectionFactory cf() { TcpNetClientConnectionFactory cf = new TcpNetClientConnectionFactory("localhost", Integer.parseInt(System.getProperty(PORT))); cf.setSingleUse(true); return cf; } @Bean public ThreadAffinityClientConnectionFactory tacf() { return new ThreadAffinityClientConnectionFactory(cf()); } @Bean @ServiceActivator(inputChannel = "out") public TcpOutboundGateway outGate() { TcpOutboundGateway outGate = new TcpOutboundGateway(); outGate.setConnectionFactory(tacf()); outGate.setReplyChannelName("toString"); return outGate; } ``` -------------------------------- ### Custom Smack Providers Configuration File Source: https://docs.spring.io/spring-integration/reference/xmpp.html An example XML configuration file for Smack's providers. This file defines custom IQ and extension providers, mapping element names and namespaces to their respective Java classes. ```xml query jabber:iq:time org.jivesoftware.smack.packet.Time query https://jabber.org/protocol/disco#items org.jivesoftware.smackx.provider.DiscoverItemsProvider subscription https://jabber.org/protocol/pubsub org.jivesoftware.smackx.pubsub.provider.SubscriptionProvider ``` -------------------------------- ### Message Interface Definition Source: https://docs.spring.io/spring-integration/reference/message.html Defines the core Message interface with methods to get the payload and headers. ```java public interface Message { T getPayload(); MessageHeaders getHeaders(); } ``` -------------------------------- ### Configure AnnotatedControllerConfigurer Source: https://docs.spring.io/spring-integration/reference/graphql.html Provides the AnnotatedControllerConfigurer bean, used for configuring runtime wiring in the GraphQL setup. ```java @Bean AnnotatedControllerConfigurer annotatedDataFetcherConfigurer() { return new AnnotatedControllerConfigurer(); } ``` -------------------------------- ### Configuring an Endpoint with Annotations Source: https://docs.spring.io/spring-integration/reference/dsl/java-endpoints.html Demonstrates advising endpoints using annotations for transaction management. This approach simplifies configuration for common advice types. ```java @Transactional @ServiceActivator(inputChannel = "inputChannel") public void handleMessage(Message message) { // ... message handling logic ... } ``` -------------------------------- ### Mocking a MessageSource with Java Configuration Source: https://docs.spring.io/spring-integration/reference/testing.html Achieve the same mocking as the XML example using Java Configuration with MockIntegration.mockMessageSource. ```java @InboundChannelAdapter(channel = "results") @Bean public MessageSource testingMessageSource() { return MockIntegration.mockMessageSource(1, 2, 3); } ``` ```java StandardIntegrationFlow flow = IntegrationFlow .from(MockIntegration.mockMessageSource("foo", "bar", "baz")) .transform(String::toUpperCase) .channel(out) .get(); IntegrationFlowRegistration registration = this.integrationFlowContext.registration(flow) .register(); ``` -------------------------------- ### Configuring ZeroMQ Proxy Bean Source: https://docs.spring.io/spring-integration/reference/zeromq.html Example of configuring a ZeroMqProxy bean with SUB/PUB type, exposing capture socket, and setting frontend/backend ports. ```java @Bean ZeroMqProxy zeroMqProxy() { ZeroMqProxy proxy = new ZeroMqProxy(CONTEXT, ZeroMqProxy.Type.SUB_PUB); proxy.setExposeCaptureSocket(true); proxy.setFrontendPort(6001); proxy.setBackendPort(6002); return proxy; } ``` -------------------------------- ### Sample Gateway and Header Enricher Configuration (XML) Source: https://docs.spring.io/spring-integration/reference/message-history.html Example XML configuration for a messaging gateway and a header enricher, which will be tracked for message history. ```xml ``` -------------------------------- ### XPath Expression for Node Name Source: https://docs.spring.io/spring-integration/reference/xml/xpath-routing.html An example of an XPath expression that returns a string, such as the name of the root node. ```xml name(./node()) ``` -------------------------------- ### Configure PeriodicTrigger with Initial Delay and Fixed Rate Source: https://docs.spring.io/spring-integration/reference/endpoint.html Illustrates setting both the initial delay and fixed rate properties for a PeriodicTrigger. ```java PeriodicTrigger trigger = new PeriodicTrigger(Duration.ofSeconds(1)); trigger.setInitialDelay(Duration.ofSeconds(5)); trigger.setFixedRate(true); ``` -------------------------------- ### LockRegistryLeaderInitiator Bean Definition Source: https://docs.spring.io/spring-integration/reference/leadership-event-handling.html Example of defining a `LockRegistryLeaderInitiator` as a Spring bean, which uses a `LockRegistry` for leadership election. ```java @Bean public LockRegistryLeaderInitiator leaderInitiator(LockRegistry locks) { return new LockRegistryLeaderInitiator(locks); } ```