Showing posts with label Messaging. Show all posts
Showing posts with label Messaging. Show all posts

Thursday, October 23, 2014

Send SMS via Twitter with JAVA application


Send SMS via Twitter step by step

Almost all the server monitoring systems has the "Health Check" functionality. Using that, we able to monitor the CPU performance, memory usage.. etc. If any of the server performances are reach the predefined threshold value, the system send the email or SMS alert to configured users.

In this tutorial, you can learn that, how to send the SMS message with using twitter via Java application. In additionally you can also learn how to register the application in twitter and what are the limitations if we use the twitter for send SMS.

Objective : The main Objective of the tutorial is that, register the application in twitter and develop a Java application for send SMS. 

Scope : Develop a simple Java application for send SMS via twitter.

Requirements : The following basic requirement we need to set it up in order to achieve the objective.
  • Eclipse JAVA EE IDE
  • JDK 1.6
  • Twitter related jars
Step 1 : You have to create an Twitter account and need to register the application with twitter. The registration details explained here. Once the registration is completed, the registered account will be use to send the messages to clients.

Step 2 : Once the registration process completed you able to get the following tokens\keys from the twitter page. Please note that the tokens and keys are very important, so save those details to some secure place. 

Do not share the key/tokens to public, because using that, any once can send the messages through your registered application.


Step 3 : Create a java project in Eclipse and name it as "TweetMsg". Add the following jars to build path of the project.
  • twitter4j-async-3.0.5.jar
  • twitter4j-core-3.0.5.jar
  • twitter4j-media-support-3.0.5.jar
  • twitter4j-stream-3.0.5.jar 
Step 4 : Create a java class "TweetMessage" in package "com.prem.twitter.message". The following TweetMessage class used to send the message to twitter account with using the token/keys.

/TweetMsg/src/com/prem/twitter/message/TweetMessage.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.prem.twitter.message;

import java.io.IOException;
import java.util.logging.Logger;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class TweetMessage {
 private final Logger logger = Logger.getLogger(TweetMessage.class
   .getName());

 public void start(String message) throws TwitterException, IOException {

  Twitter twitter = new TwitterFactory().getInstance();
  try {
   RequestToken requestToken = twitter.getOAuthRequestToken();
   AccessToken accessToken = null;
   while (null == accessToken) {
    logger.fine("Open the following URL and grant access to your account:");
    logger.fine(requestToken.getAuthorizationURL());
    try {
     accessToken = twitter.getOAuthAccessToken(requestToken);
    } catch (TwitterException te) {
     if (401 == te.getStatusCode()) {
      logger.severe("Unable to get the access token.");
     } else {
      te.printStackTrace();
     }
    }
   }
   logger.info("Got access token.");
   logger.info("Access token: " + accessToken.getToken());
   logger.info("Access token secret: " + accessToken.getTokenSecret());
  } catch (IllegalStateException ie) {
   // access token is already available, or consumer key/secret is not
   // set.
   if (!twitter.getAuthorization().isEnabled()) {
    logger.severe("OAuth consumer key/secret is not set.");
    return;
   }
  }
  twitter.updateStatus(message);
 }

 public static void main(String[] args) throws Exception {
  String tweetMsg = "";
  for (String string : args) {
   tweetMsg = tweetMsg + string + " ";
  }
  new TweetMessage().start(tweetMsg);
 }
}



Please note that, you can not send the same tweet message twice to the twitter account.


Step 5 : Store the tokens and keys in to "twitter4j.properties" file. Using the properties the class mentioned in Step 4 send the message to twitter account.

/TweetMsg/twitter4j.properties

1
2
3
4
5
6
oauth.consumerSecret=elVY6ILJJTdTDnJkTdFkClzlbRsTg7jZFxDENTqOE
debug=true
oauth.accessToken=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
oauth.accessTokenSecret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
http.prettyDebug=true
oauth.consumerKey=s1FBhBmAinYYKkX8SDHw

Step 6 : Now the time to configure the message receive option in twitter account. Once enabled the SMS notification, then only the users able to receive the SMS from twitter. You can find here for enable the SMS notification explained in the twitter site.

Step 7 : Now the time to run the "TweetMessage" class with parameters. You can find here for how to run the application with input parameters. In our example the input parameter is the string message. 

For example if you run the class with the text "Hello World" as the input parameter, then the same text message send to clients twitter account and if the twitter account enabled as SMS notification, then the same text will receive as SMS to the client mobile also.



E.E: 
- Make it sure the firewall is enable for access the twitter site.

Limitations : 
The Twitter has a set of limitations for sending SMS. You able to find the SMS limitations defined by twitter here. 


Wednesday, October 15, 2014

Send a message to Google chat via Java Application


Send a message to Google chat via Java Application.


Scope : Through the Java application send the message to Google chat.


Objective : Once execute the java application, the predefined message send as a Google chat message.

Requirements:
  • Eclipse JAVA EE IDE
  • JDK 1.6
  • Smack java library (download)
  • Need a Google account. If does not have please create an google talk account from here.

Step 1: Create a java project in eclipse and named as "GoogleChat".
             File à New à Java Project. 

            Add the downloaded smack.jar and smackx.jar to the project build path.

Step 2: Create a "SendChatMsg" java class under "com.prem.google.chat" package.

             /GoogleChat/src/com/prem/google/chat/SendChatMsg.java

package com.prem.google.chat;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class SendChatMsg {

 private static String username = "xxxxxxx@gmail.com";
 private static String password = "xxxxxxxxx";
 ConnectionConfiguration connConfig;
 XMPPConnection connection;

 public SendChatMsg() {
  createConnection();
 }

 private void createConnection() {
  try {
   connConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
   connection = new XMPPConnection(connConfig);
   connection.connect();
   connection.login(username, password);
  } catch (XMPPException e) {
   e.printStackTrace();
  }
 }

 public void sendMessage(String to, String message) {
  Message msg = new Message(to, Message.Type.chat);
  msg.setBody(message);
  connection.sendPacket(msg);
 }
 
 public static void main(String[] args) {
  SendChatMsg chatMsg = new SendChatMsg();
  String sendMailAddress = args[0];
  String message = "";
  int counter = 0;
  for (String string : args) {
   if(counter != 0){
    message = message + " " +  string;
   }
   counter++;
  }
  chatMsg.main(sendMailAddress, message);
  System.out.println("Message send to successfully.");
  System.out.println("Receivers : " + sendMailAddress);
 }

 public void disconnect() {
  connection.disconnect();
 }

 public void main(String sendMailAddress, String msg){
  SendChatMsg gtalkChat = new SendChatMsg();

  String[] address = sendMailAddress.split(",");
  
  for (String mailAddress : address) {
   gtalkChat.sendMessage(mailAddress, msg);
  }
  gtalkChat.disconnect();
 }

}

Specify the correct gmail id and password to the username & password properties respectively.
The chat message will send through the above mentioned gmail account.


That's all..

Step 2: Now the time to test the application.
Create the "Test.java" class under the same "com.prem.google.chat" package.

Sample test class as below.


package com.prem.google.chat;

public class Test {
 public static void main(String[] args) {
  SendChatMsg chatMsg = new SendChatMsg();
  chatMsg.main("receiver1@gmail.com,receiver2@gmail.com,receiver3@gmail.com", "Test Chat Message .... ");
  System.out.println("Done!!");
 }
}

Specify the correct receiver gmail address (with comma separated) as a first parameter and the message need to send.

Right click on the "Test" java file and go to Run As - Run Java application.

The receivers got an chat message from Google talk API.
E.E

1. Make it sure the port 5222 is not block from the fire wall.