integration payload router issues - spring-integration

i am trying to configure payload router to route messages to either rabbitmq,ibmq and kafka MOM's. payload will have to be routed to more than one MOM in some cases, here is the code
#ServiceActivator(inputChannel = "routerChannel", outputChannel = "outputChannel")
public PayloadTypeRouter router(Log message) {
PayloadTypeRouter router = new PayloadTypeRouter();
for (Platform platform : new MessageConfig().getConfig(message.getClientKey())) {
System.out.println("platform type=" + platform.getRouter());
if (platform.getRouter().equals(BridgeType.Bridge.rabbitmq.toString())) {
router.setChannelMapping(String.class.getName(), "rabbitChannel");
} else if (platform.getRouter().equals(BridgeType.Bridge.ibmmq.toString())) {
router.setChannelMapping(String.class.getName(), "ibmmqChannel");
} else if (platform.getRouter().equals(BridgeType.Bridge.kafka.toString())) {
router.setChannelMapping(String.class.getName(), "kafkaChannel");
}
}
return router;
}
earlier i had below code which was working fine(sending to individual MOM but not to two at same time)
#Router(inputChannel = "routerChannel")
public String route(Log message) {
log.info("message in the router='{}'", message.getClientKey());
for (Platform platform : new MessageConfig().getConfig(message.getClientKey())) {
System.out.println("platform type=" + platform.getRouter());
if (platform.getRouter().equals(BridgeType.Bridge.rabbitmq.toString())) {
return "rabbitChannel";
} else if (platform.getRouter().equals(BridgeType.Bridge.ibmmq.toString())) {
return "ibmmqChannel";
} else if (platform.getRouter().equals(BridgeType.Bridge.kafka.toString())) {
return "kafkaChannel";
}
}
return "errorChannel";
}
not sure what i am doing wrong , appreciate any help here

PayloadTypeRouter and MethodInvokingRouter only support one destination.
Use a RecipientListRouter with Recipients with MessageSelectors if you want to route to multiple destinations.
Actually, I was wrong; you can simply return List<String> from your second example.

Related

How to write test cases for webclient onstatus method

I am new to spring webclient and i'm trying to write test case for failure case for onstatus method.
Logic here
private Function<ClientResponse, Mono<? extends Throwable>> errorStrategy() {
return response -> {
return response.bodyToMono(Errors.class).flatMap(errorResponse -> {
log.info("Track Error ----> {}", errorResponse.getErrorCode());
Errors errors = new Errors(errorResponse.getErrorMsg());
return Mono.error(errors);
});
};
}
public Mono<EnterpriseSearchResponse> getCustomerID(EnterpriseSearchRequest searchRequest) {
Mono<EnterpriseSearchResponse> response = this.client.method(HttpMethod.GET)
.uri(enterpriseSearchURI + enterpriseSearchContext)
.header("Authorization", "Bearer " + enterpriseSearchAuthToken)
.accept(new MediaType[] { MediaType.APPLICATION_JSON }).bodyValue(searchRequest).retrieve()
.onStatus(HttpStatus::is5xxServerError, errorStrategy())
.onStatus(HttpStatus::is4xxClientError, errorStrategy()).bodyToMono(EnterpriseSearchResponse.class);
return response;
}
I want to write test case for errorStategy method.
can someone suggest how to achieve that?

MassTransit Consumer not getting called

In the following sample program (using MassTransit, Azure ServiceBus), I am able to send messages to the queue, but my Receive Endpoint/Consumer does not seems to get the message. What am I doing wrong here? (Simple publish and a handler example given in this link(http://masstransit-project.com/MassTransit/quickstart.html) works fine!)
static async Task MainAsync(string[] args)
{
var bus = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
{
var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", "{sb}", "{sb-name}");
var host = cfg.Host(serviceUri, h =>
{
h.OperationTimeout = TimeSpan.FromSeconds(5);
h.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
"RootManageSharedAccessKey",
"{key}");
h.TransportType = TransportType.NetMessaging;
});
cfg.ReceiveEndpoint(host, "test_queue", ep =>
{
ep.Consumer<SayHelloCommandConsumer>();
});
});
bus.Start();
await SendAHello(bus);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
bus.Stop();
}
private static async Task SendAHello(IBusControl bus)
{
var sendToUri = new Uri("queue-end-point-address");
var endPoint = await bus.GetSendEndpoint(sendToUri);
await endPoint.Send<ISayHello>( new
{
Message = "Hello there !"
});
}
}
public class SayHelloCommandConsumer : IConsumer<ISayHello>
{
public Task Consume(ConsumeContext<ISayHello> context)
{
var command = context.Message;
return Console.Out.WriteLineAsync($"Recieved a message {command}");
}
}
public interface ISayHello
{
string Message { get; set; }
}
}
The queue address looked suspect, and it seems like you've corrected it.

DNX (rc1-final): IHttpConnectionFeature not found

Using the latest rc1-final version of ASP.NET 5, I'm attempting to find the remote IP address inside an Azure API App controller method.
When running the code, 'context' is this.HttpContext, inside the controller method.
But feature is coming back null, since the feature doesn't exist.
IHttpConnectionFeature feature = context.Features.Get<IHttpConnectionFeature>();
Does anything have to be enabled in the configuration to have this feature be available?
Thanks,
Kirk
I had the same problem.
The following code works for me:
public async Task<IActionResult> Index()
{
if (!UserID.HasValue)
{
UpdateRemoteIp(HttpContext);
var remoteIpAddress = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString();
if (remoteIpAddress == null)
{
throw new Exception("Cannot determine client IP");
}
await _userService.LoginAnonymous(remoteIpAddress);
string url = UriHelper.GetDisplayUrl(Request);
return Redirect(url);
}
PrepareViewModel();
return View("Index", ViewModel);
}
private static void UpdateRemoteIp(HttpContext httpContext)
{
var xForwardedForHeaderValue = httpContext.Request.Headers.GetCommaSeparatedValues(XForwardedForHeaderName);
if (xForwardedForHeaderValue != null && xForwardedForHeaderValue.Length > 0)
{
IPAddress ipFromHeader;
int? port;
if (IPAddressWithPortParser.TryParse(xForwardedForHeaderValue[0], out ipFromHeader, out port))
{
var connection = httpContext.Connection;
var remoteIPString = connection.RemoteIpAddress?.ToString();
if (!string.IsNullOrEmpty(remoteIPString))
{
httpContext.Request.Headers[XOriginalIPName] = remoteIPString;
}
if (port.HasValue)
{
if (connection.RemotePort != 0)
{
httpContext.Request.Headers[XOriginalPortName] = connection.RemotePort.ToString(CultureInfo.InvariantCulture);
}
connection.RemotePort = port.Value;
}
connection.RemoteIpAddress = ipFromHeader;
}
}
}
Hope it helps you

Dart web audio noteOn internal error

I'm trying to get dart to play an audio, but everytime I try to play the Audio I get the following error:
Internal error: 'dart:_blink': error: line 248: native function 'AudioBufferSourceNode_noteOn_Callback_RESOLVER_STRING_1_double' (2 arguments) cannot be found
Native_AudioBufferSourceNode_noteOn_Callback(mthis, when) native "AudioBufferSourceNode_noteOn_Callback_RESOLVER_STRING_1_double";
This is the my Audio class:
class Audio {
static List<Audio> _loadQueue = new List<Audio>();
String _url;
bool loaded = false;
AudioBufferSourceNode _source;
Audio(this._url) {
if (audioContext == null) {
_loadQueue.add(this);
}
else {
load();
}
}
void load() {
print("Loading sound: " + _url);
HttpRequest req = new HttpRequest();
req.open("GET", _url);
req.responseType = "arraybuffer";
req.onLoad.listen((e) {
_source = audioContext.createBufferSource();
print("Found sound: " + _url + ". Decoding...");
audioContext.decodeAudioData(req.response).then((buffer) {
_source.buffer = buffer;
_source.connectNode(gainNode);
_source.connectNode(audioContext.destination);
loaded = true;
});
});
req.send();
}
void play() {
if (!loaded) { return; }
_source.noteOn(0);
}
void stop() {
if (!loaded) return;
_source.noteOff(0);
}
static void loadAll() {
_loadQueue.forEach((e) {e.load();});
}
}
The audio context and gain node is created in another class like this:
audioContext = new AudioContext();
gainNode = audioContext.createGain();
gainNode.connectNode(audioContext.destination);
Audio.loadAll();
I don't know what the problem is, especially since it says it's internal, and that it's missing arguments, but the noteOn function only takes one argument.
I was facing the same issue using dart 1.6. It seems noteOn has been replaced by start in the latest spec/implementation.
The AudioBufferSourceNode Interface (http://webaudio.github.io/web-audio-api/#the-audiobuffersourcenode-interface)
Porting notes (https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext#Changes_to_methods_used_to_start.2Fstop_AudioBufferSourceNode_and_OscillatorNode)

NetMQ in Publisher and subscriber not working

I'm trying to implement the NetMQ Pub/Sub Model, but the Subscriber is not receiving any messages. What possibly is wrong here?
private static void ServerTask()
{
using (var context = NetMQContext.Create())
{
using (var socket = context.CreateSubscriberSocket())
{
socket.Bind("tcp://10.120.19.109:5000");
socket.Subscribe(string.Empty);
while (true)
{
Thread.Sleep(100);
string receivedMessage = socket.ReceiveString();
Console.WriteLine("Received: " + receivedMessage);
}
}
}
}
public static void ClientTask()
{
using (NetMQContext ctx = NetMQContext.Create())
{
using (var socket = ctx.CreatePublisherSocket())
{
socket.Connect("tcp://10.120.19.109:5000");
string obj = "hi";
socket.Send(obj);
}
}
}
Both are in different apps.
If you are new to NetMQ I suggest reading the zeromq guide http://zguide.zeromq.org/page:all.
Bottom line is that you are sending the message before the subscriber sent the subscription.
Pubsub in zeromq and NetMQ is like radio, you will only get messages from the moment you start listen.
To simple way to do it (not a real life solution) is to sleep for some time after the connect.
For real life solution I need to understand what are you trying to achieve
issue is like
using (NetMQContext ctx = NetMQContext.Create())
{
using (var publisher = ctx.CreatePushSocket())
{
publisher.Bind("tcp://localhost:5000");
int i = 0;
while (true)
{
try
{
publisher.Send(i.ToString(), dontWait:true);
Console.WriteLine(i.ToString());
}
catch (Exception e)
{
}
finally
{
i++;
}
}
}
Now , this code works. But if I move my while(true) loop outside. and call this code from some other function Which forces push socket and context to be created as new everytime.. this doesnot work.

Resources