Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, September 21, 2011

Holiday Calendar

This is a Java application which can indicate the Sri Lankan holidays (other followers please don't mind). If you hover the mouse over the marked date, it'll indicate the holiday in detail as well.


 


You can use this application instead of windows calender gadget.
To download this application click here.


To run this app in startup,

  • Extract the My Calendar.rar
  • Create a desktop shortcut for HolidayCalendar.jar
  • Copy that shortcut and paste it in StartMenu/Programs/StartUp (can find in start menu) folder
I appreciate your valuable comments...


Tuesday, September 13, 2011

Some Useful Functions Related to Geo Coordinates

//GIVE THE DISTANCE BETWEEN TWO LAT, LNG COORDINATES IN METERS
public double distanceInMeters(double lat1, double lng1, double lat2,double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)* Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;
int meterConversion = 1609;
return dist * meterConversion;
}


//GIVE THE NEAREST LAT, LNG COORDINATE WHICH IS IN A ROAD, FOR THE GIVEN LAT, LNG
private double[] nearToRoad(double[] latLng1) {
double[] latLng = new double[] { latLng1[0], latLng1[1] };
try {
URL url = new URL(
"http://maps.googleapis.com/maps/api/directions/xml?origin="+ latLng1[0] + "," + latLng1[1] + "&destination=" + latLng1[0] + "," + latLng1[1] + "&sensor=false");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("<lat>")) {
latLng[0] = Double.parseDouble(line.substring(line.indexOf('>') + 1, line.indexOf('/') - 1));
line = reader.readLine();
latLng[1] = Double.parseDouble(line.substring(line.indexOf('>') + 1, line.indexOf('/') - 1));
break;
}
}
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return latLng;
}


//GIVE THE ADDRESS OF THE LAT, LNG COORDINATE (REVERSE GEOCODING)
public String findLocationAddress(double lat, double lng) {
String name = "unnamed";
try {
URL url = new URL(
"https://maps.googleapis.com/maps/api/geocode/xml?latlng="+ lat + "," + lng + "&sensor=false");
BufferedReader reader = new BufferedReader(new InputStreamReader(
url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("<formatted_address>")) {
name = line.substring(line.indexOf('>') + 1,line.indexOf('/') - 1);
break;
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return name;
}

Approximate String Matching


Here I used Levenshtein Distance method to calculate the amount of similarity between two strings. The method LevenshteinDistance(String source, String target) will return the cost to convert the source string to target string, by considering insertion, deletion and substitution of a character, each of them costs 1.

In the Tester class you can use an appropriate threshold to get the approximate matching strings.

public class StringUtils {

    public static int LevenshteinDistance(String source, String target) {
        // d[i,j] will hold the Levenshtein distance between
        // the 1st i characters of s & the 1st j characters of t;
        // note that d has (m+1) x (n+1) values

        int m = source.length(), n = target.length();
        int[][] d = new int[m][n];
        char[] s = source.toLowerCase().toCharArray();
        char[] t = target.toLowerCase().toCharArray();

        for (int i = 0; i < m; i++) {
            d[i][0] = i; // any 1st string to an empty 2nd string
        }
        for (int j = 0; j < n; j++) {
            d[0][j] = j; // any 2nd string to an empty 1st string
        }

        for (int j = 1; j < n; j++) {
            for (int i = 1; i < m; i++) {
                if (s[i] == t[j]) {
                    d[i][j] = d[i - 1][j - 1]; // no operation
                } else {
    //minimum of DELETION, INSERTION, SUBSTITUTION (each costs 1)
    d[i][j] = Math.min(d[i - 1][j] + 1, Math.min(d[i][j - 1] + 1, d[i - 1][j - 1] + 1));
                }
            }
        }
        return d[m - 1][n - 1];
    }
}

public class Tester {

    public static void main(String[] args) {
        List<String> suggestionList = new ArrayList<String>();
        List<String> sourceList = new ArrayList<String>();
sourceList.add("abc");
sourceList.add("abcefg");
sourceList.add("abcfgh");
sourceList.add("abcdhfgi");
sourceList.add("abcd ghi");
sourceList.add("abcdefgh");
        for (String s : sourceList) {
            int editCost = StringUtils.LevenshteinDistance(s,"abcdefgh");
            if (editCost <= 3) {
                suggestionList.add(editCost + s);
            }
        }
//Sort, best match first
        Collections.sort(suggestionList);
        int count = 0;
        for (String s : suggestionList) {
            System.out.println(s);
        }
    }
}

Guess the output...

Sunday, January 23, 2011

Progress Bar Demo

import java.awt.*;
import javax.swing.*;
Interface Design
class Progress extends JFrame{
PbThread t1;
JProgressBar pb;
JLabel l;

Progress() {
super("Progress Bar");
setLayout(null);
setResizable(false);
setSize(300,100);

pb=new JProgressBar();
add(pb);
pb.setBounds(10,12,270,25);
l=new JLabel();
l.setText("");
add(l);
l.setBounds(120,40,97,25);

Dimension ss=Toolkit.getDefaultToolkit().getScreenSize();
Dimension ws=getSize();
this.setBounds((ss.width-ws.width)/2,(ss.height-ws.height)/2,ws.width,ws.height);

t1=new PbThread(pb,l);
t1.start();
}
public static void main(String args[]){
Progress p=new Progress();
p.setVisible(true);
}
}

Thread to show Progress
class PbThread extends Thread{
JProgressBar pb1;
JLabel l1=new JLabel();

PbThread(JProgressBar pb,JLabel l) {
this.pb1=pb;
this.l1=l;
}
public void run(){
pb1.setMaximum(100);
pb1.setMinimum(0);
for(int x=0;x<=100;x++) {
pb1.setValue(x);
l1.setText(x+"%");
try {
sleep(100);
}
catch(InterruptedException e) {
JOptionPane.showMessageDialog(null,e,"Error",JOptionPane.ERROR_MESSAGE);
}
if(x==100)
System.exit(0);
}
}
}

Sunday, December 26, 2010

Download File in a Server-Client Application

This program downloads a mp3 file from server to client using TCP socket connection. AudioFile is a user defined class.

Client Side Code

public void downloadAudio(AudioFile a) {
    File myDir = null;
    try {
        myDir = new File("Downloads");
        myDir.mkdir();
        
        getConnection();
        oos = new ObjectOutputStream(soc.getOutputStream());
        oos.writeObject(a);

        in = new BufferedInputStream(soc.getInputStream());
        File f = new File("Downloads/" + a.getTrackName() + ".mp3");
        out = new FileOutputStream(f);

        int i = 0;
        downloaded = 0;
        
        byte[] bytesIn = new byte[1024];
        while ((i = in.read(bytesIn)) >= 0) {
            out.write(bytesIn, 0, i);
            downloaded += bytesIn.length;
        }
        out.close();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
    }
}

Server Side Code

private void download(File file) {
    try {
        out = new BufferedOutputStream(soc.getOutputStream());
        in = new FileInputStream(file);
        int i = 0;
        byte[] bytesIn = new byte[1024];
        while ((i = in.read(bytesIn)) >= 0) {
            out.write(bytesIn, 0, i);
        }
        out.close();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Saturday, December 25, 2010

Parallel Execution Using Multi-Core CPU

This program assumes multi-core CPU and split the process and execute them parallelly.

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;

public class parallel {    
    int x[] = new int[1000000];
    float xcl[] = new float[1000000];
    float xcl2[] = new float[1000000];
    float y2[];
    
    void process() throws InterruptedException, BrokenBarrierException{
        //Instantiate values
        for(int i =0; i<1000000;i++){
           xcl[i] = i;
        }
        //Create the executor object
        ExecutorService exec = Executors.newCachedThreadPool();
        //Create of CPU tasks
        class AddTask extends Thread {
              public  int n = 0;
              AddTask(int x){
                //  this.setPriority(10);
                  n = x;
              }
            public void run() {
                for(int i =n; i< n + 500000 -1;i++){
                    for(int j = 0 ; j<10000;j++){
                    x[i] = x[i]+ j;
                   }
                }
                 //Barrier to control thresds
              }
        }
        Runnable t1 = new AddTask(0);
        Runnable t2 = new AddTask(500000);
        exec.submit(t2);
        exec.submit(t1);
        exec.shutdown();
    }
    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
         (new  parallel()).process();
    }
}

Thursday, December 16, 2010

Accessing MySql Database

Here System is the mysql database name and table name is Administrator

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import modalclasses.Administrator; //user defined class

public class DBHandler {

    private Connection con;
    private Statement st;
    private ResultSet rs;
    private PreparedStatement ps;

    public Connection getMySqlConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/mysql";
        return DriverManager.getConnection(url, "root", "");
    }

    public void addAdmin(Administrator a) throws SQLException, ClassNotFoundException {
        con = getMySqlConnection();
        ps = con.prepareStatement("insert into System.Administrator values(?,?,?,?,?)");
        ps.setString(1, a.getUserName());
        ps.setString(2, String.valueOf(a.getPassword()));
        ps.setString(3, a.getName());
        ps.setString(4, a.getGender());
        ps.setString(5, a.getEmail());
        ps.executeUpdate();
        con.close();
    }

    public Administrator getAdminDetails(String uname) throws ClassNotFoundException, SQLException {
        con = getMySqlConnection();
        st = con.createStatement();
        rs = st.executeQuery("select * from System.Administrator where Username='" + uname + "'");
        if (!(rs.next())) //if Admin is not found
        {
            return null;
        } else {
            return new Administrator(uname,rs.getString("Password"),rs.getString("Name"),rs.getString("Gender"),rs.getString("Email"));
        }
    }

    public void updateAdmin(Administrator a, String uname) throws ClassNotFoundException, SQLException {
        con = getMySqlConnection();
        ps = con.prepareStatement("update System.Administrator set Username=?,Password=?,Name=?,Gender=?,Email=?" + "where Username='" + uname + "'");
        ps.setString(1, a.getUserName());
        ps.setString(2, String.valueOf(a.getPassword()));
        ps.setString(3, a.getName());
        ps.setString(4, a.getGender());
        ps.setString(5, a.getEmail());
        ps.executeUpdate();
        con.close();
    }

    public void deleteAdmin(String uname) throws ClassNotFoundException, SQLException {
        con = getMySqlConnection();
        ps = con.prepareStatement("delete from System.Administrator where Username='" + uname + "'");
        ps.executeUpdate();
        con.close();
    }
}

TCP Server-Client Application

Server Application

import java.io.*;
import java.net.*;

public class TCPServer{
public static void main(String args[]){
int port=8088;
ServerSocket ser1=null;
PrintWriter pr=null;
BufferedReader br=null;
String str;
Socket soc1=null;

try{
ser1=new ServerSocket(port);
}catch(IOException e){
System.exit(0);
}
while(true){
try{
soc1=ser1.accept();     
        pr=new PrintWriter(new OutputStreamWriter(soc1.getOutputStream()));
pr.println("Client is connected");
        br=new BufferedReader(new InputStreamReader(soc1.getInputStream()));

while((str=br.readLine()) != null)
   System.out.println(str);

if(soc1!=null){
pr.close();
soc1.close();                
}
}catch(IOException e) {
System.out.println(e);
}
}
}
}

Client Application

import java.io.*;
import java.net.*;

public class TCPClient{
public static void main(String args[]){

Socket soc1;
BufferedReader br;
String str;
PrintWriter pr=null;
try{
soc1=new Socket("127.0.0.1",8088);        
        br=new BufferedReader(new InputStreamReader(soc1.getInputStream()));

while((str=br.readLine()) != null)
   System.out.println(str);
        
        pr=new PrintWriter(new OutputStreamWriter(soc1.getOutputStream()));
pr.println("Server is connected");

br.close();
soc1.close();
pr.close();
}catch(ConnectException e){
 System.out.println(e);
}catch(IOException e){
System.out.println(e);
}       
}
}

Wednesday, December 8, 2010

Generic Binary Search Tree

Tree Node
public class TreeNode<T extends Comparable<T>> {
    TreeNode<T> leftNode;
    TreeNode<T> rightNode;
    T data;
    public TreeNode(T nodeData) {
        data = nodeData;
        leftNode = rightNode = null;
    }
    public void insert(T insertValue) {
        if (insertValue.compareTo(data) < 0) {
            if (leftNode == null) {
                leftNode = new TreeNode<T>(insertValue);
            } else {
                leftNode.insert(insertValue);
            }
        }else if (insertValue.compareTo(data) > 0) {
            if (rightNode == null) {
                rightNode = new TreeNode<T>(insertValue);
            } else {
                rightNode.insert(insertValue);
            }
        }
    }
}

Binary Search Tree

public class Tree<T extends Comparable<T>>      {
    private TreeNode<T> root;
    public Tree() {
        root = null;
    }
    public void insertNode(T insertValue) {
        if (root == null) {
            root = new TreeNode<T>(insertValue);
        } else {
            root.insert(insertValue);
        }
    }
    public void preOrderTraversal() {
        preOrderHelper(root);
    }
    private void preOrderHelper(TreeNode<T> node) {
        if (node == null) {
            return;
        }
        System.out.print(node.data + " ");
        preOrderHelper(node.leftNode);
        preOrderHelper(node.rightNode);
    }
    public void inOrderTraversal() {
        inOrderHelper(root);
    }
    private void inOrderHelper(TreeNode<T> node) {
        if (node == null) {
            return;
        }
        inOrderHelper(node.leftNode);
        System.out.print(node.data + " ");
        inOrderHelper(node.rightNode);
    }
    public void postOrderTraversal() {
        postOrderHelper(root);
    }
    private void postOrderHelper(TreeNode<T> node) {
        if (node == null) {
            return;
        }
        postOrderHelper(node.leftNode);
        postOrderHelper(node.rightNode);
        System.out.print(node.data + " ");
    }
}

Generic Linked List

List Element
public class ListNode<T> {
    T data1;
    T data2;
    ListNode<T> nextNode;
    public ListNode(T data1, T data2) {
        this(data1, data2, null);
    }
    public ListNode(T data1, T data2, ListNode<T> nextNode) {
        this.data1 = data1;
        this.data2 = data2;
        this.nextNode = nextNode;
    }
    public T getData1() {
        return data1;
    }
    public T getData2() {
        return data2;
    }
    public ListNode<T> getNextNode() {
        return nextNode;
    }
}


Linked List

public class List<T> {
    private ListNode<T> firstNode;
    private ListNode<T> lastNode;
    private String name;
    public List() {
        this("list");
    }
    public List(String name) {
        this.name = name;
        firstNode = lastNode = null;
    }
    public void add(T item1, T item2) {
        if (isEmpty()) {
            firstNode = lastNode = new ListNode<T>(item1, item2);
        } else {
            lastNode = lastNode.nextNode = new ListNode<T>(item1, item2);
        }
    }
    public boolean isEmpty() {
        return firstNode == null;
    }
    public String toString() {
        StringBuilder temp = new StringBuilder();
        if (isEmpty()) {
            temp.append("Empty " + name);
        } else {
            ListNode<T> current = firstNode;
            while (current != null) {
                temp.append(current.data1 + ":" + current.data2);
                temp.append(", ");
                current = current.nextNode;
            }
            temp.deleteCharAt(temp.length()-2);
        }
        return temp.toString();
    }
}

Tuesday, December 7, 2010

Media Player

Media Test Class
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class MediaTest {
    public static void main(String[] args) {
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) {
            URL mediaURL = null;
            try {
                mediaURL =                fileChooser.getSelectedFile().toURI().toURL();
            } catch (MalformedURLException e) {
                System.err.println("Could not create URL for the file!..");
            }
            if (mediaURL != null) {
                JFrame mediaTest = new JFrame("Media Tester");                mediaTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                MediaPanel mediaPanel = new MediaPanel(mediaURL);
                mediaTest.add(mediaPanel);
                mediaTest.setSize(300, 300);
                mediaTest.setVisible(true);
            }
        }
    }
}

Media Panel Class
import java.awt.BorderLayout;
import java.awt.Component;
import java.io.IOException;
import java.net.URL;
import javax.media.CannotRealizeException;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.swing.JPanel;
public class MediaPanel extends JPanel {
    MediaPanel(URL mediaURL) {
        setLayout(new BorderLayout());
        Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true);
        try {
            Player mediaPlayer = Manager.createRealizedPlayer(mediaURL);
            Component video = mediaPlayer.getVisualComponent();
            Component controls = mediaPlayer.getControlPanelComponent();
            if (video != null) {
                add(video, BorderLayout.CENTER);
            }
            if (controls != null) {
                add(controls, BorderLayout.SOUTH);
            }
            mediaPlayer.start();
        } catch (NoPlayerException e) {
            System.err.println(e);
        } catch (CannotRealizeException e) {
            System.err.println(e);
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}