Smack - How to read a MultiUserChat's configuration? - java

I tried to create a multiuserchat with Java. I'm using smack library.
Here is my code to create multiuserchat:
MultiUserChat muc = new MultiUserChat(connection, "roomname#somehost");
muc.create("mynickname");
Form form = muc.getConfigurationForm();
Form submitForm = form.createAnswerForm();
submitForm.setAnswer("muc#roomconfig_roomname", "A nice formatted Room Name");
submitForm.setAnswer("muc#roomconfig_roomdesc", "The description. It should be longer.");
muc.sendConfigurationForm(submitForm);
muc.addMessageListener(mucMessageListener); // mucMessageListener is a PacketListener
Then, I tried to capture the message sent by this room created above using mucMessageListener:
private PacketListener mucMessageListener = new PacketListener() {
public void processPacket(Packet packet) {
if (packet instanceof Message) {
Message message = (Message) packet;
// this is where I got the problem
}
}
}
As the message received by other part (the user who is not the owner of this multiuserchat), can he somehow get the value set in this line above:
submitForm.setAnswer("muc#roomconfig_roomname", "A nice formatted Room Name");
You see, getting just the JID of the room is not really good for the view. I expect I could have a String which value is "A nice formatted Room Name".
How can we get that?

You can easily get its configurations like name and etc from this code:
MultiUserChatManager mucManager = MultiUserChatManager.getInstanceFor(connection);
RoomInfo info = mucManager.getRoomInfo(room.getRoom());
now you can get its informations like this:
String mucName = info.getName();
Boolean isPersistence = info.isPersistent();
and etc.

Retrieving the value of muc#roomconfig_romname is described in XEP-45 6.4. Smack provides the MultiUserChat.getRoomInfo() method to perform the query.
RoomInfo roomInfo = MultiUserChat.getRoomInfo(connection, "roomname#somehost.com")
String roomDescription = roomInfo.getDescription()

If you want to read a value of var for example title name of room in config
Form form = chat.getConfigurationForm();
String value = form.getField("muc#roomconfig_roomname").getValues().next();
then do what ever you want with value..

Related

RabbitMQ parsing "client_properties" header from c#

I'm listening for connection changes through events pluging ("amq.rabbitmq.event", "connection.#").
It works properly so I'm adding at java side two additional parameters as clientproperties, to get the identity of the user that connects or disconnect.
However at c# side I can only access these properties as a list of byte[], and not sure on how to convert it to a Dictionary or so..
If I print all entries
if (args.BasicProperties.Headers.TryGetValue("client_properties", out object value))
{
var items = value as List<object>;
foreach(var item in items)
{
Console.WriteLine($"{item.GetType().ToString()}");
var bytes = item as byte[];
result.Add(Encoding.UTF8.GetString(bytes));
}
}
I can see this:
{<<"platform">>,longstr,<<"Java">>}
{<<"capabilities">>,table,[{<<"connection.blocked">>,bool,true},{<<"basic.nack">>,bool,true},{<<"exchange_exchange_bindings">>,bool,true},{<<"authentication_failure_close">>,bool,true},{<<"publisher_confirms">>,bool,true},{<<"consumer_cancel_notify">>,bool,true}]}
{<<"groupId">>,longstr,<<"1e6e935f0d4d9ec446d67dadc85cbafd10d1a095">>}
{<<"information">>,longstr,<<"Licensed under the MPL. See http://www.rabbitmq.com/">>}
{<<"version">>,longstr,<<"4.8.1">>}
{<<"copyright">>,longstr,<<"Copyright (c) 2007-2018 Pivotal Software, Inc.">>}
{<<"product">>,longstr,<<"RabbitMQ">>}
What kind of object format is and how can I parse this?:
{<<id>>,type,<<value>>}
Apparently ( as for an answer I got on Rabbit client google group for this questions ), client_properties is something that's not created to being read by the receiving party..
However is a really good way to have something like LWT ( Last Will and Testament ), then I am using it at the minute doing the parse by myself.
if (args.BasicProperties.Headers.TryGetValue("client_properties", out object value))
{
var items = value as List<object>;
foreach (var item in items)
{
var bytes = item as byte[];
//{<<id>>, type, <<value>>}
String itemStr = Encoding.UTF8.GetString(bytes);
var parts = itemStr.Split(",");
var key = CleanErlangString(parts[0]);
var value = CleanErlangString(parts[2]);
// Do things with key/value
}
}
ClearErlangFunction
private static string CleanErlangString(string toClean)
{
return toClean
.Replace("{", "").Replace("}", "")
.Replace("\"", "")
.Replace("<<", "").Replace(">>", "");
}
What I am doing to use it as LWT, is setting a custom property on client side and then obtaining it while reading events at "amq.rabbitmq.event", "connection.#". With that I know who have disconnected and even process something as LWT with my core server.
I hope this helps someone :)

How to extract fields from message object content (Jade)

I have some problem with object type in JADE. In order to send object message to another agent I am using a method ACLMessage.setContentObject. However when I want to extract particular values/fields from the received message problem is arising.
Additionaly in sending agent I have created class to make possible sending message with object content:
class BusData implements java.io.Serializable
{
public Double current;
public Double power1;
public Double power2;
public Double voltage;
}
Receiving agent has following code (part):
data = MessageTemplate.MatchConversationId("measure");
ACLMessage data1 = receive(data); //receiving data with defined template
if (data1!=null) {
for (int i = 0; i < Agents.length; ++i) {
try {
Data1 received_data = (Data1)data1.getContentObject();
} catch (UnreadableException e) {
e.printStackTrace();}
//Serializable so = (Serializable)data1;
//System.out.println(Agents[i].getName()); //from whom received
if (data1!=null) {
System.out.println(getLocalName()+ " Info from " + data1.getSender().getName()); //from whom received
}
}
}
Should I add in receiving agent similar class, e.g. BusData1 with similar variables, like in sending agent in order to extract message content? I am quite new in Java so I am asking for understanding.
Every hint will be helpful.
Regards
Its too late for you but someone might be looking for it :)
In your receiving agent, instead of:
Data1 received_data = (Data1)data1.getContentObject();
Just do :
BusData received_data = (BusData)data1.getContentObject();
You can then access your received_data public variables (The cast allows the system to understand what is the serialized object's class to trigger the unserialization).
Tip : You should use variables names that correspond to their content.
data --> messageTemplate
data1 --> receivedMessage

How I can get email headers programmatically from MS Exchange Server in Java?

I can't get access to headers in email. At that moment I can get only ExtendedPropertyCollection object, but I don't know how to work with it.
ItemEvent item = (ItemEvent) event;
EmailMessage message = EmailMessage.bind(args.getSubscription().getService(), item.getItemId());
ExtendedPropertyCollection extendedProperties = ((ExtendedPropertyCollection) message.getExtendedProperties());
UPDATE:
The result code in Java looks like:
PropertySet propertySet = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.MimeContent);
EmailMessage message = EmailMessage.bind(args.getSubscription().getService(), item.getItemId(), propertySet);
String emailTextWithHeaders = new String(message.getMimeContent().getContent());
There are two ways to do that you should be able to access the InternetMessageHeader collection vai the EmailMessage class https://github.com/OfficeDev/ews-java-api/blob/master/src/main/java/microsoft/exchange/webservices/data/InternetMessageHeader.java
The other way is to use the PR_TRANSPORT_MESSAGE_HEADERS extended property eg
ExtendedPropertyDefinition PR_TRANSPORT_MESSAGE_HEADERS = new ExtendedPropertyDefinition(0x007D, MapiPropertyType.String);
PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties) { PR_TRANSPORT_MESSAGE_HEADERS};
EmailMessage message = EmailMessage.bind(args.getSubscription().getService(), item.getItemId(),psPropSet);
Cheers
Glen

Lotus Notes - Mail Document - Principal/From,INetFrom, SentTime, ReceivedTime fields

I have a requirement to fetch the SenderName,SenderEmail,ToNames,ToEmails,CCNames,CcEmails from a lotus notes document instance.
Issue1
Looking into lotus.domino.Document API I found out the method getItems. When I write the elements to the system.out values for SenderEmail, ToEmails and CcEmails can be found.
However values for SenderName(a.k.a From), ToNames cannot be derived that easily.
The values seems to be using an common name format. For example check check my system.output below.
Principal = "CN=Amaw Scritz/O=fictive"
$MessageID = "<OF0FF3779B.36590F8A-ON80257D15.001DBC47-65257D15.001DC804#LocalDomain>"
INetFrom = "AmawScritz#fictive.com"
Recipients = "CN=Girl1/O=fictive#fictive"
MailOptions = "0"
SaveOptions = "1"
From = "CN=Amaw Scritz/O=fictive"
AltFrom = "CN=Amaw Scritz/O=fictive"
SendTo = "CN=Girl1/O=fictive#fictive"
CopyTo = "CN=Girl2/O=fictive#fictive"
BlindCopyTo = ""
InetSendTo = "Girl1#fictive.com"
InetCopyTo = "Girl2#fictive.com"
$Abstract = "sasdasda"
$UpdatedBy = "CN=Amaw Scritz/O=fictive"
Body = "Hello World"
The question is how can I get 'Amaw Scritz' from the common name 'CN=Amaw Scritz/O=fictive'. Is there any look up mechanism that can be used. (I would prefer to have a option other than doing a substring of the common name)
Issue2
is it possible to retrieve SentTime and ReceivedTime from mail document instance?
I know that there are two methods called getCreated and getLastModified. getCreated can be loosely associated with the SentTime and getLastModified can be loosely associated with ReceivedTime. Are there are other ways to get times for SentTime and ReceivedTime.
Issue3
How can one distinguish whether a mail document is a Sent mail or a Received Mail?
Issue1
You can use Name class.
Here example from this link:
import lotus.domino.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
// (Your code goes here)
// Create a hierarchical name
Name nam = session.createName(
"CN=John B Goode/OU=Sales/OU=East/O=Acme/C=US");
// Returns:
// John B Goode
// John B Goode/Sales/East/Acme/US
// CN=John B Goode/OU=Sales/OU=East/O=Acme/C=US
System.out.println(nam.getCommon());
System.out.println(nam.getAbbreviated());
System.out.println(nam.getCanonical());
} catch(Exception e) {
e.printStackTrace();
}
}
}
Issue2
Use values of PostedDate field and DeliveredDate field of mail document.
Issue3
Check that $Inbox folder contains your mail document. Or take a look at Dave Delay answer.
I agree with #nempoBu4 on Issues 1 and 2. I disagree with the answer to Issue 3. A received message can be removed from the inbox, so checking $Inbox doesn't help you distinguish between sent and received messages.
Assuming you have the document open, the best approach is to check two items. Sent and received messages both have a PostedDate item, but only a received message has a DeliveredDate item. Incidentally, a draft message has neither PostedDate or DeliveredDate.

What is the error in the following HL7 encoding?

I am trying to encode an HL7 message of the type ORU_R01 using the HAPI 2.0 library for an OpenMRS module. I have followed the tutorials given in the HAPI documentation and according to that, I have populated the required fields of the ORU_R01 message. Now, I want to post this message using the following link:
http://localhost:8080/openmrs/remotecommunication/postHl7.form
I am using the following message for testing:
MSH|^~\&|||||20140713154042||ORU^R01|20140713154042|P|2.5|1
PID|||1
OBR|1||1234^SensorReading|88304
OBX|0|NM|1||45
OBX|1|NM|2||34
OBX|2|NM|3||23
I have properly ensured that all the parameters are correct. Once I have posted the HL7 message, I start the HL7 task from the scheduler. Then I go to the admin page and click on "Manage HL7 errors" in order to see if the message arrives there. I get the following stack trace:
ca.uhn.hl7v2.HL7Exception: HL7 encoding not supported
...
Caused by: ca.uhn.hl7v2.parser.EncodingNotSupportedException: Can't parse message beginning MSH|^~\
at ca.uhn.hl7v2.parser.Parser.parse(Parser.java:140)
The full stack trace is here: http://pastebin.com/ZnbFqfWC.
I have written the following code to encode the HL7 message (using the HAPI library):
public String createHL7Message(int p_id, int concept_id[], String val[])
throws HL7Exception {
ORU_R01 message = new ORU_R01();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss",
Locale.ENGLISH);
MSH msh = message.getMSH();
msh.getFieldSeparator().setValue("|");
msh.getEncodingCharacters().setValue("^~\\&");
msh.getProcessingID().getProcessingID().setValue("P");
msh.getSequenceNumber().setValue("1");
msh.getMessageType().getTriggerEvent().setValue("R01");
msh.getMessageType().getMessageCode().setValue("ORU");
msh.getVersionID().getVersionID().setValue("2.5");
msh.getMessageControlID().setValue(
sdf.format(Calendar.getInstance().getTime()));
msh.getDateTimeOfMessage().getTime()
.setValue(sdf.format(Calendar.getInstance().getTime()));
ORU_R01_ORDER_OBSERVATION orderObservation = message
.getPATIENT_RESULT().getORDER_OBSERVATION();
ca.uhn.hl7v2.model.v25.segment.PID pid = message.getPATIENT_RESULT()
.getPATIENT().getPID();
Patient patient = (Patient) Context.getPatientService()
.getPatient(p_id);
System.out.println(String.valueOf(p_id) + " " + patient.getGivenName()
+ " " + patient.getFamilyName());
pid.getPatientName(0).getFamilyName().getSurname()
.setValue(patient.getFamilyName());
pid.getPatientName(0).getGivenName().setValue(patient.getGivenName());
pid.getPatientIdentifierList(0).getIDNumber()
.setValue(String.valueOf(p_id));
System.out.println();
// Parser parser = new PipeParser();
// String encodedMessage = null;
// encodedMessage = parser.encode(message);
// System.out.println(encodedMessage);
// Populate the OBR
OBR obr = orderObservation.getOBR();
obr.getSetIDOBR().setValue("1");
obr.getFillerOrderNumber().getEntityIdentifier().setValue("1234");
obr.getFillerOrderNumber().getNamespaceID().setValue("SensorReading");
obr.getUniversalServiceIdentifier().getIdentifier().setValue("88304");
Varies value = null;
// Varies value[] = new Varies[4];
for (int i = 0; i < concept_id.length; i++) {
ORU_R01_OBSERVATION observation = orderObservation
.getOBSERVATION(i);
OBX obx2 = observation.getOBX();
obx2.getSetIDOBX().setValue(String.valueOf(i));
obx2.getObservationIdentifier().getIdentifier()
.setValue(String.valueOf(concept_id[i]));
obx2.getValueType().setValue("NM");
NM nm = new NM(message);
nm.setValue(val[i]);
value = obx2.getObservationValue(0);
value.setData(nm);
}
Parser parser = new PipeParser();
String encodedMessage = null;
encodedMessage = parser.encode(message);
return encodedMessage;
}
In all likelihood, something is wrong with the MSH segment of the message, but I cannot seem to figure out what it is. What can I do to correct this error?
Why do you declare the Encoding Characters using double backslashes?
msh.getEncodingCharacters().setValue("^~\\&");
Shouldn't it be:
msh.getEncodingCharacters().setValue("^~\&");
...and because your message is using the default encoding characters maybe you don't even need to declare them at all? Extract from HAPI MSH Class reference
getENCODINGCHARACTERS
public ST getENCODINGCHARACTERS()
Returns MSH-2: "ENCODING CHARACTERS" - creates it if necessary
Update
I have no previous experience with HAPI. A quick google found an ORU example. Could you try initializing your MSH with initQuickstart("ORU", "R01", "P");
According to the comments in the example-code the initQuickstart method populates all of the mandatory fields in the MSH segment of the message, including the message type, the timestamp, and the control ID. (...and hopefully the default encoding chars as well :-)

Categories