Convert String to XMPP Stanza using Smack Android - java

or
Q) Generate XMPP Stanza From String.
Q) Cast String into XMPP Stanza.
By using Smack library in Android,
Message message = new Message();
message.setStanzaId("123");
message.setFrom("923442621149");
message.setType(Message.Type.chat);
message.setBody("shanraisshan");
final String msgString = message.toXML().toString();
Log.e("message --->", msgString);
the above code generated following stanza
msgString:
<message from='923442621149' id='123' type='chat'><body>shanraisshan</body></message>
I have save this msgString into my database.
Now, What I wanted to do is, on retrieving this string back from database
Cast this msgString back into Java Message Class
so that I can use attributes (From, Body, Id)
using message.getFrom()
Since Message is a child class of Stanza, I tried the below code:
Stanza stanza = new Stanza() {
#Override
public CharSequence toXML() {
return msgString;
}
};
Log.e("stanza XML --->", stanza.toXML().toString());
Log.e("stanza getFrom() ->", stanza.getFrom() + ":");
Log.e("stanza getStanzaId() ->", stanza.getStanzaId() + ":");
The Console Log prints follows
stanza XML --->: <message from='923442621149' id='123' type='chat'><body>shanraisshan</body></message>
stanza getFrom() ->: null:
stanza getStanzaId() ->: OtU0i-29:
I am unable to understand, why
stanza.toXML().toString() prints the right stanza while
stanza.getFrom() is null instead of 923442621149
stanza.getStanzaId() is OtU0i-29 instead of 123
Plus, on casting Stanza to Message , produces ClassCastException
Message castedMsg = (Message)stanza;
produces
java.lang.ClassCastException:
SIMPLIFYING THINGS
How can I convert msgString
msgString = "<message from='923442621149' id='123' type='chat'><body>shanraisshan</body></message>";
into org.jivesoftware.smack.packet.Message class?

After going through Smack Library source code on Github, I found out that the library is using PacketParserUtils.java method's parseStanza() for casting String to Stanza.
String msgString = "<message from='923442621149' id='123' type='chat'><body>shanraisshan</body></message>";
Message message = (Message)PacketParserUtils.parseStanza(msgString);
Log.e("message XML->", message.toXML().toString());
Log.e("message getFrom()->", message.getFrom() + ":"); //923442621149:
Log.e("message getStanzaId()->", message.getStanzaId() + ":"); //123:

Related

How to use Apache Tika to extract the "Subject” field by using Apache Metadata class ?

I'm trying to extract the "Subject" field from an email, but am having some trouble . I was able to get the "To" and "From" fields already, like so :
String messageTo = tikaMetadata.MESSAGE_TO; //Works fine
String toField = tikaMetadata.get(messageTo); //Works fine
System.out.println("From field is : " + fromField); //Works fine
System.out.println("To field is : " + toField); //Works fine
String messageSubj = tikaMetadata.getValues("Message:Raw-Header:Subject");
String subjField = tikaMetadata.get(messageTo); //Doesn't Work
How would we extract the subject field by using Tika ?
any tips helpful thanks
You can try two ways:
String subjectObs = tikaMetadata.get(tikaMetadata.SUBJECT);
but where.SUBJECT is deprecated
String subject = tikaMetadata.get(TikaCoreProperties.DESCRIPTION);probably the substitute that is closest to Metadata.SUBJECT (for more details about TikaCoreProperties look at this: tika documentation)

Error: expected END_ARRAY but was STRING - only on specific phones when using mobile internet

I have an android application in which I get data from web services using JSON.
I have tested the application on multiple mobile phones (samsung galaxy s2/s4, htc one/ one s, lg, sony .... ) and the problem I am getting is that when using mobile internet (on wifi everything works fine) on some devices (htc one s, Huawei Ascend p6) I get an error: expected END_ARRAY but was STRING and nothing downloads.
I can not wrap my mind why this is only happening on some devices. Did anyone experience anything similar? Please help.
Note: this is using GSON but the same problem happened when I used JSON.
JSON data:
[{"ID":"1","name":"Germany"}]
class:
public class Language {
#SerializedName("ID")
public int ID;
#SerializedName("name")
public String name;
}
Code:
try
{
this.httpClient = new DefaultHttpClient();
this.httpPost = new HttpPost(webserviceURL);
this.httpPost.setEntity(new UrlEncodedFormEntity(this.nameValuePairs));
this.httpResponse = this.httpClient.execute(this.httpPost);
this.httpEntity = this.httpResponse.getEntity();
this.isLanguage = this.httpEntity.getContent();
if (this.httpResponse.getStatusLine().getStatusCode() == 200)
{
Gson gson = new Gson();
Reader reader = new InputStreamReader(this.isLanguage, "UTF-8");
Language[] xy = gson.fromJson(reader, Language[].class);
for (int i=0; i<xy.length; i++)
Log.i("Language-GSON", "ID: " + xy[i].ID + " - Name: " + xy[i].name);
}
}catch (Exception e) { Log.i("Language-GSON", "Exception -> " + e.getMessage()); }
finally { this.isLanguage.close(); }
Exception:
java.lang.IllegalStateException: expected END_ARRAY but was STRING at line 1 column 1
Change to
this.httpClient = new DefaultHttpClient();
this.httpPost = new HttpPost(webserviceURL);
this.httpPost.setEntity(new UrlEncodedFormEntity(this.nameValuePairs));
this.httpResponse = this.httpClient.execute(this.httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String response = EntityUtils.toString(httpEntity);
Gson gson = new Gson();
Language[] xy = gson.fromJson(response, Language[].class);
for (int i=0; i<xy.length; i++)
{
Log.i("Language-GSON", "ID: " + xy[i].ID + " - Name: " + xy[i].name);
}
I justed testing paring of json with gson locally. It works. If it is not working you will need to check the response form the server. The parsing code is fine.
Also check if the NetworkConnection is available before making a http request. Also check if the response is null or not.
It has nothing to with specific devices or mobile internet. It has something to do with the response from the server.
I am guessing your response is not a valid json. Due check the response by logging the same.
I found the answer to why it was not working on some phones.
The problem in not in the code and not in the phones or server but in ISP set proxy for the internet provider(default setting). The proxys are blocking php response and so there was no answer. After removing proxy everything worked fine.
The problem now is that some phone have the proxys set and they block response from PHP. That means that my application will not work on mobile data on some phones and I cannot do anything about it.
Does anyone have a suggestion on how could I get around my problem? Or any other way to get data from database that isn't by PHP webservices?

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 :-)

Smack - How to read a MultiUserChat's configuration?

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..

Passing parameters to YQL using Java

I am using the following code:
String zip = "75227";
String str = "http://query.yahooapis.com/v1/public/yql?q=select%20Title%2C%20Address%2C%20" +
"City%2C%20State%2C%20Phone%2C%20Distance%20from%20local.search%20where%20query%3D%22" +
"food%20pantries%22%20and%20zip%3D%22" + zip +"%22%20and%20(category%3D%2296927050%22%20or" +
"%20category%3D%2296934498%22)%20%7C%20sort(field%3D%22Distance%22)";
Document doc = Jsoup.connect(str).get();
and it is producing the results I want by replacing the zip code value. I would like to also change the location. I tried doing the same I did with the zip code by doing this:
String zip = "32207";
String service = "food pantry";
String testOne = "http://query.yahooapis.com/v1/public/yql?q=select%20Title%2C%20Address%2C%20" +
"City%2C%20State%2C%20Phone%2C%20Distance%20from%20local.search%20where%20query%3D%22" +
service + "%22%20and%20zip%3D%22" + zip +"%22%20and%20(category%3D%2296927050%22%20or" +
"%20category%3D%2296934498%22)%20%7C%20sort(field%3D%22Distance%22)";
When used this way the variable "service" gave me an error.
I initially tried to use the yql table like this:
String search = "http://query.yahooapis.com/v1/public/yql?q=";
String table = "select Title, Address, City, State, Phone, Distance from local.search where " +
"query=\"food pantries\" and zip=\"75227\" and (category=\"96927050\" or category=" +
"\"96934498\") | sort(field=\"Distance\")";
String searchText = search + table;
UPDATE:
Here is the error I am getting:
Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=505, URL=http://query.yahooapis.com/v1/public/yql?q=select%20Title%2C%20Address%2C%20City%2C%20State%2C%20Phone%2C%20Distance%20from%20local.search%20where%20query%3D%22food pantry%22%20and%20zip%3D%2232207%22%20and%20(category%3D%2296927050%22%20or%20category%3D%2296934498%22)%20%7C%20sort(field%3D%22Distance%22)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:418)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:393)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:159)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:148)
at org.jsoup.examples.HtmlToPlainText.main(HtmlToPlainText.java:86)
However, this did not work either. Any ideas on how I can do this search and provide the service and zip code as variables?
Have you tried replacing String service = "food pantry"; with String service = "food%20pantry"; ?
EDIT:
and it is "food pantry" or "food pantries"... ?

Categories