Transfer a file using Apache Camel file component - spring

I am trying a demo file transfer program using Spring Boot and Apache Camel file component. I have exposed a REST Controller using Spring Boot which is calling an Apache Camel route and it is doing the file transfer. I have three files in the directory C:\CamelDemo\inputFolder namely input1.txt, input2.txt and input3.txt. I want to only transfer the file input2.txt in the output folder. My Spring Boot controller is as below:
package com.example.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/camel")
public class FileTransferController {
#Autowired private ProducerTemplate producerTemplate;
#RequestMapping(value="/file", method=RequestMethod.GET)
public String callCamelRoute() {
String fileName = "input2.txt";
Map<String, Object> headerMap = new HashMap<String, Object>();
headerMap.put("fileName", fileName);
producerTemplate.sendBodyAndHeaders("direct:transferFile", null, headerMap);
return "Route invoked";
}
}
My Route is as below:
package com.example.demo.route;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
#Component
public class FileTransferRoute extends RouteBuilder {
#SuppressWarnings("deprecation")
#Override
public void configure() {
errorHandler(defaultErrorHandler()
.maximumRedeliveries(3)
.redeliverDelay(1000)
.retryAttemptedLogLevel(LoggingLevel.WARN));
from("direct:transferFile")
.log("Route reached")
.log("file:C:\\CamelDemo\\inputFolder?fileName=${in.headers.fileName}&noop=true")
.pollEnrich("file://C:/CamelDemo/inputFolder?fileName=${in.headers.fileName}&noop=true")
.to("file://C:/CamelDemo/outputFolder?autoCreate=false")
.end();
}
}
But the first time I invoke this route, the file input1.txt is getting transferred even when I have specified the fileName parameter. Please help.

I think the issue is that your file name isn't being set, because you're not telling Camel that you're using a Simple expression, rather than a fixed URI.
Looking at the manual (https://camel.apache.org/manual/latest/pollEnrich-eip.html#_using_dynamic_uris), it implies that you will need
.pollEnrich().simple("file://C:/CamelDemo/inputFolder?fileName=${in.headers.fileName}&noop=true")
to be able to use the dynamic endpoint.

Related

How to fetch file from azure blob using spring boot

I want to fetch files from Azure blob storage. Following code does it fine-
package com.<your-resource-group>.<your-artifact-name>;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.WritableResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
#RestController
#RequestMapping("blob")
public class BlobController {
#Value("azure-blob://<your-container-name>/<your-blob-name>")
private Resource blobFile;
#GetMapping("/readBlobFile")
public String readBlobFile() throws IOException {
return StreamUtils.copyToString(
this.blobFile.getInputStream(),
Charset.defaultCharset());
}
#PostMapping("/writeBlobFile")
public String writeBlobFile(#RequestBody String data) throws IOException {
try (OutputStream os = ((WritableResource) this.blobFile).getOutputStream()) {
os.write(data.getBytes());
}
return "file was updated";
}
}
My Question -
The #Value annotation provides value to the Resource that is static (i.e I cannot put any variable containing my path as a string inside #Value).
How can I implement the this
In application properties try storing the path
#application.properties
blob.path=
We can use #Value("${...property's name}") annotation to access the above property in the Java class as follows:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ValueController {
#Value("${blob.path}")
private String path;
#GetMapping("")
..
}
}
Here try to use blob uri complete path in application properties and use the same in #value annotation as variable by map datatype
//
#Value("${blob.path}")
private Map<String, String> blobPath;
See this > java - How to read external properties based on value of local variable in Spring Boot? - Stack Overflow
& Value Spring: Spring #Value annotation tricks - DEV Community
Also see Requestmapping
Other references :
Spring Azure Blob Storage | DevGlan
spring batch - How to read the csv files from Azure Blob Storage in
Java with folder structure as 'dir1 / dir2 / dir3 /..'? - Stack Overflow

How do i connect my webMethods REStful service to my spring boot application

All i wanted to know is that if i have a flow service in SoftwareAG webMethods and i have converted it into a REStful service by making a rest resource and i have exposed it, so how do i make a call to that service via a spring boot appplication.
This is my code for the my spring application, Can someone please suggest me that how do i make a rest call to a webMethods Rest Resource flow service which is already been exposed.
A quick help is appreciated.
package com.scb.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.scb.entity.ReadingEntity;
import java.util.concurrent.atomic.AtomicLong;
#RestController
public class PreProcessorController {
private List<ReadingEntity> myEntity=new ArrayList();
private final AtomicLong counter = new AtomicLong();
#GetMapping("/GetData")
public void getData(#RequestBody ReadingSCBMLEntity entity) {
//myEntity.add(entity);
final String uri="http://uklvadapp881.uk.dev.net:5555/invoke/scb.wb.fm.support.flow.ResourceGet/_get?";
RestTemplate template=new RestTemplate();
String result=template.getForObject(uri, String.class);
System.out.println(result);
}
}

I cannot get a Restcontroller included in Spring Boot project - error 404

newbie pb on Spring Boot, I cannot get a RestController to be added to my application.
Here are the 2 files used to build this very simple app with maven:
1) Application.java
package com.learn.hello;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan(basePackages = "com.learn.hello.controller")
#RestController
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
HelloController.java
package com.learn.hello.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
public class HelloController {
#RequestMapping("/titi")
public String index() {
return "Greetings from titi Boot!";
}
}
Structure of the project
/src/main/java/com/learn/hello/Application.java
/src/main/java/com/learn/hello/controller/HelloController.java
/target/*
/pom.xml
localhost:8080 works
but localhost:8080/titi does not (404 not found)
Any idea ?
Thx
You forgot to provide request method RequestMethod.GET :
#RequestMapping(value = "/students", method = RequestMethod.GET)
You can use #GetMapping("/titi") instead of #RequestMapping("/titi") :
#GetMapping("/titi")
To all, thanks a lot to all for your answers.
#Valerio,
you were right it was correct!!! In fact an invisible char got added at the end of the filename: HelloController.java (me probably messing-up with Sublime...), thus it was not processed as a java file by maven...
Sorry for the noise.My apologies.
BTW if anybody knows about any sort of options to actually warn that a file located in the /src/main/java/* directories was not processed as a "regular java project" file I'm interested to know about it even though I doubt that this is really feasible and thus existing...

Spring Boot & Hibernate Validation's ConstraintMappingContributor

The hibernate validations documentation describes how to create ConstraintMappingContributors here.
It states:
You then need to specify the fully-qualified class name of the
contributor implementation in META-INF/validation.xml, using the
property key hibernate.validator.constraint_mapping_contributors. You
can specify several contributors by separating them with a comma.
Given I have many of these, what would be the most appropriate way to auto-discover these i.e. via #Component and add them dynamically at runtime to the ConstrainMappingConfiguration during Spring Boot startup.
For example.. if a developer creates a new ConstraintMappingContributor, it should be picked up and added automatically when spring boot starts, requiring no other file changes.
This is what I came up with, seems to be working for me.
package...
import org.hibernate.validator.spi.cfg.ConstraintMappingContributor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
#Configuration
public class ValidationConfiguration {
private final List<ConstraintMappingContributor> contributors;
public ValidationConfiguration(Optional<List<ConstraintMappingContributor>> contributors) {
this.contributors = contributors.orElseGet(ArrayList::new);
}
#Bean
public LocalValidatorFactoryBean validatorFactory() {
return new ValidatorFactoryBean(this.contributors);
}
}
package...
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.hibernate.validator.internal.cfg.context.DefaultConstraintMapping;
import org.hibernate.validator.spi.cfg.ConstraintMappingContributor;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import javax.validation.Configuration;
import java.util.List;
public class ValidatorFactoryBean extends LocalValidatorFactoryBean {
private final List<ConstraintMappingContributor> contributors;
ValidatorFactoryBean(List<ConstraintMappingContributor> contributors) {
this.contributors = contributors;
}
#Override
protected void postProcessConfiguration(Configuration<?> cfg) {
if (cfg instanceof HibernateValidatorConfiguration) {
HibernateValidatorConfiguration configuration = (HibernateValidatorConfiguration) cfg;
this.contributors.forEach(contributor -> contributor.createConstraintMappings(() -> {
DefaultConstraintMapping mapping = new DefaultConstraintMapping();
configuration.addMapping(mapping);
return mapping;
}));
}
}
}
I invoke it like this...
if(SpringValidatorAdapter.class.isInstance(this.validatorFactory)){
SpringValidatorAdapter.class.cast(this.validatorFactory).validate(entity, errors);
}

Spring cannot serve end point

I have a simple Spring back-end. It has a folder that contains controllers.
package com.movieseat.controllers;
// Java imports
import java.util.List;
// Spring imports
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
// Project imports
import com.movieseat.models.Movie;
import com.movieseat.services.MovieService;
#RestController
#RequestMapping("/api/movies")
public class MovieController {
#Autowired
private MovieService movieService;
#RequestMapping(value = "/allMovies", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Movie> getAllMovies() {
return movieService.getAllmovies();
}
}
In my Angular service I have a getAll() method:
public getAll<T>(): Observable<T[]> {
return this.http.get<T[]>('/api/movies/allMovies');
}
When I run the application I get a:
GET http://localhost:8090/api/movies/allMovies 404 ()
I have the server running on port 8090.
The following structure is used:
com
movieseat
Application.java
controllers
MovieController.java
models
MovieModel.java
repositories
MovieRepository.java
services
impl
MovieServiceImpl.java
MovieService.java
See if your controller class is picked up by spring scanning and performs mapping correctly. For example - If you are using Spring Boot, put a #SpringBootApplication on your main class that runs the app. The best way to know if your endpoint is scanned is to look for it when spring launches (in the log). You should look for something like
2017-09-17 14:45:49.522 INFO 2873 --- [main] RequestMappingHandlerMapping : Mapped "{[/allMovies],methods=[GET]}" onto public java.lang.String com.movieseat.controllers.MovieController.getAllMovies...

Resources