org.springframework.integration.dsl.IntegrationFlows Java Examples

The following examples show how to use org.springframework.integration.dsl.IntegrationFlows. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FinishedFileFlowConfiguration.java    From messaging with Apache License 2.0 6 votes vote down vote up
@Bean
IntegrationFlow finishedJobsFlow(BatchChannels channels,
 @Value("${completed-directory:${HOME}/Desktop/completed}") File finished,
 JdbcTemplate jdbcTemplate) {
 return IntegrationFlows
   .from(channels.completed())
   .handle(JobExecution.class,
     (je, headers) -> {
      String ogFileName = String.class.cast(headers
        .get(FileHeaders.ORIGINAL_FILE));
      File file = new File(ogFileName);
      mv(file, finished);
      List<Contact> contacts = jdbcTemplate.query(
        "select * from CONTACT",
        (rs, i) -> new Contact(
          rs.getBoolean("valid_email"),
          rs.getString("full_name"),
          rs.getString("email"),
          rs.getLong("id")));
      contacts.forEach(log::info);
      return null;
     }).get();
}
 
Example #2
Source File: JdbcSourceConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Bean
public IntegrationFlow pollingFlow() {
	IntegrationFlowBuilder flowBuilder = IntegrationFlows.from(jdbcMessageSource(),
			new Consumer<SourcePollingChannelAdapterSpec>() {

				@Override
				public void accept(SourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) {
					sourcePollingChannelAdapterSpec.poller(poller);
				}

			});
	if (this.properties.isSplit()) {
		flowBuilder.split();
	}
	flowBuilder.channel(this.source.output());
	return flowBuilder.get();
}
 
Example #3
Source File: StreamConsumer.java    From messaging with Apache License 2.0 6 votes vote down vote up
private IntegrationFlow incomingMessageFlow(SubscribableChannel incoming,
 String prefix) {

 Log log = LogFactory.getLog(getClass());

 return IntegrationFlows
  .from(incoming)
  .transform(String.class, String::toUpperCase)
  .handle(
   String.class,
   (greeting, headers) -> {
    log.info("greeting received in IntegrationFlow (" + prefix + "): "
     + greeting);
    return null;
   }).get();
}
 
Example #4
Source File: SftpSinkConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Bean
public IntegrationFlow ftpInboundFlow(SftpSinkProperties properties, SessionFactory<LsEntry> ftpSessionFactory) {
	SftpMessageHandlerSpec handlerSpec =
		Sftp.outboundAdapter(new SftpRemoteFileTemplate(ftpSessionFactory), properties.getMode())
			.remoteDirectory(properties.getRemoteDir())
			.remoteFileSeparator(properties.getRemoteFileSeparator())
			.autoCreateDirectory(properties.isAutoCreateDir())
			.temporaryFileSuffix(properties.getTmpFileSuffix());
	if (properties.getFilenameExpression() != null) {
		handlerSpec.fileNameExpression(properties.getFilenameExpression().getExpressionString());
	}
	return IntegrationFlows.from(Sink.INPUT)
		.handle(handlerSpec,
			new Consumer<GenericEndpointSpec<FileTransferringMessageHandler<LsEntry>>>() {
				@Override
				public void accept(GenericEndpointSpec<FileTransferringMessageHandler<LsEntry>> e) {
					e.autoStartup(false);
				}
			})
		.get();
}
 
Example #5
Source File: FtpSinkConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Bean
public IntegrationFlow ftpInboundFlow(FtpSinkProperties properties, SessionFactory<FTPFile> ftpSessionFactory) {
	FtpMessageHandlerSpec handlerSpec =
		Ftp.outboundAdapter(new FtpRemoteFileTemplate(ftpSessionFactory), properties.getMode())
			.remoteDirectory(properties.getRemoteDir())
			.remoteFileSeparator(properties.getRemoteFileSeparator())
			.autoCreateDirectory(properties.isAutoCreateDir())
			.temporaryFileSuffix(properties.getTmpFileSuffix());
	if (properties.getFilenameExpression() != null) {
		handlerSpec.fileNameExpression(properties.getFilenameExpression().getExpressionString());
	}
	return IntegrationFlows.from(Sink.INPUT)
		.handle(handlerSpec,
			new Consumer<GenericEndpointSpec<FileTransferringMessageHandler<FTPFile>>>() {
				@Override
				public void accept(GenericEndpointSpec<FileTransferringMessageHandler<FTPFile>> e) {
					e.autoStartup(false);
				}
			})
		.get();
}
 
Example #6
Source File: DemoApplication.java    From spring-and-kafka with Apache License 2.0 6 votes vote down vote up
@Bean
IntegrationFlow consumer() {

    log.info("starting consumer..");

    KafkaHighLevelConsumerMessageSourceSpec messageSourceSpec = Kafka.inboundChannelAdapter(
            new ZookeeperConnect(this.kafkaConfig.getZookeeperAddress()))
            .consumerProperties(props ->
                    props.put("auto.offset.reset", "smallest")
                            .put("auto.commit.interval.ms", "100"))
            .addConsumer("myGroup", metadata -> metadata.consumerTimeout(100)
                    .topicStreamMap(m -> m.put(this.kafkaConfig.getTopic(), 1))
                    .maxMessages(10)
                    .valueDecoder(String::new));

    Consumer<SourcePollingChannelAdapterSpec> endpointConfigurer = e -> e.poller(p -> p.fixedDelay(100));

    return IntegrationFlows
            .from(messageSourceSpec, endpointConfigurer)
            .<Map<String, List<String>>>handle((payload, headers) -> {
                payload.entrySet().forEach(e -> log.info(e.getKey() + '=' + e.getValue()));
                return null;
            })
            .get();
}
 
Example #7
Source File: FolderListener.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
private void initIntegrationFlow() {
    this.integrationFlow = IntegrationFlows
            .from(Files.inboundAdapter(new File(this.jobListenerConfiguration.getSourceFolder()))
                    .filter(this.fileFileListFilter)
                    .scanEachPoll(Boolean.TRUE)
                    .get(), e -> {
                e.poller(Pollers.fixedRate(this.jobListenerConfiguration.getPollerPeriod()).maxMessagesPerPoll(1000));
                e.autoStartup(Boolean.TRUE);
            })
            .transform(this.transformer,
                    e -> e.autoStartup(Boolean.TRUE))
            .handle(this.jobLaunchingMessageHandler)
            .channel(MessageChannels.direct())
            .handle(new JobExecutionFinishedMessageHandler())
            .get();

}
 
Example #8
Source File: IntegrationConfiguration.java    From building-microservices with Apache License 2.0 6 votes vote down vote up
@Bean
IntegrationFlow batchJobFlow(Job job,
                             JdbcTemplate jdbcTemplate,
                             JobLauncher launcher,
                             MessageChannel files) {

    return IntegrationFlows.from(files)
            .transform((GenericTransformer<Object,JobLaunchRequest>) file -> {
                System.out.println(file.toString());
                System.out.println(file.getClass());
                return null ;
            })
            .transform((GenericTransformer<File, JobLaunchRequest>) file -> {
                JobParameters jp = new JobParametersBuilder()
                        .addString("file", file.getAbsolutePath())
                        .toJobParameters();
                return new JobLaunchRequest(job, jp);
            })
            .handle(new JobLaunchingGateway(launcher))
            .handle(JobExecution.class, (payload, headers) -> {
                System.out.println("job execution status: " + payload.getExitStatus().toString());

                List<Person> personList = jdbcTemplate.query("select * from PEOPLE",
                        (resultSet, i) -> new Person(resultSet.getString("first"),
                                resultSet.getString("last"),
                                resultSet.getString("email")));

                personList.forEach(System.out::println);
                return null;
            })
            .get();

}
 
Example #9
Source File: IntegrationConfiguration.java    From messaging with Apache License 2.0 6 votes vote down vote up
@Bean
IntegrationFlow etlFlow(
 @Value("${input-directory:${HOME}/Desktop/in}") File dir) {

 return IntegrationFlows
 // <1>
  .from(Files.inboundAdapter(dir).autoCreateDirectory(true),
   consumer -> consumer.poller(spec -> spec.fixedRate(1000)))
  // <2>
  .handle(File.class, (file, headers) -> {
   log.info("we noticed a new file, " + file);
   return file;
  })
  // <3>
  .routeToRecipients(
   spec -> spec.recipient(csv(), msg -> hasExt(msg.getPayload(), ".csv"))
    .recipient(txt(), msg -> hasExt(msg.getPayload(), ".txt"))).get();
}
 
Example #10
Source File: MongodbSourceConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow startFlow() throws Exception {
    IntegrationFlowBuilder flow =  IntegrationFlows.from(mongoSource());
    if (config.isSplit()) {
        flow.split();
    }
    flow.channel(output);
    return flow.get();
}
 
Example #11
Source File: ConsumerApplication.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@Bean
IntegrationFlow greetingsFlow(MessageChannels channels) {
    return IntegrationFlows.from(channels.input())
            .handle(String.class, (payload, headers) -> {
                System.out.println(payload);
                return null;
            })
            .get();
}
 
Example #12
Source File: IntegrationConfiguration.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@Bean
IntegrationFlow incomingFiles(@Value("${HOME}/Desktop/in") File dir) {

    return IntegrationFlows.from(
            Files.inboundAdapter(dir)
                    .preventDuplicates()
                    .autoCreateDirectory(true),
            poller -> poller.poller(spec -> spec.fixedRate(1, TimeUnit.SECONDS)))
            .channel( this.files())
            .get();

}
 
Example #13
Source File: IntegrationDslConfig.java    From spring-reactive-sample with GNU General Public License v3.0 5 votes vote down vote up
@Bean
public IntegrationFlow inboundChannelAdapterFlow() {
    return IntegrationFlows
        .from(
            WebFlux
                .inboundGateway("/all")
                .requestMapping(m -> m.methods(HttpMethod.GET))
                // .requestPayloadType(ResolvableType.forClassWithGenerics(Flux.class, String.class))
                //.statusCodeFunction(m -> HttpStatus.OK)
        )
        .channel(c -> c.flux("outboundReactive.input"))
        .get();
}
 
Example #14
Source File: FileSourceConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow fileSourceFlow() {
	FileInboundChannelAdapterSpec messageSourceSpec = Files.inboundAdapter(new File(this.properties.getDirectory()));

	if (StringUtils.hasText(this.properties.getFilenamePattern())) {
		messageSourceSpec.patternFilter(this.properties.getFilenamePattern());
	} else if (this.properties.getFilenameRegex() != null) {
		messageSourceSpec.regexFilter(this.properties.getFilenameRegex().pattern());
	}

	if (this.properties.isPreventDuplicates()) {
		messageSourceSpec.preventDuplicates();
	}

	IntegrationFlowBuilder flowBuilder = IntegrationFlows
			.from(messageSourceSpec,
					new Consumer<SourcePollingChannelAdapterSpec>() {

						@Override
						public void accept(SourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) {
							sourcePollingChannelAdapterSpec
									.poller(defaultPoller);
						}

					});
	return FileUtils.enhanceFlowForReadingMode(flowBuilder, this.fileConsumerProperties)
			.channel(source.output())
			.get();
}
 
Example #15
Source File: MailSourceConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
/**
 * Method to build Integration flow for IMAP Idle configuration.
 * @param urlName Mail source URL.
 * @return Integration Flow object IMAP IDLE.
 */
private IntegrationFlowBuilder getIdleImapFlow(URLName urlName) {
	return IntegrationFlows.from(Mail.imapIdleAdapter(urlName.toString())
			.shouldDeleteMessages(this.properties.isDelete())
			.javaMailProperties(getJavaMailProperties(urlName))
			.selectorExpression(this.properties.getExpression())
			.shouldMarkMessagesAsRead(this.properties.isMarkAsRead()));
}
 
Example #16
Source File: AmazonS3SourceConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow s3InboundFlow(FileConsumerProperties fileConsumerProperties,
		S3InboundFileSynchronizer s3InboundFileSynchronizer) {
	S3InboundFileSynchronizingMessageSource s3MessageSource =
			new S3InboundFileSynchronizingMessageSource(s3InboundFileSynchronizer);
	s3MessageSource.setLocalDirectory(this.s3SourceProperties.getLocalDir());
	s3MessageSource.setAutoCreateLocalDirectory(this.s3SourceProperties.isAutoCreateLocalDir());

	return FileUtils.enhanceFlowForReadingMode(IntegrationFlows.from(s3MessageSource), fileConsumerProperties)
			.channel(Source.OUTPUT)
			.get();
}
 
Example #17
Source File: TacoOrderEmailIntegrationConfig.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow tacoOrderEmailFlow(
    EmailProperties emailProps,
    EmailToOrderTransformer emailToOrderTransformer,
    OrderSubmitMessageHandler orderSubmitHandler) {
  
  return IntegrationFlows
      .from(Mail.imapInboundAdapter(emailProps.getImapUrl()),
          e -> e.poller(
              Pollers.fixedDelay(emailProps.getPollRate())))
      .transform(emailToOrderTransformer)
      .handle(orderSubmitHandler)
      .get();
}
 
Example #18
Source File: AmqpIntegration.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow amqpReplyFlow(ConnectionFactory rabbitConnectionFactory,
		EchoService echoService) {
	return IntegrationFlows
			.from(Amqp.inboundGateway(rabbitConnectionFactory,
					this.echoQueueAndExchangeName))
			.transform(String.class, echoService::echo).get();
}
 
Example #19
Source File: FunctionConfiguration.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private IntegrationFlowBuilder integrationFlowFromProvidedSupplier(Supplier<?> supplier,
		Publisher<Object> beginPublishingTrigger, PollableBean pollable, GenericApplicationContext context,
		TaskScheduler taskScheduler, Type functionType) {

	IntegrationFlowBuilder integrationFlowBuilder;

	boolean splittable = pollable != null
			&& (boolean) AnnotationUtils.getAnnotationAttributes(pollable).get("splittable");

	if (pollable == null && FunctionTypeUtils.isReactive(FunctionTypeUtils.getInputType(functionType, 0))) {
		Publisher publisher = (Publisher) supplier.get();
		publisher = publisher instanceof Mono
				? ((Mono) publisher).delaySubscription(beginPublishingTrigger).map(this::wrapToMessageIfNecessary)
				: ((Flux) publisher).delaySubscription(beginPublishingTrigger).map(this::wrapToMessageIfNecessary);

		integrationFlowBuilder = IntegrationFlows.from(publisher);

		// see https://github.com/spring-cloud/spring-cloud-stream/issues/1863 for details about the following code
		taskScheduler.schedule(() -> { }, Instant.now()); // will keep AC alive
	}
	else { // implies pollable
		integrationFlowBuilder = IntegrationFlows.from(supplier);
		if (splittable) {
			integrationFlowBuilder = integrationFlowBuilder.split();
		}
	}

	return integrationFlowBuilder;
}
 
Example #20
Source File: SourceToFunctionsSupportTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow messageSourceFlow(Source source) {
	Supplier<Message<String>> messageSource = () -> MessageBuilder
			.withPayload("hello function")
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN)
			.build();
	return IntegrationFlows.from(messageSource).channel(source.output()).get();
}
 
Example #21
Source File: SpringIntegrationWebMvcApplication.java    From springfox-demos with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow toUpperGetFlow() {
    return IntegrationFlows.from(
            Http.inboundGateway("/conversions/pathvariable/{upperLower}")
                    .requestMapping(r -> r
                            .methods(HttpMethod.GET)
                            .params("toConvert"))
                    .headerExpression("upperLower",
                            "#pathVariables.upperLower")
                    .payloadExpression("#requestParams['toConvert'][0]")
                    .id("toUpperLowerGateway"))
            .<String>handle((p, h) -> "upper".equals(h.get("upperLower")) ? p.toUpperCase() : p.toLowerCase())
            .get();
}
 
Example #22
Source File: SpringIntegrationWebMvcApplication.java    From springfox-demos with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow toUpperFlow() {
    return IntegrationFlows.from(
            Http.inboundGateway("/conversions/upper")
                    .requestMapping(r -> r.methods(HttpMethod.POST)
                            .consumes("text/plain"))
                    .requestPayloadType(String.class)
                    .id("toUpperGateway"))
            .<String>handle((p, h) -> p.toUpperCase())
            .get();
}
 
Example #23
Source File: SpringIntegrationWebMvcApplication.java    From springfox-demos with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow toLowerFlow() {
    return IntegrationFlows.from(
            Http.inboundGateway("/conversions/lower")
                    .requestMapping(r -> r.methods(HttpMethod.POST)
                            .consumes("application/json"))
                    .requestPayloadType(Foo.class)
                    .id("toLowerGateway"))
            .<Foo>handle((p, h) -> new Foo(p.getBar()
                    .toLowerCase()))
            .get();
}
 
Example #24
Source File: SpringIntegrationWebFluxApplication.java    From springfox-demos with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow toUpperFlow() {
    return IntegrationFlows.from(
            WebFlux.inboundGateway("/conversions/upper")
                    .requestMapping(r -> r.methods(HttpMethod.POST)
                            .consumes("text/plain")))
            .<String>handle((p, h) -> p.toUpperCase())
            .get();
}
 
Example #25
Source File: SpringIntegrationWebFluxApplication.java    From springfox-demos with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow toUpperGetFlow() {
    return IntegrationFlows.from(
            WebFlux.inboundGateway("/conversions/pathvariable/{upperLower}")
                    .requestMapping(r -> r
                            .methods(HttpMethod.GET)
                            .params("toConvert"))
                    .headerExpression("upperLower", "#pathVariables.upperLower")
                    .payloadExpression("#requestParams['toConvert'][0]"))
            .<String>handle((p, h) -> "upper".equals(h.get("upperLower")) ? p.toUpperCase() : p.toLowerCase())
            .get();
}
 
Example #26
Source File: SpringIntegrationWebFluxApplication.java    From springfox-demos with Apache License 2.0 5 votes vote down vote up
@Bean
public IntegrationFlow toLowerFlow() {
    return IntegrationFlows.from(
            WebFlux.inboundGateway("/conversions/lower")
                    .requestMapping(r -> r.methods(HttpMethod.POST)
                            .consumes("application/json"))
                    .requestPayloadType(Foo.class))
            .<String>handle((p, h) -> p.toUpperCase())
            .get();
}
 
Example #27
Source File: CommoditiesReservationConsumerConfiguration.java    From event-based-shopping-system with MIT License 5 votes vote down vote up
@Bean
IntegrationFlow consumer() {

	log.info("starting consumer..");

	KafkaHighLevelConsumerMessageSourceSpec messageSourceSpec = Kafka
			.inboundChannelAdapter(
					new ZookeeperConnect(this.kafkaConfig
							.getZookeeperAddress()))
			.consumerProperties(
					props -> props.put("auto.offset.reset", "smallest")
							.put("auto.commit.interval.ms", "100"))
			.addConsumer(
					"myGroup",
					metadata -> metadata
							.consumerTimeout(100)
							.topicStreamMap(
									m -> m.put(this.kafkaConfig.getTopic(),
											1)).maxMessages(1)
							.valueDecoder(String::new));

	Consumer<SourcePollingChannelAdapterSpec> endpointConfigurer = e -> e.poller(p -> p.fixedDelay(100));

	return IntegrationFlows
			.from(messageSourceSpec, endpointConfigurer)
			.<Map<String, ConcurrentHashMap<String, String>>> handle(
					(payload, headers) -> {
						payload.entrySet().forEach(
								e -> orderEntryService.createOrderEntryFromJson(e.getValue()));
						return null;
					}).get();
}
 
Example #28
Source File: JavaDSLFileCopyConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public IntegrationFlow fileMover() {
    return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000)))
        .filter(onlyJpgs())
        .handle(targetDirectory())
        .get();
}
 
Example #29
Source File: JavaDSLFileCopyConfig.java    From tutorials with MIT License 5 votes vote down vote up
public IntegrationFlow fileMoverWithLambda() {
    return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000)))
        .filter(message -> ((File) message).getName()
            .endsWith(".jpg"))
        .handle(targetDirectory())
        .get();
}
 
Example #30
Source File: JavaDSLFileCopyConfig.java    From tutorials with MIT License 5 votes vote down vote up
public IntegrationFlow fileMoverWithPriorityChannel() {
    return IntegrationFlows.from(sourceDirectory())
        .filter(onlyJpgs())
        .channel("alphabetically")
        .handle(targetDirectory())
        .get();
}