Spring Integration DSL: handle vs enrichHeaders - spring-integration

I have an integration flow where I use a handler to add a few headers to my message:
...
.handle(this, "enrichTaskHeaders")
...
public Message<?> enrichTaskHeaders(Map<String, String> payload) {
var id = payload.get("id");
var t = service.findById(id);
return MessageBuilder.withPayload(payload).setHeader("a", t.getA())
.setHeader("b", t.getB())
.setHeader(...)
.build();
}
It works perfectly, but since it's about enriching headers, I was wondering if I could use a enrichHeaders method to do the same thing. The closest I could get to is this:
.enrichHeaders(consumer -> consumer.headerFunction("a",
(Message<Map<String, String>> m) -> {
var id = m.getPayload().get("id");
var t = service.findById(id);
return t.getA();})
.headerFunction("b",
(Message<Map<String, String>> m) -> {
var id = m.getPayload().get("id");
var t = service.findById(i));
return t.getB();})
...
)
It works as intended, but it is obviously underefficient since I duplicate a service call for each header I add. Is there a way to rewrite it efficiently or should I just go with the handler?

See enrich(Consumer<EnricherSpec> enricherConfigurer) instead. It has an option like requestPayload() to have that your service call only once. And then you use a .headerFunction() for your purposes.
.enrich(e -> e
.<Map<String, String>>requestPayload(m -> "v")
.headerFunction("a", m -> m.getPayload().getA())
.headerFunction("b", m -> m.getPayload().getB()))
See more in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/message-transformation.html#payload-enricher

Related

Flutter compute function not called if parameter is not a primitive?

I tried to send a Map to a compute, but computer is never called. The strange point is if I replace Map with int, it works:
void A()
{
var map=Map();
map["p1"]=90;
D("before compute");
var r1 = await compute(p1, 10);
D("after compute(p1) : $r1");
var r2 = await compute(p2, map);
// code never reaches here!
D("after compute(p2) : $r2");
}
static int p2(Map p)
{
return p["p1"]*10;
}
static int p1(int z)
{
return z*10;
}
output is :
after compute(p1) : 100
Flutter compute methods use Isolates and its only transfer (null, num, bool, double, String) types.
https://api.flutter.dev/flutter/dart-isolate/SendPort/send.html
Just define exact type of Map that "p2" receives as parameter:
static int p2(Map<String,int> p)
{
return p["p1"]*10;
}
Try passing a const parameter:
var r2 = await compute(p2, {"p1":90});

How to chan "RoomDatabase and Retrofit" in RxJava

I'm using the Repository Pattern.
I would like to implement logic that if there is no value in the internal DB returns the value of the Api Response and inserts it in the internal DB.
Received internal DB Value (Single Type) Return final value if found, Request Server Api if not found Insert in internal DB (Completable Type) Return final value (Single Type)
If any of these processes call onError, the final return value of this logic shall be onError.
fun getAllStudent(): Single<List<StudentEntity>> =
cache.getAllStudent().onErrorResumeNext { getAllStudentRemote() }
private fun getAllStudentRemote(): Single<List<StudentEntity>> =
remote.getAllMember()
.map { memberData -> memberData.students }
.map { studentList -> studentList.map { student -> studentMapper.mapToEntity(student) } }
.doOnSuccess { studentEntityList -> cache.insertStudents(studentEntityList) }
This is how I tried.
However, in the insert section, because it cannot subscribe, It cannot insert into internal DB or detect onError.
How can I implement this logic? ++ I'm sorry for my poor English.
Since you need to wait for cache.insertStudents() to complete, one thing you can do is to chain cache.insertStudents() into the stream using flatMap.
For example:
fun getAllStudent(): Single<List<StudentEntity>> =
cache.getAllStudent().onErrorResumeNext { getAllStudentRemote() }
private fun getAllStudentRemote(): Single<List<StudentEntity>> =
remote.getAllMember()
.map { memberData -> memberData.students }
.map { studentList -> studentList.map { student -> studentMapper.mapToEntity(student) } }
.flatMap { studentEntityList ->
cache.insertStudents(studentEntityList) // Completable
.toSingleDefualt(studentEntityList) // Convert to Single<List<StudentEntity>>
}
Also note that .do... operators are side-effect operators, and you should not do any operation that can affect the stream.

Rewrite code for Automapper v5.0 to v4.0

Automapper v4.0 was very straight forward to use within a method, can someone help rewrite this for v5.0 please (specifically the Mapper code):
public IEnumerable<NotificationDto> GetNewNotifications()
{
var userId = User.Identity.GetUserId();
var notifications = _context.UserNotifications
.Where(un => un.UserId == userId && !un.IsRead)
.Select(un => un.Notification)
.Include(n => n.Gig.Artist)
.ToList();
Mapper.CreateMap<ApplicationUser, UserDto>();
Mapper.CreateMap<Gig, GigDto>();
Mapper.CreateMap<Notification, NotificationDto>();
return notifications.Select(Mapper.Map<Notification, NotificationDto>);
}
UPDATE:
It seems that EF Core doesn't project what AutoMapper is mapping with:
return notifications.Select(Mapper.Map<Notification, NotificationDto>);
But I do get results in Postman with the following code:
return notifications.Select(n => new NotificationDto()
{
DateTime = n.DateTime,
Gig = new GigDto()
{
Artist = new UserDto()
{
Id = n.Gig.Artist.Id,
Name = n.Gig.Artist.Name
},
DateTime = n.Gig.DateTime,
Id = n.Gig.Id,
IsCancelled = n.Gig.IsCancelled,
Venue = n.Gig.Venue
},
OriginalVenue = n.OriginalVenue,
OriginalDateTime = n.OriginalDateTime,
Type = n.Type
});
If you want to keep using static instance - the only change is in mapper initialization:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ApplicationUser, UserDto>();
cfg.CreateMap<Gig, GigDto>();
cfg.CreateMap<Notification, NotificationDto>();
});
Also you should run this code only once per AppDomain (somewhere on startup for example) and not every time you calling GetNewNotifications.

Java 8 CompletedFuture web crawler doesn't crawl past one URL

I'm playing with the newly introduced concurrency features in Java 8, working exercises from the book "Java SE 8 for the Really Impatient" by Cay S. Horstmann. I created the following web crawler using the new CompletedFuture and jsoup. The basic idea is given a URL, it'll find first m URLs on that page and repeat the process n times. m and n are parameters, of course. Problem is the program fetches the URLs for the initial page but doesn't recurse. What am I missing?
static class WebCrawler {
CompletableFuture<Void> crawl(final String startingUrl,
final int depth, final int breadth) {
if (depth <= 0) {
return completedFuture(startingUrl, depth);
}
final CompletableFuture<Void> allDoneFuture = allOf((CompletableFuture[]) of(
startingUrl)
.map(url -> supplyAsync(getContent(url)))
.map(docFuture -> docFuture.thenApply(getURLs(breadth)))
.map(urlsFuture -> urlsFuture.thenApply(doForEach(
depth, breadth)))
.toArray(size -> new CompletableFuture[size]));
allDoneFuture.join();
return allDoneFuture;
}
private CompletableFuture<Void> completedFuture(
final String startingUrl, final int depth) {
LOGGER.info("Link: {}, depth: {}.", startingUrl, depth);
CompletableFuture<Void> future = new CompletableFuture<>();
future.complete(null);
return future;
}
private Supplier<Document> getContent(final String url) {
return () -> {
try {
return connect(url).get();
} catch (IOException e) {
throw new UncheckedIOException(
" Something went wrong trying to fetch the contents of the URL: "
+ url, e);
}
};
}
private Function<Document, Set<String>> getURLs(final int limit) {
return doc -> {
LOGGER.info("Getting URLs for document: {}.", doc.baseUri());
return doc.select("a[href]").stream()
.map(link -> link.attr("abs:href")).limit(limit)
.peek(LOGGER::info).collect(toSet());
};
}
private Function<Set<String>, Stream<CompletableFuture<Void>>> doForEach(
final int depth, final int breadth) {
return urls -> urls.stream().map(
url -> crawl(url, depth - 1, breadth));
}
}
Test case:
#Test
public void testCrawl() {
new WebCrawler().crawl(
"http://en.wikipedia.org/wiki/Java_%28programming_language%29",
2, 10);
}
The problem is in the following code:
final CompletableFuture<Void> allDoneFuture = allOf(
(CompletableFuture[]) of(startingUrl)
.map(url -> supplyAsync(getContent(url)))
.map(docFuture -> docFuture.thenApply(getURLs(breadth)))
.map(urlsFuture -> urlsFuture.thenApply(doForEach(depth, breadth)))
.toArray(size -> new CompletableFuture[size]));
For some reason you are doing all this inside a stream of one element (is that a part of the exercise?). The result is that allDoneFuture is not tracking the completion of the sub-tasks. It's tracking the completion of the Stream<CompletableFuture> that comes from doForEach. But that stream is ready right away and the futures inside of it are never asked to complete.
Fix it by removing the stream that doesn't do anything helpful:
final CompletableFuture<Void> allDoneFuture=supplyAsync(getContent(startingUrl))
.thenApply(getURLs(breadth))
.thenApply(doForEach(depth,breadth))
.thenApply(futures -> futures.toArray(CompletableFuture[]::new))
.thenCompose(CompletableFuture::allOf);

Anonymous type and getting values out side of method scope

I am building an asp.net site in .net framework 4.0, and I am stuck at the method that supposed to call a .cs class and get the query result back here is my method call and method
1: method call form aspx.cs page:
helper cls = new helper();
var query = cls.GetQuery(GroupID,emailCap);
2: Method in helper class:
public IQueryable<VariablesForIQueryble> GetQuery(int incomingGroupID, int incomingEmailCap)
{
var ctx = new some connection_Connection();
ObjectSet<Members1> members = ctx.Members11;
ObjectSet<groupMember> groupMembers = ctx.groupMembers;
var query = from m in members
join gm in groupMembers on m.MemberID equals gm.MemID
where (gm.groupID == incomingGroupID) && (m.EmailCap == incomingEmailCap)
select new VariablesForIQueryble(m.MemberID, m.MemberFirst, m.MemberLast, m.MemberEmail, m.ValidEmail, m.EmailCap);
//select new {m.MemberID, m.MemberFirst, m.MemberLast, m.MemberEmail, m.ValidEmail, m.EmailCap};
return query ;
}
I tried the above code with IEnumerable too without any luck. This is the code for class VariablesForIQueryble:
3:Class it self for taking anonymouse type and cast it to proper types:
public class VariablesForIQueryble
{
private int _emailCap;
public int EmailCap
{
get { return _emailCap; }
set { _emailCap = value; }
}`....................................
4: and a constructor:
public VariablesForIQueryble(int memberID, string memberFirst, string memberLast, string memberEmail, int? validEmail, int? emailCap)
{
this.EmailCap = (int) emailCap;
.........................
}
I can't seem to get the query result back, first it told me anonymous type problem, I made a class after reading this: link text; and now it tells me constructors with parameters not supported. Now I am an intermediate developer, is there an easy solution to this or do I have to take my query back to the .aspx.cs page.
If you want to project to a specific type .NET type like this you will need to force the query to actually happen using either .AsEnumerable() or .ToList() and then use .Select() against linq to objects.
You could leave your original anonymous type in to specify what you want back from the database, then call .ToList() on it and then .Select(...) to reproject.
You can also clean up your code somewhat by using an Entity Association between Groups and Members using a FK association in the database. Then the query becomes a much simpler:
var result = ctx.Members11.Include("Group").Where(m => m.Group.groupID == incomingGroupID && m.EmailCap == incomingEmailCap);
You still have the issue of having to do a select to specify which columns to return and then calling .ToList() to force execution before reprojecting to your new type.
Another alternative is to create a view in your database and import that as an Entity into the Entity Designer.
Used reflection to solve the problem:
A: Query, not using custom made "VariablesForIQueryble" class any more:
//Method in helper class
public IEnumerable GetQuery(int incomingGroupID, int incomingEmailCap)
{
var ctx = new some_Connection();
ObjectSet<Members1> members = ctx.Members11;
ObjectSet<groupMember> groupMembers = ctx.groupMembers;
var query = from m in members
join gm in groupMembers on m.MemberID equals gm.MemID
where ((gm.groupID == incomingGroupID) && (m.EmailCap == incomingEmailCap)) //select m;
select new { m.MemberID, m.MemberFirst, m.MemberLast, m.MemberEmail, m.ValidEmail, m.EmailCap };
//select new VariablesForIQueryble (m.MemberID, m.MemberFirst, m.MemberLast, m.MemberEmail, m.ValidEmail, m.EmailCap);
//List<object> lst = new List<object>();
//foreach (var i in query)
//{
// lst.Add(i.MemberEmail);
//}
//return lst;
//return query.Select(x => new{x.MemberEmail,x.MemberID,x.ValidEmail,x.MemberFirst,x.MemberLast}).ToList();
return query;
}
B:Code to catch objects and conversion of those objects using reflection
helper cls = new helper();
var query = cls.GetQuery(GroupID,emailCap);
if (query != null)
{
foreach (var objRow in query)
{
System.Type type = objRow.GetType();
int memberId = (int)type.GetProperty("MemberID").GetValue(objRow, null);
string memberEmail = (string)type.GetProperty("MemberEmail").GetValue(objRow, null);
}
else
{
something else....
}

Resources