How to read message from a IBM MessageQueue or remote MQ - queue

Currently I'm doing MQ scripting in load runner using JAVA Vuser protocol.I'm using one Input queue and one Output queue. I'm able to put the message using Input queue successfully, But I'm unable to read the message from the output queue.
Below is the code I'm using to PUT/GET message from MQ. Kindly Let me know how to read message from output MQ.
lr.start_transaction("test_message");
try {
MQQueue destQueue1 = queueMgr.accessQueue(putQueueName, MQC.MQOO_INQUIRE);
pmo.options = MQC.MQPMO_NEW_MSG_ID;
requestMsg.replyToQueueName =getQueueName;
requestMsg.report=MQC.MQRO_PASS_MSG_ID;
requestMsg.format = MQC.MQFMT_STRING;
requestMsg.messageType=MQC.MQMT_REQUEST;
requestMsg.writeString(msgBody);
putQueue.put(requestMsg, pmo);
} catch(Exception e) {
lr.error_message("Error sending message.");
lr.exit(lr.EXIT_VUSER, lr.FAIL);
}
putQueue.close();
// Get the response message object from the response queue
try {
responseMsg.correlationId = requestMsg.messageId;
gmo.matchOptions=MQC.MQMO_MATCH_CORREL_ID;
gmo.options= MQC.MQGMO_NO_SYNCPOINT;
gmo.matchOptions=MQC.MQMO_NONE;
gmo.options= MQC.MQGMO_SYNCPOINT;
gmo.options= MQC.MQGMO_CONVERT;
gmo.options= MQC.MQGMO_WAIT;
gmo.waitInterval=MQC.MQWI_UNLIMITED;
gmo.waitInterval=60000;
getQueue.get(responseMsg, gmo);
System.out.println("QueueDepth for get:"+getQueue.getCurrentDepth());
//Check the message content
byte[] responseMsgData = responseMsg.readStringOfByteLength(responseMsg.getTotalMessageLength()).getBytes();
String msg = new String(responseMsgData);
lr.output_message(msg);
} catch(Exception e) {
lr.error_message("Error receiving message.");
lr.exit(lr.EXIT_VUSER, lr.FAIL);
}
lr.end_transaction("test_message", lr.AUTO);

You seem to be new to MQ. There are multiple problems in your code. Here is a piece of code demonstrating MQ Request/Response scenario. Code is developed using MQ v8. Modify it according to your MQ version and need.
/**
* Reqeust reply scenario
*/
public void mqRequestRespose() {
Hashtable<String, Object> properties;
try {
System.out.println("***Request/Reply Started *** ");
properties = new Hashtable<String, Object>();
properties.put("hostname", "localhost");
properties.put("port", new Integer(1414));
properties.put("channel", "APP.SVRCONN.CHN");
properties.put(MQConstants.USE_MQCSP_AUTHENTICATION_PROPERTY,"true");
properties.put(MQConstants.USER_ID_PROPERTY, "username");
properties.put(MQConstants.PASSWORD_PROPERTY, "password");
/**
* Connect to a queue manager
*/
MQQueueManager queueManager = new MQQueueManager("APPQMGR", properties);
/**
* Now create a subscription by providing our own temporary queue
*/
MQQueue mqRequestQ = queueManager.accessQueue("REQUEST.QUEUE", CMQC.MQOO_FAIL_IF_QUIESCING | CMQC.MQOO_OUTPUT );
MQQueue mqReplyQ = queueManager.accessQueue("REPLY.QUEUE", CMQC.MQOO_FAIL_IF_QUIESCING | CMQC.MQOO_INPUT_AS_Q_DEF);
/**
* Build a request message and send it to request queue.
*/
System.out.println("***Sending a request ***");
MQMessage msgRequest = new MQMessage();
msgRequest.writeUTF("Give me quote for IBM");
mqRequestQ.put(msgRequest);
/**
* Wait for 30 seconds to receive reply from reply queue
*/
System.out.println("*** Waiting for reply ***");
MQGetMessageOptions mqgmo = new MQGetMessageOptions();
mqgmo.options = CMQC.MQGMO_WAIT | CMQC.MQGMO_CONVERT;
mqgmo.waitInterval = 30000;
mqgmo.matchOptions=CMQC.MQMO_MATCH_CORREL_ID;
MQMessage msgReply = new MQMessage();
msgReply.correlationId = msgRequest.messageId;
try {
mqReplyQ.get(msgReply, mqgmo);
System.out.println("***Reply received***");
System.out.println("STOCK QUOTE: USD" + msgReply.readUTF());
}catch (MQException mqex) {
System.out.println("***No reply received in given time***");
}
} catch (Exception e) {
System.err.println(e);
e.printStackTrace();
for (Throwable t = e.getCause(); t != null; t = t.getCause()) {
System.out.println("... Caused by ");
t.printStackTrace();
}
}
}

Related

Unity Mirror - NetworkServer Send Message To Target Client

I'm not sure what I'm doing wrong here but I can't seem to get my message from the server to the client. Here is what I have so far:
protected virtual void RegisterHandlers(bool enable)
{
if (enable)
{
NetworkServer.RegisterHandler<ClientRequestLoadScene>(OnClientRequestedToLoadScene);
NetworkClient.RegisterHandler<ServerRequestLoadScene>(OnServerRequestLoadScene);
}
else
{
NetworkServer.UnregisterHandler<ClientRequestLoadScene>();
NetworkClient.UnregisterHandler<ServerRequestLoadScene>();
}
}
The above is called when the instance starts to register a new handler. Then I have the client call:
ClientRequestLoadScene msg = new ClientRequestLoadScene();
msg.scene = scene;
NetworkClient.Send(msg);
This is received by the server fine. Then the server runs the following:
private void OnClientRequestedToLoadScene(NetworkConnection conn, ClientRequestLoadScene msg)
{
...
...
ServerRequestLoadScene server_msg = new ServerRequestLoadScene();
server_msg.scene = msg.scene;
NetworkServer.SendToClientOfPlayer(conn.identity, msg);
...
...
}
The above message is never received by the client. I have also tried: NetworkServer.SendToAll(msg); and that is never received by the client either. What am I doing wrong?
The issue with the above is with these lines:
server_msg.scene = msg.scene;
NetworkServer.SendToClientOfPlayer(conn.identity, msg);
It needed to be:
server_msg.scene = msg.scene;
conn.Send(server_msg);

Forward an email(read using JavaMailApi) with Attachments by apache common java api

I'm reading messages from an Outlook webmail and getting a list of Messages('javax.mail.Message'). Now I want to forward these Messages to another email address using a java program.
private void sendTestMail(String from, String subject, String sentDate, Object object, Message message)
throws EmailException, Exception {
MultiPartEmail email = new MultiPartEmail();
email.setHostName(forwardHost);
email.addTo(mailRecipients(to));
email.setFrom(emailFrom);
email.setSubject(subject);
email.setMsg("Testing email by sahil.");
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("c:\\sahil\\test.jpg");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Picture_of_John");
attachment.setName("John.jpg");
email.attach(attachment);
MimeMultipart multiPart = getMimeMultipart(message);
email.addPart(multiPart);
email.send();
}
If I comment below two lines in above code then it works fine.
MimeMultipart multiPart = getMimeMultipart(message);
email.addPart(multiPart);
But with these two line I'm getting exception.
2020-04-20 15:41:44,271 ERROR com.st.ict.ols.service.impl.ReplyToMessageServiceImpl [main] Inner Exception occurred while processing individual message. Error stacktrace is[org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtpapp1.sgp.st.com:25
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1421)
at org.apache.commons.mail.Email.send(Email.java:1448)
at com.st.ict.ols.service.impl.ReplyToMessageServiceImpl.sendTestMail(ReplyToMessageServiceImpl.java:342)
at com.st.ict.ols.service.impl.ReplyToMessageServiceImpl.processMessage(ReplyToMessageServiceImpl.java:167)
at com.st.ict.ols.service.impl.MessageServiceImpl.processMessage(MessageServiceImpl.java:22)
at com.st.ict.ols.OlsMailSenderApplication.run(OlsMailSenderApplication.java:36)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:716)
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:703)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:304)
at com.st.ict.ols.OlsMailSenderApplication.main(OlsMailSenderApplication.java:27)
Caused by: javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.IOException: Exception writing Multipart
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1308)
at javax.mail.Transport.send0(Transport.java:255)
at javax.mail.Transport.send(Transport.java:124)
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1411)
... 10 more
Caused by: java.io.IOException: Exception writing Multipart
at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:83)
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:884)
at javax.activation.DataHandler.writeTo(DataHandler.java:317)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1652)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:961)
at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:553)
at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:81)
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:884)
at javax.activation.DataHandler.writeTo(DataHandler.java:317)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1652)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1850)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1259)
... 13 more
Caused by: javax.mail.MessagingException: Empty multipart: multipart/mixed;
boundary="----=_Part_1_1176580790.1587377502798"
at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:548)
at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:81)
... 24 more
Code I've written to retrieve MimeMultipart from JavaMailApi's Message object to set in apache common's org.apache.commons.mail.MultiPartEmail Object using attach function.
public MimeMultipart getMimeMultipart(Message message) throws Exception {
Object content = message.getContent();
if (content instanceof String)
return null;
if (content instanceof MimeMultipart) {
MimeMultipart multiPartResult = new MimeMultipart();
MimeMultipart multiPart = (MimeMultipart) content;
List<BodyPart> result = new ArrayList<>();
for (int i = 0; i < multiPart.getCount(); i++) {
BodyPart bodyPart = (BodyPart) multiPart.getBodyPart(i);
result.addAll(getMimeMultipart(bodyPart));
}
for(BodyPart part:result) {
multiPart.addBodyPart(part);
}
return multiPartResult;
}
return null;
}
private List<BodyPart> getMimeMultipart(BodyPart part) throws Exception{
List<BodyPart> result = new ArrayList<>();
Object content = part.getContent();
if (content instanceof InputStream || content instanceof String) {
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotBlank(part.getFileName())) {
result.add(part);
}
return result;
}
if (content instanceof MimeMultipart) {
MimeMultipart multipart = (MimeMultipart) content;
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = (BodyPart) multipart.getBodyPart(i);
result.addAll(getMimeMultipart(bodyPart));
}
}
return result;
}
I was able to forward email excluding attachments but facing issues forwarding with attachments/inline images.
Please help me with this issue.
I'm able to forward the complete message as an attachment, how to forward the message as it is.
MultiPartEmail email = new MultiPartEmail();
MimeMultipart mp = new MimeMultipart();
MimeBodyPart fmbp = new MimeBodyPart();
fmbp.setContent(message, "message/rfc822");
fmbp.setDisposition(Part.INLINE);
mp.addBodyPart(fmbp);
email.setContent(mp);
or if I use code
MimeMultipart mp = (MimeMultipart) message.getContent();
email.setContent(mp, message.getContentType());
I'm getting forwarded email like this
screenshot of forwarded encoded mail
Here the situation is reading mail from one mail server and sending the same message to another email id, within same application.
To achieve this, I used Java Mail API for both reading and sending.
Make sure to update the properties if you're using different host for both steps.
private void sendMailJavax(Message oldMessage) {
try {
// creating a new message using the older message
MimeMessage message = new MimeMessage((MimeMessage)oldMessage);
// updating properties as per sender Mailing API
message.getSession().getProperties().clear();
message.getSession().getProperties().setProperty("mail.smtp.host", forwardHost);
// setting appropriate headers. // make sure you don't append using .add methods.
message.setFrom(new InternetAddress(emailFrom));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setReplyTo(new Address[] { new InternetAddress(replyToEmail)});
Transport.send(message);
System.out.println("Email Sent successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}

pgjdbc-ng Ill-formed region:

Currently i'm trying to make a module which will listen to any changes via trigger on Postgres. I'm using pgjdbc-ng ver 0.8.2 ,download the JAR from maven repo central and add it as project reference.
Following is the code that i used :
public class ListenNotify
{
// Create the queue that will be shared by the producer and consumer
private BlockingQueue queue = new ArrayBlockingQueue(10);
// Database connection
PGConnection connection;
public ListenNotify()
{
// Get database info from environment variables
/*
String DBHost = System.getenv("DBHost");
String DBName = System.getenv("DBName");
String DBUserName = System.getenv("DBUserName");
String DBPassword = System.getenv("DBPassword");
*/
String DBHost = "127.0.0.1";
String DBName = "dbname";
String DBUserName = "postgres";
String DBPassword = "postgres";
// Create the listener callback
PGNotificationListener listener = new PGNotificationListener()
{
#Override
public void notification(int processId, String channelName, String payload)
{
// Add event and payload to the queue
queue.add("/channels/" + channelName + " " + payload);
}
};
try
{
// Create a data source for logging into the db
PGDataSource dataSource = new PGDataSource();
dataSource.setHost(DBHost);
dataSource.setPort(5432);
dataSource.setDatabaseName(DBName);
dataSource.setUser(DBUserName);
dataSource.setPassword(DBPassword);
// Log into the db
connection = (PGConnection) dataSource.getConnection();
// add the callback listener created earlier to the connection
connection.addNotificationListener(listener);
// Tell Postgres to send NOTIFY q_event to our connection and listener
Statement statement = connection.createStatement();
statement.execute("LISTEN q_event");
statement.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* #return shared queue
*/
public BlockingQueue getQueue()
{
return queue;
}
/**
*
* main entry point
*
* #param args
*/
public static void main(String[] args)
{
// Create a new listener
ListenNotify ln = new ListenNotify();
// Get the shared queue
BlockingQueue queue = ln.getQueue();
// Loop forever pulling messages off the queue
while (true)
{
try
{
// queue blocks until something is placed on it
String msg = queue.take().toString();
// Do something with the event
System.out.println(msg);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
Upon running, i got exception :
Ill-formed region: Indonesia [at index 0]
I have read the official git, saying that it should be fixed within some release number.
How do i apply those fix ?
Thank you
I know its a little bit late ;)
I had the same problem and also read that the problem was solved. But it does not seem that way.
Anyway the problem is this when creating the postgres database, LC_COLLATE is probably set to Indonesian_Indonesia.1252. When trying to establish a connection this value is compared with the java locales. In the Java Locales class, the value is probably in your language so the entry can not be found. However, to solve the problem you can set the default value of the Java locales to English. This is certainly not the best way to solve the problem, but it works. For security, I would put back after the connection is established
you can set the default value as follows:
Locale.setDefault(Locale.ENGLISH)

Gcloud PubSub Java implementation - java.util.concurrent.RejectedExecutionException

I use the sample snippet from GCloud documentation to receive msg as a subscriber. My pubsub gcloud jar version is 0.19.0-alpha
The problem is that I can receive the msg with attribute map but I keep having this exception:
2017-07-12 16:52:25,219 [grpc-default-worker-ELG-1-16] WARN io.netty.util.concurrent.DefaultPromise - An exception was thrown by io.grpc.netty.NettyClientHandler$3.operationComplete()
java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask#fbf4a6d rejected from java.util.concurrent.ScheduledThreadPoolExecutor#25cbe860[Terminated, pool size = 35, active threads = 0, queued tasks = 0, completed tasks = 2403]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ScheduledThreadPoolExecutor.delayedExecute(ScheduledThreadPoolExecutor.java:326)
at java.util.concurrent.ScheduledThreadPoolExecutor.schedule(ScheduledThreadPoolExecutor.java:533)
at java.util.concurrent.ScheduledThreadPoolExecutor.execute(ScheduledThreadPoolExecutor.java:622)
at java.util.concurrent.Executors$DelegatedExecutorService.execute(Executors.java:668)
at io.grpc.internal.SerializingExecutor.execute(SerializingExecutor.java:110)
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.onReady(ClientCallImpl.java:573)
at io.grpc.internal.DelayedStream$DelayedStreamListener.onReady(DelayedStream.java:398)
at io.grpc.internal.AbstractStream2$TransportState.notifyIfReady(AbstractStream2.java:305)
at io.grpc.internal.AbstractStream2$TransportState.onStreamAllocated(AbstractStream2.java:248)
at io.grpc.netty.NettyClientStream$TransportState.setHttp2Stream(NettyClientStream.java:227)
at io.grpc.netty.NettyClientHandler$3.operationComplete(NettyClientHandler.java:429)
at io.grpc.netty.NettyClientHandler$3.operationComplete(NettyClientHandler.java:417)
at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507)
at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:481)
at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:420)
at io.netty.util.concurrent.DefaultPromise.trySuccess(DefaultPromise.java:104)
After that, the program shuts and stop listening and getting msg. How to resolve this interruption and I even get rid of finally clause that has subscriber.stopAsync().
There is a bug in the snippet provided by them. You need to call get() on the messaegeIdFuture. Following code resolves the issue:
Publisher publisher = null;
String projectId = ServiceOptions.getDefaultProjectId();
ProjectTopicName topic = ProjectTopicName.of(projectId, "test");
ApiFuture<String> messageIdFuture = null;
try {
publisher = Publisher.newBuilder(topic).build();
ByteString data = ByteString.copyFromUtf8("my-message");
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
messageIdFuture = publisher.publish(pubsubMessage);
} catch (IOException e) {
e.printStackTrace();
} finally {
messageIdFuture.get(); //This resolves this issue.
// Wait on any pending requests
if (publisher != null) {
publisher.shutdown();
//publisher.awaitTermination(1, TimeUnit.SECONDS);
}
}

I want to send additional parameter with message by Smack API client in ejabberd

I am using Ejabberd as XMPP server and creating xmpp client in smack API.I want to send additional parameter with message.
My code is below :
public static void main(String[] args) throws SmackException,IOException,XMPPException {
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setResource("Smack")
.setSecurityMode(SecurityMode.disabled)
.setServiceName("localhost")
.setHost("localhost")
.setPort(Integer.parseInt("5222"))
.build();
AbstractXMPPConnection conn = new XMPPTCPConnection(config);
try {
conn.setPacketReplyTimeout(10000);
SASLAuthentication.unBlacklistSASLMechanism("PLAIN");
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
//SASLAuthentication.
conn.connect();
conn.login("test1#localhost","123456");
System.out.println("login successfull");
Message message = new Message();
String stanza = "i am vip";
message.setBody(stanza);
stanza+= "<type>.jpg</type>";
ChatManager manager = ChatManager.getInstanceFor(conn);
manager.createChat("vipul#localhost").sendMessage(message);
message.setBody(stanza);
System.out.println("Message Sent");
} catch (Exception e) {
e.printStackTrace();
}
}
By this code i am able to add type in xmpp stanza but i think it is not preferable way.So i need help to send additional parameter with message.
If i get solution this will be appreciated.
Thanks !!
you can add additional parameter like that-
Message message = new Message();
String stanza = "i am vip";
message.setBody(stanza);
message.addBody("customtag","Custom tag value");
message.addBody("customtag1","Custom tag value1");
and you can get it like-
String customtageValue= message.getBody("customtag");
for more detail check this link