Sunday, January 25, 2015

IntelliJ Plugin Development Tutorial - Project View Popup Menu Action Item

This simple tutorial shows you how to create an Action Item in the Project View Popup Menu.
When  you right click on the project view you will have this action item in the popup menu. You can extend or use this to execute any action.

 Following are the two files you should work with.

<idea-plugin version="2">
<id>com.lakj.comspace.intellij.projectviewmenuaction</id>
<name>Lak J Prject View Menu Action</name>
<version>1.0</version>
<vendor email="" url="http://lakjeewa.blogspot.com/">Lak J Comspace</vendor>
<description><![CDATA[
Enter short description for your plugin here.<br>
<em>most HTML tags may be used</em>
]]></description>
<change-notes><![CDATA[
Add change notes here.<br>
<em>most HTML tags may be used</em>
]]>
</change-notes>
<!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
<idea-version since-build="131"/>
<!-- please see http://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products
on how to target different products -->
<!-- uncomment to enable plugin in all products
<depends>com.intellij.modules.lang</depends>
-->
<extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here -->
</extensions>
<application-components>
<!-- Add your application components here -->
</application-components>
<project-components>
<!-- Add your project components here -->
</project-components>
<actions>
<group id="lakj.comspace">
<action
id="lakj.comspace.projectviewmenuaction"
class="com.lakj.comspace.intellij.projectviewmenuaction.ProjectViewAction"
text="Lak J Project View Menu Action"
description="Lak J Compspace Project View Menu Popup Action."
icon="/com/lakj/comspace/intellij/projectviewmenuaction/resources/icon/icon.png"/>
<add-to-group anchor="after" group-id="ProjectViewPopupMenu" relative-to-action="AnalyzeMenu"/>
</group>
</actions>
</idea-plugin>
view raw plugin.xml hosted with ❤ by GitHub
package com.lakj.comspace.intellij.projectviewmenuaction;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
/**
* Created by Lak J Comspace on 1/25/2015.
*/
public class ProjectViewAction extends AnAction {
/**
* Implement this method to provide your action handler.
*
* @param e Carries information on the invocation place
*/
@Override
public void actionPerformed(AnActionEvent e) {
Project project = e.getProject();
Messages.showMessageDialog(project, "Hello, You just clicked the IntelliJ project view popup menu action item.",
"Project View Action", Messages.getInformationIcon());
}
}
Following are the GitHub URL's for complete plugin project. You can clone the project or downolad the project as a zip file. To run the project open IntelliJ IDEA and import the project.

GitHub repository URL - https://github.com/lakjcomspace/IntelliJProjectViewMenuAction
GitHub HTTPS clone URL - https://github.com/lakjcomspace/IntelliJProjectViewMenuAction.git
Download Project as a Zip - https://github.com/lakjcomspace/IntelliJProjectViewMenuAction/archive/master.zip



Wednesday, January 7, 2015

Android Client-Server Chat Application

This is a simple Android chat application which communicate with a Java server program. This tutorial will help you to understand socket programming in Android which sends information both ways.
To run this application, first execute the server program. You can run this application in your PC.

Then execute the client program. You can use your Android emulator or your Android device. If you are using Android emulator you can use IP address 10.0.2.2 to connect your sever which is running in the same computer. But if you are using an Android device you may have to change the IP address in the client app code according to your network configuration.
Once you execute the client app, the chat window will be opened in the server program. Type the message on the chat box and press "Send" button. The message will be appeared in the other end.

      
Android Chat App
 
Server Program





                                                         









                                                                                   
Following are the source codes of the main components of both programs.

Android Chat Application

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_alignLeft="@+id/editText1"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/button1"
android:layout_toLeftOf="@+id/button1" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Send" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button1"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/button1"
android:ems="10"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lakj.comspace.simpleclientserverchatapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.lakj.comspace.simpleclientserverchatapp.SimpleClientServerChatActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
package com.lakj.comspace.simpleclientserverchatapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* This is the main activity class for Client-Server Chat App.
*
* @author Lak J Comspace (http://lakjeewa.blogspot.com)
*
*/
public class SimpleClientServerChatActivity extends Activity {
private EditText textField;
private Button button;
private TextView textView;
private Socket client;
private PrintWriter printwriter;
private BufferedReader bufferedReader;
//Following is the IP address of the chat server. You can change this IP address according to your configuration.
// I have localhost IP address for Android emulator.
private String CHAT_SERVER_IP = "10.0.2.2";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1);
button = (Button) findViewById(R.id.button1);
textView = (TextView) findViewById(R.id.textView1);
ChatOperator chatOperator = new ChatOperator();
chatOperator.execute();
}
/**
* This AsyncTask create the connection with the server and initialize the
* chat senders and receivers.
*/
private class ChatOperator extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
try {
client = new Socket(CHAT_SERVER_IP, 4444); // Creating the server socket.
if (client != null) {
printwriter = new PrintWriter(client.getOutputStream(), true);
InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
} else {
System.out.println("Server has not bean started on port 4444.");
}
} catch (UnknownHostException e) {
System.out.println("Faild to connect server " + CHAT_SERVER_IP);
e.printStackTrace();
} catch (IOException e) {
System.out.println("Faild to connect server " + CHAT_SERVER_IP);
e.printStackTrace();
}
return null;
}
/**
* Following method is executed at the end of doInBackground method.
*/
@Override
protected void onPostExecute(Void result) {
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Sender messageSender = new Sender(); // Initialize chat sender AsyncTask.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
messageSender.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
messageSender.execute();
}
}
});
Receiver receiver = new Receiver(); // Initialize chat receiver AsyncTask.
receiver.execute();
}
}
/**
* This AsyncTask continuously reads the input buffer and show the chat
* message if a message is availble.
*/
private class Receiver extends AsyncTask<Void, Void, Void> {
private String message;
@Override
protected Void doInBackground(Void... params) {
while (true) {
try {
if (bufferedReader.ready()) {
message = bufferedReader.readLine();
publishProgress(null);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
}
@Override
protected void onProgressUpdate(Void... values) {
textView.append("Server: " + message + "\n");
}
}
/**
* This AsyncTask sends the chat message through the output stream.
*/
private class Sender extends AsyncTask<Void, Void, Void> {
private String message;
@Override
protected Void doInBackground(Void... params) {
message = textField.getText().toString();
printwriter.write(message + "\n");
printwriter.flush();
return null;
}
@Override
protected void onPostExecute(Void result) {
textField.setText(""); // Clear the chat box
textView.append("Client: " + message + "\n");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Server Program

package com.lakj.comspace.simplechatserver;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
* This is the GUI component for chat window.
*
* @author Lak J Comspace (http://lakjeewa.blogspot.com)
*
*/
public class ChatWindow extends JFrame {
private JTextArea chatView;
private JButton sendButton;
private JTextArea chatBox;
/**
* This method open the chat window.
*
* @param clientSocket
* Socket which has been opened for chat
*/
public void open(final Socket clientSocket) {
initComponents();
setWinodwCloseListnerToCloseSocket(clientSocket);
initSenderAndReceiver(clientSocket);
}
/**
* This method initialize the components of the chat winodow.
*/
private void initComponents() {
chatView = new JTextArea(20, 46);
JScrollPane chatViewScrollPane = new JScrollPane(chatView);
chatBox = new JTextArea(5, 40);
JScrollPane chatBoxScrollPane = new JScrollPane(chatBox);
sendButton = new JButton("Send");
setResizable(false);
setTitle("Chat Server");
setSize(550, 450);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(chatViewScrollPane);
contentPane.add(chatBoxScrollPane);
contentPane.add(sendButton);
chatView.setEditable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
/**
* This method initialize the chat sender and receiver for this chat window.
*
* @param clientSocket
* Socket which has been opened for chat
*/
private void initSenderAndReceiver(final Socket clientSocket) {
Receiver receiver = new Receiver(clientSocket, chatView);
final Sender sender = new Sender(clientSocket, chatView);
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sender.sendMessage(chatBox.getText());
chatBox.setText(""); //Clear the chat box
}
});
Thread receiverThread = new Thread(receiver);
receiverThread.run();
}
/**
* This method register window closing listener to close the clientSocket
* when the chat window is closed.
*
* @param clientSocket
* Socket which has been opened for chat
*/
private void setWinodwCloseListnerToCloseSocket(final Socket clientSocket) {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
clientSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
}
view raw ChatWindow.java hosted with ❤ by GitHub
package com.lakj.comspace.simplechatserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.swing.JTextArea;
/**
* This is the chat receiver. This works as a thread and continuously check
* whether a message is available in the input buffer.
*
* @author Lak J Comspace (http://lakjeewa.blogspot.com)
*
*/
public class Receiver implements Runnable {
private BufferedReader bufferedReader;
private JTextArea chatView;
/**
* Public constructor.
*
* @param clientSocket
* Socket which has been opened for chat
* @param chatViewParam
* Chat history text area of chat window
*/
public Receiver(Socket clientSocket, JTextArea chatViewParam) {
chatView = chatViewParam;
try {
InputStreamReader inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
String message;
while (true) {
try {
if (bufferedReader.ready()) {
message = bufferedReader.readLine(); // Read the chat message.
chatView.append("Client: " + message + "\n"); // Print the chat message on chat window.
}
} catch (IOException ex) {
System.out.println("Problem in message reading");
ex.printStackTrace();
}
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
}
}
view raw Receiver.java hosted with ❤ by GitHub
package com.lakj.comspace.simplechatserver;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JTextArea;
/**
* This is the chat sender.
*
* @author Lak J Comspace (http://lakjeewa.blogspot.com)
*
*/
public class Sender {
private PrintWriter out;
private JTextArea chatView;
/**
* Public constructor.
*
* @param clientSocket
* Socket which has been opened for chat
* @param chatViewParam
* Chat history text area of chat window
*/
public Sender(Socket clientSocket, JTextArea chatViewParam) {
chatView = chatViewParam;
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String message) {
out.println(message); // Print the message on output stream.
chatView.append("Server: " + message + "\n"); // Print the message on chat window.
}
}
view raw Sender.java hosted with ❤ by GitHub
package com.lakj.comspace.simplechatserver;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* This is the main class for chat server.
*
* @author Lak J Comspace (http://lakjeewa.blogspot.com)
*
*/
public class SimpleChatServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
try {
serverSocket = new ServerSocket(4444);
System.out.println("Server started. Listening to the port 4444. Waitng for the client.");
clientSocket = serverSocket.accept();
System.out.println("Client connected on port 4444.");
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
e.printStackTrace();
return;
}
ChatWindow chatWindow = new ChatWindow();
chatWindow.open(clientSocket);
}
}

Following are the both Android client and Java server complete projects. You can clone or download them as zips from Git-Hub.

Git-Hub HTTPS clone URL: https://github.com/lakjcomspace/AndroidChatClientServer.git
Git-Hub Repository URL: https://github.com/lakjcomspace/AndroidChatClientServer
Download as a Zip: https://github.com/lakjcomspace/AndroidChatClientServer/archive/master.zip

You can run the projects by importing them to the IDE. Or just create you own project and copy and paste above source files.