In a test project based of the nServiceBus pub/sub sample, I've replace the bus.publish with bus.send in the server. The server sends 50 messages with a 1sec wait after each 5 (ie 10 burst of 5 messages). The client does not get all the messages.
The soln has 3 projects - Server, Client, and common messages. The server and client are hosted via the nServiceBus generic host. Only a single bus is defined.
Both client and server are configured to use StructureMap builder and BinarySerialisation.
Server Endpoint:
public class EndPointConfig : AsA_Publisher, IConfigureThisEndpoint, IWantCustomInitialization
{
public void Init()
{
NServiceBus.Configure.With()
.StructureMapBuilder()
.BinarySerializer();
}
}
Server Code :
for (var nextId = 1; nextId <= 50; nextId++)
{
Console.WriteLine("Sending {0}", nextId);
IDataMsg msg = new DataMsg { Id = nextId, Body = string.Format("Batch Msg #{0}", nextId) };
_bus.SendLocal(msg);
Console.WriteLine(" ...sent {0}", nextId);
if ((nextId % 5) == 0)
Thread.Sleep(1000);
}
Client Endpoint:
public class EndPointConfig : AsA_Client, IConfigureThisEndpoint, IWantCustomInitialization
{
public void Init()
{
NServiceBus.Configure.With()
.StructureMapBuilder()
.BinarySerializer();
}
}
Client Clode:
public class DataMsgHandler : IMessageHandler<IDataMsg>
{
public void Handle(IDataMsg msg)
{
Console.WriteLine("DataMsgHandler.Handle({0}, {1}) - ({2})", msg.Id, msg.Body, Thread.CurrentThread.ManagedThreadId);
}
}
Client and Server App.Config:
<MsmqTransportConfig InputQueue="nsbt02a" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5" />
<UnicastBusConfig DistributorControlAddress="" DistributorDataAddress="">
<MessageEndpointMappings>
<add Messages="Test02.Messages" Endpoint="nsbt02a" />
</MessageEndpointMappings>
</UnicastBusConfig>
All run via VisualStudio 2008.
All 50 messages are sent - but after the 1st or 2nd batch. only 1 msg per batch is sent?
Any ideas? I'm assuming config or misuse but ....?
Your main problem is that you've configured both processes to use the same input queue. Give each one their own queue.
Related
I want to complete a function with netty
http send data to netty -> netty proxy data to target https
I start a client to connet target link.
I tried proxy to http ,it's ok
But when i use https link , future.isSuccess() return false
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) msg;
Bootstrap b = new Bootstrap();
b.group(ctx.channel().eventLoop())
.channel(ctx.channel().getClass())
.handler(new HttpProxyInitializer(ctx.channel()));
ChannelFuture f = b.connect("https://xxxx",443);
outboundChannel = f.channel();
f.addListener(new ChannelFutureListener() {
#Override
public void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
future.channel().writeAndFlush(msg);
} else {
ctx.channel().close();
}
}
});
}
}
So is netty connet https not feasible?
How you connect does not look correct.
You would use:
b.connect("hostname", 443)
Ensure your HttpProxyInitializer also add the SslHandler to the ChannelPipeline.
Also if things not work you should inspect the future.cause() as it will contain a Throwable which will provide details about why the operation failed.
my goal is to maintain the traceId (of a brave.Span) between a rabbitMq sender and consumer. In order to achieve this I use spring-cloud-sleuth autoconfigured in version 2.1.0.RELEASE
When creating a span and eventually sending a message over RabbitTemplate to the broker and receiving it in the same (test) application I would expect spring-cloud-sleuth to maintain the traceId between sender and consumer.
My observation is that when sending a Message over RabbitMq the traceId is not correctly appended to the headers of the message. There is indeed a traceId/context appended and submitted, but it is a new one, different from that I read when creating the span (see code below).
On the consumer the newly created (but unrelated) traceId then is correctly processed and can be read from the Tracer.
#Test
public void messaging_ShouldPreserveTraceId() {
final Span spanProbe = tracer.newTrace().name("TraceIT").start();
spanProbe.start();
final String traceIdBefore = spanProbe.context().traceIdString();
log.info("TRACE CONTEXT BEFORE: " + spanProbe.context());
log.info("TRACE ID BEFORE: " + traceIdBefore);
log.info("TRACE ID BEFORE Parent: " + spanProbe.context().parentIdString());
// send - the actual rabbitTemplate Call (in the producer) happens in the same (main) thread
try{
producer.sendAsString(ROUTING_KEY, "CONTENT");
}finally {
spanProbe.finish();
}
// consume
Awaitility.await().atMost(TEN_MINUTES).until(() -> {
assertThat(consumer.spans(), hasSize(1));
});
// assert
final Span consumerSpan = consumer.spans().get(0);
final String traceIdAfter = consumerSpan.context().traceIdString();
log.info("TRACE CONTEXT AFTER: " + consumerSpan.context());
log.info("TRACE ID AFTER: " + traceIdAfter);
assertEquals(traceIdAfter, traceIdBefore);
}
The consumer (test class field) is:
static class TraceTestListener implements MessageListener {
private final List<Span> spans = new ArrayList<>();
#Autowired
private Tracing tracing;
#Override
public void onMessage(Message message) {
log.info("---> Received MESSAGE: {}", message);
spans.add(tracing.tracer().currentSpan());
}
public List<Span> spans() {
return spans;
}
}
[main ] sl.euth.debug.boot.rabbit.trace.TraceIT.messaging_ShouldPreserveTraceId(114) - TRACE CONTEXT BEFORE: 23ca5b3b9f068716/23ca5b3b9f068716
[main ] sl.euth.debug.boot.rabbit.trace.TraceIT.messaging_ShouldPreserveTraceId(115) - TRACE ID BEFORE: 23ca5b3b9f068716
[main ] sl.euth.debug.boot.rabbit.trace.TraceIT.messaging_ShouldPreserveTraceId(116) - TRACE ID BEFORE Parent: null
[Rabbit-4 ] org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$InternalConsumer.handleDelivery(897) - Storing delivery for consumerTag: 'amq.ctag-HnuJEiuRHAHTYfzypJDW6w' with deliveryTag: '1' in Consumer#6c27e700: tags=[[amq.ctag-HnuJEiuRHAHTYfzypJDW6w]], channel=Cached Rabbit Channel: AMQChannel(amqp://asdasdaa#35.243.142.228:5672/asdasdaa,2), conn: Proxy#33ebe4f0 Shared Rabbit Connection: SimpleConnection#3a88f6fb [delegate=amqp://asdasdaa#35.243.142.228:5672/asdasdaa, localPort= 58539], acknowledgeMode=AUTO local queue size=0
// Please mind how in the received message's headers a different traceId is present
[test_rabbitConsumer1] org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.handle(469) - Received message: (Body:'[B#1989ac6d(byte[7])' MessageProperties [headers={X-B3-SpanId=b335bbaf06a08879, X-B3-Sampled=0, X-B3-TraceId=b335bbaf06a08879}, timestamp=Tue May 21 13:44:57 CEST 2019, contentType=text/plain; charset=utf-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=test-exchange, receivedRoutingKey=test-routing, deliveryTag=1, consumerTag=amq.ctag-HnuJEiuRHAHTYfzypJDW6w, consumerQueue=test-queue])
[test_rabbitConsumer1] org.springframework.cloud.sleuth.log.Slf4jScopeDecorator.log(180) - Starting scope for span: b335bbaf06a08879/46a25dd87dc63878
[test_rabbitConsumer1] org.springframework.cloud.sleuth.log.Slf4jScopeDecorator.decorateScope(102) - With parent: 4663306299116113188
[test_rabbitConsumer1] sl.euth.debug.boot.rabbit.trace.TraceIT$TraceTestListener.onMessage(150) - ---> Received MESSAGE: (Body:'[B#1989ac6d(byte[7])' MessageProperties [headers={}, timestamp=Tue May 21 13:44:57 CEST 2019, contentType=text/plain; charset=utf-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=test-exchange, receivedRoutingKey=test-routing, deliveryTag=1, consumerTag=amq.ctag-HnuJEiuRHAHTYfzypJDW6w, consumerQueue=test-queue])
[test_rabbitConsumer1] org.springframework.cloud.sleuth.log.Slf4jScopeDecorator.log(180) - Closing scope for span: b335bbaf06a08879/46a25dd87dc63878
[main ] sl.euth.debug.boot.rabbit.trace.TraceIT.messaging_ShouldPreserveTraceId(133) - TRACE CONTEXT AFTER: b335bbaf06a08879/46a25dd87dc63878
//💥 Here we would expect the traceId to be 23ca5b3b9f068716
[main ] sl.euth.debug.boot.rabbit.trace.TraceIT.messaging_ShouldPreserveTraceId(134) - TRACE ID AFTER: b335bbaf06a08879
[main ] sl.euth.debug.commons.lib.test.junit.rules.LoggingRule$1.evaluate(77) - Finished test messaging_ShouldPreserveTraceId(sl.euth.debug.boot.rabbit.trace.TraceIT) in 13102 ms
I have tried to troubleshoot this issue a lot and now as a last resort posting it here. Please help me!
Issue: I am able to send mail by calling the class from a main method. When I try to call the same class from a Struts2 Action class it does not send an email, rather gives the below error. I am using Jboss EAP 7.0.0.Alpha1. I think the issue might be lying in the JBoss configuration. I have also changed the Standalone-full.xml file.(To note I am using standalone-full.xml and my other web components are working fine).
I did run it in debug mode and saw all values are getting populated. When we run it from the struts2 action class it does not send the message.
Changes made to Standalone-full.xml:
<mail-session name="java:jboss/mail/Default"
from="somedummyuser#gmail.com" jndi-
name="java:jboss/mail/Default">
<smtp-server password="******" username="somedummyuser"
ssl="true" outbound-socket-binding-ref="mail-smtp"/>
</mail-session>
</subsystem>
<outbound-socket-binding name="mail-smtp">
<remote-destination host="smtp.gmail.com" port="465"/>
</outbound-socket-binding>
Java Code:
public class SendEmail {
private MailSender mailSender;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String from, String to, String subject, String
msg)
throws Exception,NamingException{
//creating message
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(from);
simpleMailMessage.setTo(to);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(msg);
//sending message
System.out.println("SimpleMailMessage object:"+simpleMailMessage);
mailSender.send(simpleMailMessage);
}
}
Class with MainMethod Which is executing the above code findE and sending the email successfully:
public class MainMethod_SendEmail {
public static void main(String[] args) throws Exception{
Resource r=new ClassPathResource("webApplicationContext.xml");
BeanFactory b=new XmlBeanFactory(r);
SendEmail m=(SendEmail)b.getBean("sendEmail");
String sender = AccessPropertiesUtil.getInstance().getProperty("from");
String receiver = AccessPropertiesUtil.getInstance().getProperty("to");
String subject =
AccessPropertiesUtil.getInstance().getProperty("subject");
String message =
AccessPropertiesUtil.getInstance().getProperty("message");
m.sendMail(sender, receiver, subject, message);
System.out.println("success");
}
}
But the same mail sending code is not getting executed from a Struts2 Action class:
Struts2Action Class:
public String execute()
{
emailSending();
}
private void emailSending() throws Exception
{
System.out.println("Sending Email");
String sender =
AccessPropertiesUtil.getInstance().getProperty("from");
String receiver =
AccessPropertiesUtil.getInstance().getProperty("to");
String subject =
AccessPropertiesUtil.getInstance().getProperty("subject");
String message =
AccessPropertiesUtil.getInstance().getProperty("message");
sendEmail.sendMail(sender, receiver, subject, message);
}
Error Trace:
org.springframework.mail.MailSendException: Mail server connection
failed;
nested exception is javax.mail.MessagingException: Could not
connect to SMTP host: smtp.gmail.com, port: 465, response: -1. Failed
messages: javax.mail.MessagingException: Could not connect to SMTP
host: smtp.gmail.com, port: 465, response: -1; message exception details
(1) are:
2016-07-13 02:45:33 ERROR stderr:71 - Failed message 1:
2016-07-13 02:45:33 ERROR stderr:71 - javax.mail.MessagingException:
Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
2016-07-13 02:45:33 ERROR stderr:71 - at
com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2042)
2016-07-13 02:45:33 ERROR stderr:71 - at
com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
2016-07-13 02:45:33 ERROR stderr:71 - at
javax.mail.Service.connect(Service.java:364)
I'm writing an application that should retranslate some data received from Bluetooth LE device to all TCP clients connected to it. The platform is Windows 10. For now it is console application with C++/CX enable as Bluetooth LE API is only available from WinRT. The BLE part is ready but I cannot make proper TCP server using WinRT.
I'm creating TCP socket server using StreamSocketListener and store all StreamSocket objects in std::vector. In a loop iterate the vector and send the data to all connected clients. Everything is working fine at this point. But should one client disconnect and the server crashes as it tries to send a data to disconnected socket and throws COMException and I cannot catch it.
Visual Studio 2015 crash message: Exception thrown at 0x752ADAE8 in SensoCLI.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x02EFE1C0. Call stack points to auto sent = writeTask.get();
Below is the minimal listing of my app that corresponds to the problem:
#include "pch.h"
#using <platform.winmd>
#using <Windows.winmd>
using namespace std;
using namespace Windows::Foundation;
using namespace Platform;
using namespace concurrency;
namespace WFC = Windows::Foundation::Collections;
namespace WNS = Windows::Networking::Sockets;
namespace WSS = Windows::Storage::Streams;
bool shouldStop = false;
// TCP socket server
WNS::StreamSocketListener ^tcpListener;
vector<WNS::StreamSocket ^> *tcpClients;
void OnSocketConnectionReceived(WNS::StreamSocketListener ^aListener, WNS::StreamSocketListenerConnectionReceivedEventArgs ^args);
int main(Array<String ^> ^args)
{
tcpClients = new vector<WNS::StreamSocket ^>();
tcpListener = ref new WNS::StreamSocketListener();
tcpListener->ConnectionReceived += ref new TypedEventHandler<WNS::StreamSocketListener ^, WNS::StreamSocketListenerConnectionReceivedEventArgs ^>(&OnSocketConnectionReceived);
auto listenTask = create_task(tcpListener->BindServiceNameAsync("53450"));
listenTask.wait();
while (!shouldStop)
{
if (tcpClients->size() > 0)
{
auto netDataStream = ref new WSS::InMemoryRandomAccessStream();
auto writer = ref new WSS::DataWriter(netDataStream);
auto reader = ref new WSS::DataReader(netDataStream->GetInputStreamAt(0));
String^ stringToSend("Hello");
writer->WriteUInt32(writer->MeasureString(stringToSend));
writer->WriteString(stringToSend);
auto aTask = create_task(writer->StoreAsync());
unsigned int bytesStored = aTask.get();
aTask = create_task(reader->LoadAsync(bytesStored));
aTask.wait();
auto netData = reader->ReadBuffer(bytesStored);
for (auto iter = tcpClients->begin(); iter != tcpClients->end(); ++iter)
{
create_task((*iter)->OutputStream->WriteAsync(netData)).then([](task<unsigned int> writeTask) {
try
{
// Try getting an exception.
auto sent = writeTask.get();
wcout << L"Sent: " << sent << endl;
}
catch (Exception^ exception)
{
wcout << L"Send failed with error: " << exception->Message->Data() << " " << endl;
}
});
}
Sleep(1000);
}
}
}
void OnSocketConnectionReceived(WNS::StreamSocketListener ^aListener, WNS::StreamSocketListenerConnectionReceivedEventArgs ^args)
{
auto sock = args->Socket;
tcpClients->push_back(sock);
}
How do I properly catch the exception and handle disconnected StreamSocket?
I am using the below configuration to connect to Online LDAP Test Server
<className>com.worklight.core.auth.ext.LdapLoginModule</className>
<parameter name="ldapProviderUrl" value="ldap://forumsys.com:389"/>
<parameter name="ldapTimeoutMs" value="2000"/>
<parameter name="ldapSecurityAuthentication" value="simple"/>
<parameter name="validationType" value="searchPattern"/>
<parameter name="ldapSecurityPrincipalPattern" value="uid={username},ou=mathematicians,dc=example,dc=com"/>
<parameter name="ldapSearchFilterPattern" value="(uid={username})"/>
<parameter name="ldapSearchBase" value="dc=example,dc=com"/>
But i am getting
"FWLSE4014W: LdapLoginModule authentication failed. Reason 'javax.naming.CommunicationException: forumsys.com:389 [Root exception is java.net.SocketTimeoutException: connect timed out]" error.
Is there anything wrong with the settings ?
that server is pretty old and the LDAP service is no longer active
This exception is not unique to MobileFirst and so I remove this information from the question.
See here: http://www-01.ibm.com/support/docview.wss?uid=swg21599197.
I suggest that you will follow the same solution steps, which are to verify that you are attempting to correctly connect to your LDAP server.
Recommended but optional: Download a third-party tool (such as the ldapsearch tool) that can verify your server(s) are able to communicate with the LDAP server independent of the Portal ConfigEngine configuration task. Run the tool directly from the Portal server (and Deployment Manager if clustered) to verify all servers can communicate with the LDAP server.
In this particular use case, a network firewall was configured to block all traffic to the LDAP server except from IP addresses that were explicitly whitelisted / permitted to connect. The primary Portal server had been configured in the network firewall to communicate with the LDAP server, but the Deployment Manager had not been configured. Adding the Deployment Manager IP address to the firewall rules allowed the configuration task to complete successfully.
I recently used ForumSys LDAP Test server mentioned using KeyCloak successfully:
You can find all the configuration here.
If you are looking for an easily configurable dockerized test LDAP authentication server.
try
https://hub.docker.com/r/upekshejay/simple-ldap-test-server
I used ForumSys LDAP Test Server
, here is fully tested sample used to check if a user is already inside an active directory.
public class ActiveDirectoryManagerTwo {
final static String domainTree = "dc=example,dc=com";
public static void main(String[] args) {
System.out.println(isInsideActiveDirectory("tesla"));
}
public static String isInsideActiveDirectory(String userName) {
String isFound = "NO";
String rootDN = "cn=read-only-admin,dc=example,dc=com";
String rootPWD = "password";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://ldap.forumsys.com :389");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, rootDN);
environment.put(Context.SECURITY_CREDENTIALS, rootPWD);
DirContext dirContext = null;
NamingEnumeration<?> results = null;
try {
System.out.println("inside try");
dirContext = new InitialDirContext(environment);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(uid=" + userName + "))";
results = dirContext.search(domainTree, filter, controls);
if (results.hasMore()) {
isFound = "YES";
} else {
}
} catch (NamingException e) {
System.out.println("inside catch");
e.printStackTrace();
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
}
}
if (dirContext != null) {
try {
dirContext.close();
} catch (Exception e) {
}
}
}
return isFound;
}
}