Retrieve Offline Messages and Chat History From Google Talk in Java - java

I have to retrieve offline messages from Google Talk for a particular client (friend/ XMPP Client) with whom I have had a conversationn with.
Additionally, I want to retrieve the chat history.
Right now, I am using a Hash Map to keep track of the conversation and have no means of having the offline messages.
I have made an XMPP connection to "talk.google.com". I am currently able to send messages to the client via my console. I have implemented the Message Listener Interface and hence can receive messages in my console itself.
I have another implementaion(made use of OfflineMessageManager) where I try to extract the offline messages headers as a start, unfortunately, it fails with Null Exception.
I have used smack-tcp version 4.0.3 and smackx 3.1.0.
Please find below what I have tried till now...
Working Implementation:
public class StartChatImpl implements startChat, MessageListener {
static XMPPConnection myXMPPConnection;
static ArrayList<String> myFriends = new ArrayList<String>();
ArrayList<Msg> messages;
HashMap<String,ArrayList> conversation = new HashMap<String, ArrayList>();
OfflineMessageManager offlineMessages;
#Override
public void engageChat(ChatRequest chatRequest) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setSendPresence(true);
myXMPPConnection = new XMPPTCPConnection(config);
try{
System.out.println("Connecting to talk.google.com");
myXMPPConnection.connect();
System.out.println("Logging you in...");
myXMPPConnection.login(chatRequest.getUsername(),chatRequest.getPassword());
Presence pres = new Presence(Presence.Type.unavailable);
myXMPPConnection.sendPacket(pres);
offlineMessages = new OfflineMessageManager(myXMPPConnection);
System.out.println("You have been successfully connected.");
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void send (String message, String to) throws XMPPException
{
Chat chat = ChatManager.getInstanceFor(myXMPPConnection).createChat(to, this);
//System.out.println("********************************************");
//System.out.println("CHAT ID: "+ chat.getThreadID());
//System.out.println("Participant: "+chat.getParticipant());
//System.out.println("********************************************");
try {
chat.sendMessage(message);
String friendName = myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName();
if(conversation.containsKey(friendName))
{
messages = conversation.get(friendName);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
message = "bot says: "+message;
Msg actualMsg = new Msg(currentTimestamp,message,"bot");
messages.add(actualMsg);
//messages.add("bot says: "+message);
}
else
{
messages = new ArrayList<Msg>();
//messages.add("Bot initiated the conversation on: "+new Date());
//messages.add("bot says: "+message);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
message = "bot says: "+message;
Msg actualMsg = new Msg(currentTimestamp,message,"bot");
messages.add(actualMsg);
conversation.put(friendName,messages);
}
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
System.out.println("You said "+"'"+message+"'"+" to "+myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName());
}
PacketListener myPacketListener = new PacketListener() {
#Override
public void processPacket(Packet p) {
if (p instanceof Message) {
Message msg = (Message) p;
}
}
};
public void displayMyFriends()
{
Roster roster = myXMPPConnection.getRoster();
Collection entries = roster.getEntries();
System.out.println("You currently have: "+entries.size()+" friends available to chat.");
int counter = 0;
Iterator i = entries.iterator();
while(i.hasNext())
{
RosterEntry r = (RosterEntry) i.next();
Presence.Type entryPresence;
entryPresence = roster.getPresence(r.getUser()).getType();
System.out.println((counter+1)+" . "+r.getName() +" is "+entryPresence);
//System.out.println("id:..."+r.getUser());
myFriends.add(r.getUser());
counter++;
}
}
public void disconnectMe()
{
try {
System.out.println("Disconnection in progress...");
myXMPPConnection.disconnect();
System.out.println("You have been successfully disconnected.");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
#Override
public void processMessage(Chat chat, Message message)
{
if((message.getType() == Message.Type.chat) && (message.getBody()!= null)) {
System.out.println(myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName() + " says: " + message.getBody());
String myMsg = myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName() + " says: " + message.getBody();
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
Msg actualMsg = new Msg(currentTimestamp,myMsg,"customer");
conversation.get(myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName()).
add(actualMsg);
}
}
public void receiveMessage(){
myXMPPConnection.addPacketListener(myPacketListener, null);
}
public void retrieveUnservicedMessagesForSpecificPerson(String clientName)
{
ArrayList<Msg> myMessages = conversation.get(clientName);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
System.out.println("Unserviced messages from: "+ clientName);
if(!myMessages.isEmpty())
{
int counter = myMessages.size()-1;
System.out.println("Size of array list: "+counter);
boolean found = false;
java.sql.Timestamp lastBotTimestamp = null;
while (counter != 0 && found == false){
if(myMessages.get(counter).getOwner()=="bot")
{
lastBotTimestamp = myMessages.get(counter).getTimestamp();
found = true;
}
else
{
counter = counter-1;
}
}
for(Msg msg:myMessages)
{
if(msg.getTimestamp().before(currentTimestamp) &&
msg.getTimestamp().after(lastBotTimestamp)){
System.out.println("---------------------------");
System.out.println("-"+msg.getActualMessage());
System.out.println("-"+msg.getTimestamp());
System.out.println("---------------------------");
}
}
}
}
public void returnConversation(String name) {
System.out.println("Name of participant entered: "+ name);
System.out.println("Conversation history is: ");
ArrayList<Msg> m = conversation.get(name);
for(Msg msg:m){
System.out.println(msg.getActualMessage());
System.out.println("on: "+msg.getTimestamp());
}
}
public void returnAllUnservicedMessagesHistory()
{
for(String name: conversation.keySet())
{
System.out.println("History of unserviced messages for: "+ name);
retrieveUnservicedMessagesForSpecificPerson(name);
}
}
public void getOfflineMessagesCount(){
try {
System.out.println("Number of offline messages: "+ offlineMessages.getMessageCount());
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
My Main Class Implementation:
public class MainGoogleChatApp {
public static void main(String[] args)
{
//Step 1: need to make a chat request with your username and password.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your username to start: ");
String myUsername = input.next();
System.out.println("Please enter your password to continue: ");
String myPassword = input.next();
ChatRequest myChatRequest = new ChatRequest();
myChatRequest.setUsername(myUsername);
myChatRequest.setPassword(myPassword);
//Step 2: Need to initiate a connection to talk.google.com
StartChatImpl convo = new StartChatImpl();
try {
convo.engageChat(myChatRequest);
} catch (XMPPException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String myMessage;
System.out.println("Friend list.");
convo.displayMyFriends();
convo.receiveMessage();
try {
while(true)
{
System.out.println("Input Which friend you want to chat with '0 to sign out' : ");
int num = input.nextInt() -1;
if (num == -1){
break;
}
String chatWith = StartChatImpl.myFriends.get(num);
System.out.print("Type your message: ");
myMessage=br.readLine();
try {
convo.send(myMessage,chatWith);
} catch (XMPPException e) {
e.printStackTrace();
}
convo.displayMyFriends();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Enter participant name to get specific chat...");
String yourName = null;
try {
yourName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("/./././././././././././././..//.");
if(yourName!=null){
System.out.println("Your name is not null...ok");
convo.returnConversation(yourName);
}
System.out.println("Enter another participant's name to get specific chat...");
String yourName1 = null;
try {
yourName1 = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("/./././././././././././././..//.");
if(yourName1!=null){
System.out.println("Your name is not null...ok");
convo.returnConversation(yourName1);
}
System.out.println("Select a client name for whom you want to view unserviced messages: ");
String yourClientName = null;
try {
yourClientName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(yourClientName!=null){
System.out.println("...........................................");
convo.retrieveUnservicedMessagesForSpecificPerson(yourClientName);
}
System.out.println("...........................................");
convo.returnAllUnservicedMessagesHistory();
System.out.println("You have chosen to disconnect yourself from talk.google.com");
convo.disconnectMe();
System.exit(0);
}
}
Attempt to retrieve offline messages headers:
public class TestOfflineService {
XMPPConnection xmppConnection = null;
//OfflineMessageManager offlineMessageManager = null;
public void makeConnection()
{
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setSendPresence(true);
xmppConnection = new XMPPTCPConnection(config);
try{
System.out.println("Connecting to talk.google.com");
xmppConnection.connect();
System.out.println("Logging you in...");
xmppConnection.login("*******.*#***.com", "*****");
System.out.println("You have been successfully connected.");
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
public void makeMeUnavailable()
{
try {
xmppConnection.sendPacket(new Presence(Presence.Type.unavailable));
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
public void getOfflineMessages()
{
OfflineMessageManager offlineMessageManager1 = new OfflineMessageManager(xmppConnection);
try {
Iterator<OfflineMessageHeader> headers = offlineMessageManager1.getHeaders();
if(headers.hasNext())
{
System.out.println("Messages found");
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
TestOfflineService test = new TestOfflineService();
test.makeConnection();
test.makeMeUnavailable();
System.out.println("Enter messages");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Getting offline messages.....");
test.getOfflineMessages();
}
}

OfflineMessageManager tries to use XEP-0013 to retrieve offline messages. This XEP isn't implemented by GTalk. Also note that ever starting Hangouts means you'll never get offline messages anymore, as the Hangouts instance is never offline.
GTalk also does not have an XMPP API to retrieve chat history, like XEP-0136 or XEP-0313.

Related

RMI does not return response over internet

I have a simple rmi-server and rmi-client. When i run this server and client in same network, my server function returns the result properly. But my server and client are in different networks and if the process time is more than 3-4 minutes client can not get the result, although server fihishes the operation.
here is my entire server code:
public class SimpleServer {
ServerRemoteObject mRemoteObject;
public static int RMIInPort = 27550;
public static int delay = 0;
public byte[] handleEvent(byte[] mMessage) throws Exception {
String request = new String(mMessage, "UTF-8");
// if ("hearthbeat".equalsIgnoreCase(request)) {
// System.out.println("returning for hearthbeat");
// return "hearthbeat response".getBytes("UTF-8");
// }
System.out.println(request);
Thread.sleep(delay);
System.out.println("returning response");
return "this is response".getBytes("UTF-8");
}
public void bindYourself(int rmiport) {
try {
mRemoteObject = new ServerRemoteObject(this);
java.rmi.registry.Registry iRegistry = LocateRegistry.getRegistry(rmiport);
iRegistry.rebind("Server", mRemoteObject);
} catch (Exception e) {
e.printStackTrace();
mRemoteObject = null;
}
}
public static void main(String[] server) {
int rmiport = Integer.parseInt(server[0]);
RMIInPort = Integer.parseInt(server[1]);
delay = Integer.parseInt(server[2]);
System.out.println("server java:" + System.getProperty("java.version"));
System.out.println("server started on:" + rmiport + "/" + RMIInPort);
System.out.println("server delay on:" + delay);
SimpleServer iServer = new SimpleServer();
iServer.bindYourself(rmiport);
while (true) {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and here is my client code:
public class SimpleClient {
ISimpleServer iServer;
public SimpleClient(String p_strServerIp, String p_strCMName, int nRMIPort) {
try {
if (nRMIPort == 1099) {
iServer = (ISimpleServer) Naming.lookup("rmi://" + p_strServerIp + "/" + p_strCMName);
} else {
Registry rmiRegistry = null;
rmiRegistry = LocateRegistry.getRegistry(p_strServerIp, nRMIPort);
iServer = (ISimpleServer) rmiRegistry.lookup(p_strCMName);
}
} catch (Exception ex) {
ex.printStackTrace();
iServer = null;
}
}
public static void main(String... strings) {
String ip = strings[0];
int rmiport = Integer.parseInt(strings[1]);
System.out.println("client java:" + System.getProperty("java.version"));
System.out.println("client is looking for:" + ip + ":" + rmiport);
SimpleClient iClient = new SimpleClient(ip, "Server", rmiport);
try {
byte[] response = iClient.iServer.doaction("this is request".getBytes("UTF-8"));
System.out.println(new String(response, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
and here is my rmi-registry code:
public class SimpleRMI implements Runnable {
Registry mRegistry = null;
public SimpleRMI(int nPort) {
try {
mRegistry = new sun.rmi.registry.RegistryImpl(nPort);
} catch (RemoteException e1) {
e1.printStackTrace();
}
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(360000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String... strings) {
int rmiport = Integer.parseInt(strings[0]);
System.out.println("rmi java:" + System.getProperty("java.version"));
System.out.println("rmi started on:" + rmiport);
SimpleRMI iRegisry = new SimpleRMI(rmiport);
Thread tThread = new Thread(iRegisry);
tThread.start();
byte[] bytes = new byte[1];
while (true) {
try {
System.in.read(bytes);
if (bytes[0] == 13) {
try {
iRegisry.listRegistry();
} catch (Exception exc2) {
exc2.printStackTrace();
}
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
private void listRegistry() {
String[] strList = null;
try {
strList = mRegistry.list();
if (strList != null) {
for (int i = 0; i < strList.length; i++) {
int j = i + 1;
String name = strList[i];
java.rmi.Remote r = mRegistry.lookup(name);
System.out.println(j + ". " + strList[i] + " -> "
+ r.toString());
}
}
System.out.println();
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
and my remote interface and remote object:
public interface ISimpleServer extends java.rmi.Remote {
public byte[] doaction(byte[] message) throws java.rmi.RemoteException;
}
#SuppressWarnings("serial")
public class ServerRemoteObject extends UnicastRemoteObject implements ISimpleServer {
SimpleServer Server = null;
public ServerRemoteObject(SimpleServer pServer) throws RemoteException {
super(SimpleServer.RMIInPort);
Server = pServer;
}
#Override
public byte[] doaction(byte[] message) throws RemoteException {
try {
return Server.handleEvent(message);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
when i run client and server in different networks. (i run client in my home network) and if delay is more than 3-4 mins server prints returning response but client still waits for the response. If delay is only 1 minute, clients gets the result properly.
Can you please help me to find where the problem is?

Creating an Object in a Class then using it in different class

I'm trying to create an object in one class then use that object in another class but each time I try to use it it just says the value is null
Customer cus = new Customer();
ServerSocket s = null;
public AddCustomer() {
}
public void getCustomerDetail() {
String back = " ";
{
try {
s = new ServerSocket(5433);
} catch (IOException e) {
System.out.println("Error:" + e.getMessage());
System.exit(0);
}
while (back.equals(" ")) {
try {
Socket s1 = s.accept();
System.out.println("Connection established at port 5433");
InputStream is = s1.getInputStream();
ObjectInputStream dis = new ObjectInputStream(is);
System.out.println("Getting data...");
cus = (Customer)dis.readObject();
System.out.println(cus.toString());
System.out.println(cus.getName());
dis.close();
s1.close();
System.out.println("Connection closed.");
} catch (ConnectException connExcep) {
System.out.println("1Error: " + connExcep.getMessage());
} catch (IOException ioExcep) {
System.out.println("2Error: " + ioExcep.getMessage());
} catch (Exception e) {
System.out.println("3Error: " + e.getMessage());
}
new AddCustomer().addCustomerToDB();
}
}
}
public void addCustomerToDB() {
System.out.println("start ");
Connection connection = null;
Statement statement = null;
int check = 1;
System.out.println(cus.getName()+"dadawd");
}
When I print out the value of cus.getName() it just gives me null but when I print it out in getCustomerDetail it gives me the correct value.
dis.readObject returns an object with the values in it.
Depends on what you are doing in the getName function and in the constructor.
Maybe in getCustomerDetails() you are setting the values in the input stream. But the default constructor doesn't do anything with name variable.
It looks like the issue of packaging. Try below code.
public class AddCustomer {
public static void main(String[] args) {
new AddCustomer().getCustomerDetail();
}
Customer cus = new Customer();
public void getCustomerDetail() {
String back = " ";
{
while (back.equals(" ")) {
try {
System.out.println(cus.toString());
System.out.println(cus.getName());
System.out.println("Connection closed.");
} catch (Exception e) {
System.out.println("3Error: " + e.getMessage());
}
new AddCustomer().addCustomerToDB();
break;
}
}
}
public void addCustomerToDB() {
System.out.println(cus.getName()+"dadawd");
}
}
class Customer{
private String name="ABC";
String getName() {
return name;
}
}
We found here one issue you have to create "Customer cus = new Customer();" this object under main() function like as
public class AddCustomer {
public static void main(String[] args) {
Customer cus = new Customer();
new AddCustomer().getCustomerDetail();
}

Bluemix disconnects at publish with Paho MQTT client

I am trying to run the below code I am getting EOFException. The below is my output
Connected to ssl://REMOVED.messaging.internetofthings.ibmcloud.com:8883
.deliveryComplete() entered
Data published on topic iot-2/type/loradevice/id/cdef1234/cmd/cid/fmt/json and the msg is{"count":0,"cmd":"reset","time":"2017-01-25 18:38:34"}
connection true
Connection lost (32109) - java.io.EOFException
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:146)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.EOFException
at java.io.DataInputStream.readByte(DataInputStream.java:267)
at org.eclipse.paho.client.mqttv3.internal.wire.MqttInputStream.readMqttWireMessage(MqttInputStream.java:65)
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:107)
... 1 more
The code is below
package com.ibm.bluemixmqtt;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.json.JSONException;
import org.apache.commons.json.JSONObject;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
public class AppTest2
{
private MqttHandler1 handler;
/**
* #param args
*/
public static void main(String[] args)
{
new AppTest2().doApp();
}
/**
* Run the app
*/
public void doApp()
{
// Read properties from the conf file
Properties props = MqttUtil.readProperties("Mydata\\app.conf");
String org = "REMOVED";
String id = "REMOVED";
String authmethod = "REMOVED";
String authtoken = "REMOVED";
// isSSL property
String sslStr = props.getProperty("isSSL");
boolean isSSL = false;
if (sslStr.equals("T")) {
isSSL = true;
}
System.out.println("org: " + org);
System.out.println("id: " + id);
System.out.println("authmethod: " + authmethod);
System.out.println("authtoken" + authtoken);
System.out.println("isSSL: " + isSSL);
// Format: a:<orgid>:<app-id>
String clientId = "a:" + org + ":" + id;
String serverHost = org + MqttUtil.SERVER_SUFFIX;
handler = new MqttHandler1();
handler.connect(serverHost, clientId, authmethod, authtoken, isSSL);
publish();
}
public void publish(){
JSONObject jsonObj = new JSONObject();
String deviceid = "cdef1234";
try {
jsonObj.put("cmd", "reset");
jsonObj.put("count", 0);
jsonObj.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
} catch (JSONException e) {
e.printStackTrace();
}
handler.publish(
"iot-2/type/" + MqttUtil.DEFAULT_DEVICE_TYPE + "/id/" + deviceid + "/cmd/" + MqttUtil.DEFAULT_CMD_ID + "/fmt/json",
jsonObj.toString(), false, 0);
}
}
class MqttHandler1 implements MqttCallback
{
private final static String DEFAULT_TCP_PORT = "1883";
private final static String DEFAULT_SSL_PORT = "8883";
private MqttClient client = null;
public MqttHandler1()
{
}
#Override
public void connectionLost(Throwable throwable)
{
if (throwable != null) {
System.out.println("Error3");
throwable.printStackTrace();
}
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken)
{
System.out.println(".deliveryComplete() entered");
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception
{
String payload = new String(mqttMessage.getPayload());
System.out.println(".messageArrived - Message received on topic " + topic + ": message is " + payload);
}
public void connect(String serverHost, String clientId, String authmethod, String authtoken, boolean isSSL)
{
// check if client is already connected
if (!isMqttConnected()) {
String connectionUri = null;
// tcp://<org-id>.messaging.internetofthings.ibmcloud.com:1883
// ssl://<org-id>.messaging.internetofthings.ibmcloud.com:8883
if (isSSL) {
connectionUri = "ssl://" + serverHost + ":" + DEFAULT_SSL_PORT;
} else {
connectionUri = "tcp://" + serverHost + ":" + DEFAULT_TCP_PORT;
}
if (client != null) {
try {
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
client = null;
}
try {
client = new MqttClient(connectionUri, clientId);
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(this);
// create MqttConnectOptions and set the clean session flag
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
options.setUserName(authmethod);
options.setPassword(authtoken.toCharArray());
options.setKeepAliveInterval(2000);
// If SSL is used, do not forget to use TLSv1.2
if (isSSL) {
java.util.Properties sslClientProps = new java.util.Properties();
sslClientProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
options.setSSLProperties(sslClientProps);
}
try {
// connect
client.connect(options);
System.out.println("Connected to " + connectionUri);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
public void disconnect()
{
// check if client is actually connected
if (isMqttConnected()) {
try {
// disconnect
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
public void subscribe(String topic, int qos)
{
// check if client is connected
if (isMqttConnected()) {
try {
client.subscribe(topic, qos);
System.out.println("Subscribed: " + topic);
} catch (MqttException e) {
e.printStackTrace();
}
} else {
connectionLost(null);
}
}
public void unsubscribe(String topic)
{
// check if client is connected
if (isMqttConnected()) {
try {
client.unsubscribe(topic);
} catch (MqttException e) {
e.printStackTrace();
}
} else {
connectionLost(null);
}
}
public void publish(String topic, String message, boolean retained, int qos)
{
// check if client is connected
if (isMqttConnected()) {
// create a new MqttMessage from the message string
MqttMessage mqttMsg = new MqttMessage(message.getBytes());
// set retained flag
mqttMsg.setRetained(retained);
// set quality of service
mqttMsg.setQos(qos);
try {
client.publish(topic, mqttMsg);
System.out.println("Data published on topic " + topic + " and the msg is" + mqttMsg);
System.out.println("connection "+client.isConnected());
} catch (MqttPersistenceException e) {
System.out.println("Error1");
e.printStackTrace();
} catch (MqttException e) {
System.out.println("Error1");
e.printStackTrace();
}
} else {
connectionLost(null);
}
}
private boolean isMqttConnected()
{
boolean connected = false;
try {
if ((client != null) && (client.isConnected())) {
connected = true;
}
} catch (Exception e) {
// swallowing the exception as it means the client is not connected
}
return connected;
}
}
Any one help me on this.
Thanks in adavance.
the EOFException might indicates that the clientID is reused and the access is blocked... make sure that you only call once the connect method... possibly use only the SSL or non-SSL connection sequence

How to retrieve Message and Task body - Exchange Web Services - Java

I am creating a message using JWebServices, but even though all other fields are retrieved successfully, body does not. message.getBody() returns null. Here are the two methods I call subsequently.
private void createMessage(Service service) throws ParseException {
try {
Message message = new Message();
message.setItemClass(ItemClass.MESSAGE);
message.setSubject("Test");
message.setBody(new Body("Body text"));
message.getToRecipients().add(new Mailbox("John#mydomain.com"));
message.getCcRecipients().add(new Mailbox("Mark#mydomain.com"));
ItemId itemId = service.createItem(message,StandardFolder.SENT_ITEMS);
} catch (ServiceException e) {
System.out.println(e.getMessage());
System.out.println(e.getXmlMessage());
e.printStackTrace();
}
}
private void listItemsInSent(Service service) throws ParseException {
try {
FindItemResponse response = service.findItem(StandardFolder.SENT_ITEMS);
Message m = null;
for (int i = 0; i < response.getItems().size(); i++) {
m = (Message)response.getItems().get(i);
System.out.println(m.getSubject());
System.out.println(m.getItemClass());
System.out.println(m.getLastModifiedTime());
System.out.println(m.getBody());
System.out.println(m.getBodyHtmlText());
System.out.println(m.getBodyPlainText());
System.out.println(m.getItemId());
System.out.println(m.toString());
System.out.println();
}
} catch (ServiceException e) {
System.out.println(e.getMessage());
System.out.println(e.getXmlMessage());
e.printStackTrace();
}
}
Try to replace
m = (Message)response.getItems().get(i);
with
m = service.getMessage(response.getItems().get(i).getItemId());

Problems with RMS to store persistent data

1.Problem on emulator:
I am launching my midlet app at first time is to store some data and then I am restarting it at second time is to read the stored data. It is working well in first two cases without any exception.
However I am restarting it second time on the same way then It gives exception: "Uncaught exception java/lang/NumberFormatException:" it is processing only char and total data is less than 64 kb.
2.Problem on real device:
RMS is not working at all. I don't know if I need to give a permission for the handset (nokia n95).
Thanks.
In app, it is only storing charity companies into rms according to a selected country. So if a country is already selected, it must skip country list and then display company list in every restart.
In below code, rms_Check() method is to check the data in order to open country or company list frame.
public class X {
private static RecordStore rs =null;
private static Vector rms_Vector = new Vector();
static final String REC_STORE ="db_1";
public X() {
}
public void openRecStore(){
try {
rs = RecordStore.openRecordStore(REC_STORE, true);
System.out.println("open record store");
} catch (Exception e)
{
db(e.toString()+" in openRecStore");
}
}
public void closeRecStore(){
try {
rs.closeRecordStore();
} catch (Exception e) {
db(e.toString()+" in closeRecStore");
}
}
public void deleteRecStore()
{
if (RecordStore.listRecordStores()!=null){
try {
RecordStore.deleteRecordStore(REC_STORE);
} catch (Exception e) {
db(e.toString()+" in deleteRecStore");
}
}
}
public void writeRecord(String str) throws UnsupportedEncodingException
{
byte[] rec = str.getBytes("UTF-8");
try {
rs.addRecord(rec, 0, rec.length);
System.out.println("write record store");
} catch (Exception e) {
db(e.toString()+" in writeRecord");
}
}
public void readRecord()
{
try {
// Intentionally it is too small to test code
byte[] m_enc = new byte[5];
byte[] recData = new String(m_enc).getBytes("UTF-8");
int len;
for(int i =1; i<= rs.getNumRecords(); i++){
if(rs.getRecordSize(i)> recData.length)
recData = new byte[rs.getRecordSize(i)];
len = rs.getRecord(i, recData, 0);
System.out.println("Record #"+i+":"+new String(recData, 0, len));
System.out.println("------------------------");
rms_Vector.addElement(new String(recData, 0, len));
}
} catch (Exception e) {
db(e.toString() +" in readStore");
}
}
private void db(String str)
{
System.out.println("Msg:"+str);
}
public Vector rms_Array(){
return this.rms_Vector;
}
public boolean rms_Check(){
if(this.rms_Vector.size()>0){
System.out.print("rms_check: true");
// if true it will display company list every time
return true;
}else{
System.out.print("rms_check: false");
//if false it will display country list then company list
return false;
}
}
}
Use this
private RecordStore rs = null; // Record store
public String REC_STORE = "RSM name"; // Name of record store
public int record_max=0;
public void openRecStore(){
try{
rs = RecordStore.openRecordStore(REC_STORE, true );
}catch (Exception e){}
}
public void closeRecStore(){
try{
rs.closeRecordStore();
}catch (Exception e){}
}
public void deleteRecStore(){
if (RecordStore.listRecordStores() != null){
try{
RecordStore.deleteRecordStore(REC_STORE);
}catch (Exception e){}
}
}
public void writeRecord(String str){
byte[] rec = str.getBytes();
try{
rs.addRecord(rec, 0, rec.length);
}catch (Exception e){}
}
public void readRecords(){
try{
byte[] recData = new byte[5];
int len;
record_max=rs.getNumRecords();
for(int i = 1; i <= record_max; i++){
if(rs.getRecordSize(i) > recData.length){
recData = new byte[rs.getRecordSize(i)];
}
len = rs.getRecord(i, recData, 0);
file_name[i]=new String(recData, 0, len);
}
}catch (Exception e){}
}
you have file_name[] array of save data
for load actin commad use :
openRecStore();
readRecords();
for(int j=1;j<=record_max;j++ ) {
System.out.println("Record " + j + " : " + file_name[j]);
}
closeRecStore();
and save this :
openRecStore();
writeRecord(textField.getString());
closeRecStore();

Categories