Asynchronous messaging in websphare 855 setmessagelistener - asynchronous

Hi am migrating my application from jrun to websphere server and it has functionality of asynchronous messaging usnig message listener.
public void startMessageListener(final String queueName,
final MessageListener listener) throws Exception {
QueueSession queueSession = createNewQueueSession();
Queue queue = (Queue) queueContext.lookup(queueName);
QueueReceiver queueReceiver = queueSession.createReceiver((queue));
queueReceiver.setMessageListener(listener);
//LOG Forging fix-Fortify Scan TTP 345546 -START
log.debug("started queue " + queueName);
//LOG Forging fix-Fortify Scan TTP 345546 -END
}
when i use same code in websphere it throws error javax.jms.IllegalStateException: Method setMessageListener not permitted
Because the JMS spec does not allow you to use this feature in a JEE Container.
Please help me to make it work with less code changes.

Related

How to retry failed ConsumerRecord in reactor-kafka

I am trying on reactor-kafka for consuming messages. Everything else work fine, but I want to add a retry(2) for failing messages. spring-kafka already retries failed record 3 times by default, I want to achieve the same using reactor-kafka.
I am using spring-kafka as a wrapper for reactive-kafka. Below is my consumer template:
reactiveKafkaConsumerTemplate
.receiveAutoAck()
.map(ConsumerRecord::value)
.flatMap(this::consumeWithRetry)
.onErrorContinue((error, value)->log.error("something bad happened while consuming : {}", error.getMessage()))
.retryWhen(Retry.backoff(30, Duration.of(10, ChronoUnit.SECONDS)))
.subscribe();
Let us consider the consume method is as follows
public Mono<Void> consume(MessageRecord message){
return Mono.error(new RuntimeException("test retry"); //sample error scenario
}
I am using the following logic to retry the consume method on failure.
public Mono<Void> consumeWithRetry(MessageRecord message){
return consume(message)
.retry(2);
}
I want to retry consuming the message if the current consumer record fails with exception. I have tried to wrap the consume method with another retry(3) but that does not serve the purpose. The last retryWhen is only for retrying subscription on kafka rebalances.
#simon-baslé #gary-russell
Previously while retrying I was using the below approach:
public Mono<Void> consumeWithRetry(MessageRecord message){
return consume(message)
.retry(2);
}
But it was not retrying. After adding Mono.defer, the above code works and adds required retry.
public Mono<Void> consumeWithRetry(MessageRecord message){
return Mono.defer(()->consume(message))
.retry(2);
}

How can i get logs/debugging for an error 500?

I'm working on a .NET Core 2.0 web application. I got a mocked database where application works good. Today i created a clean database and got this error 500 both on IIS Express and on regular IIS.
The thing is: i couldn't debug why is throwing the error 500. The application just run.
I've currently tried:
Check IIS logs by activating stdoutLogEnabled="true" and the only log created was:
Hosting environment: Production Content root path:
C:\Users\pistolon\Downloads\peto Now listening on:
http://localhost:13361 Application started. Press Ctrl+C to shut down.
Debugging from start the startup.cs file.
When I switch back to the mocked db it works without error.
Do you any of you could point me on where could i get an exception or log for this?
You can use Event Viewer or Visual Studio Remote Debugging to debug your deployed applications.
Also, you can use a logging framework like Serilog and use one of it sinks like file sink and create a middleware which catches and logs your exceptions and write their StackTrace, Message, Source to a log file that you can read them.
Here is ErrorHandlingMiddleware implementation :
public class ErrorHandlingMiddleware
{
readonly RequestDelegate _next;
static ILogger<ErrorHandlingMiddleware> _logger;
public ErrorHandlingMiddleware(RequestDelegate next,
ILogger<ErrorHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
static async Task HandleExceptionAsync(
HttpContext context,
Exception exception)
{
string error = "An internal server error has occured.";
_logger.LogError($"{exception.Source} - {exception.Message} - {exception.StackTrace} - {exception.TargetSite.Name}");
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(new
{
error
}));
}
}
Usage :
app.UseMiddleware<ErrorHandlingMiddleware>();
I don't believe this is enough information to go off of, however if you're seeing that 500 error when using the real database and the mock database is working appropriately, I would bet that your issue is with the connection string. You can also check to ensure that you're in the development environment as well.
Update: You can also try to use app.UseDeveloperExceptionPage();

EJB server error on Wildfly 8.0

I have just started learning EJB and just wanted to execute my first code.
However, I am unable to remove this error:
Error-11:24:22,065 INFO [org.jboss.as.naming] (default task-3) JBAS011806:
Channel end notification received, closing channel Channel ID 4fb1d052
(inbound) of Remoting connection 6e42fa05 to null
I am using Java 1.8 with wildfly 8.0
Code ClientBean
public static void main(String[] args) throws CommunicationException {
try {
Context context = getInitialContext();
Hello remote=(Hello)context.lookup("HelloBean/remote");
System.out.println(remote.Hello());
}
catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Context getInitialContext() throws javax.naming.NamingException {
Properties properties=new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
properties.put(Context.PROVIDER_URL,"http-remoting://localhost:8080");
properties.put("jboss.naming.client.ejb.context", true);
return new javax.naming.InitialContext(properties);
}
Are you able to invoke your EJB and you see this error after that ?
Also please add credentials to InitialContext Properties ,like below
properties.put("java.naming.security.principal", "user");
properties.put("java.naming.security.credentials", "pass");
You can add this user to wildfly , using addUser.bat/sh scripts. It will ask for something like "use this user for EJB remote communication " , say yes for that.

How can I use SignalR as Azure Service Bus transport?

I'm trying to find an alternative to using REST to read Azure Service Bus Topic Subscriptions from the browser. Seems like SignalR would be a natural for this but I can't seem to find anyone that has done it. I'm not talking about scale-out, just a SignalR Hub that would relay a set of Service Bus functions back and forth to the browser. I'm thinking of functions like, addReceiver(string topic, string subscriptionID);defineSubscription(string name, string subscriptionRule);deleteSubscription(string name);postMessageToTopic(string topic, string message);addReceiver would initiate an async receive on the subscription. Each time a message came available from Service Bus, a function would be called on the JS client.
Here's some code to point people in the right direction.
namespace SBTester
{
public class SBHub : Hub
{
public void AddReceiver(string topic, string subscriptionName, string subscriptionFilter)
{
string messageData;
TopicConnector.Initialize( topic,
Context.ConnectionId + "." + subscriptionName,
subscriptionFilter);
// Initiate receive loop on Service Bus
TopicConnector.SBClient.OnMessage((receivedMessage) =>
{
try
{
// Process the message
messageData = receivedMessage.GetBody<string>();
Clients.Caller.onMessage(topic, messageData);
}
catch
{
// Handle any message processing specific exceptions here
}
});
}
public void DefineSubscription(string topic, string subscriptionRule)
{
// Call Service Bus to create Subscription on the Specified topic
}
public void PostMessageToTopic(string topic, string message)
{
// Call Service Bus to send a message
Clients.All.addNewMessageToPage(topic, message);
}
}
}
From your Hub code you could directly call the Service Bus APIs to send messages or directly use Service Bus APIs from JavaScript/Browsers: http://developers.de/blogs/damir_dobric/archive/2014/03/27/microsoft-azure-service-bus-receiving-of-messages-from-queue-and-topic-with-javascript.aspx

NullReferenceException when initializing NServiceBus within web application Application_Start method

I am running the 2.0 RTM of NServiceBus and am getting a NullReferenceException when my MessageModule binds the CurrentSessionContext to my NHibernate sessionfactory.
From within my Application_Start, I call the following method:
public static void WithWeb(IUnityContainer container)
{
log4net.Config.XmlConfigurator.Configure();
var childContainer = container.CreateChildContainer();
childContainer.RegisterInstance<ISessionFactory>(NHibernateSession.SessionFactory);
var bus = NServiceBus.Configure.WithWeb()
.UnityBuilder(childContainer)
.Log4Net()
.XmlSerializer()
.MsmqTransport()
.IsTransactional(true)
.PurgeOnStartup(false)
.UnicastBus()
.ImpersonateSender(false)
.LoadMessageHandlers()
.CreateBus();
var activeBus = bus.Start();
container.RegisterInstance(typeof(IBus), activeBus);
}
When the bus is started, my message module starts with the following:
public void HandleBeginMessage()
{
try
{
CurrentSessionContext.Bind(_sessionFactory.OpenSession());
}
catch (Exception e)
{
_log.Error("Error occurred in HandleBeginMessage of NHibernateMessageModule", e);
throw;
}
}
In looking at my log, we are logging the following error when the bind method is called:
System.NullReferenceException: Object reference not set to an instance of an object.
at NHibernate.Context.WebSessionContext.GetMap()
at NHibernate.Context.MapBasedSessionContext.set_Session(ISession value)
at NHibernate.Context.CurrentSessionContext.Bind(ISession session)
Apparently, there is some issue in getting access to the HttpContext. Should this call to configure NServiceBus occur later in the lifecycle than Application_Start? Or is there another workaround that others have used to get handlers working within an Asp.NET Web application?
Thanks,
Steve
I wouldn't use WebSessionContext in this case, precisely because NServiceBus can operate independently of HttpContexts. If you want to use a single session context implementation for both web and NServiceBus message handling, I'd implement NHibernate.Context.ICurrentSessionContext with an hybrid storage, i.e. if HttpContext.Current != null, use the HttpContext as session storage. Otherwise use a thread local storage. This is similar to what Castle ActiveRecord does with its HybridWebThreadScopeInfo.

Resources