Friday 19 November 2010

Monitor File for changes in Java

import java.io.File;import java.util.Hashtable;import java.util.Timer;import java.util.TimerTask;/** * Monitor files for changes. This singleton class maintains a map of files to * monitor and objects to notify when something they change. */public class FileMonitor { private static final FileMonitor SINGLETON = new FileMonitor(); private Timer timer; private Hashtable timerTasks; private FileMonitor() { timer = new Timer(true); timerTasks = new Hashtable(); } /** * Returns the singleton instance of this class. * @return the singleton instance */ public static FileMonitor getInstance() { return SINGLETON; } /** * Start monitoring a file. * * @param listener listener to notify when the file changed. * @param fileName name of the file to monitor. * @param period polling period in milliseconds. */ public void addFileChangeListener(FileChangeListener listener, String fileName, long period) { removeFileChangeListener(listener, fileName); FileMonitorTask task = new FileMonitorTask(listener, fileName); timerTasks.put(fileName + listener.hashCode(), task); timer.schedule(task, period, period); } /** * Remove the listener from the notification list. * * @param listener the listener to be removed. */ public void removeFileChangeListener(FileChangeListener listener, String fileName) { FileMonitorTask task = (FileMonitorTask) timerTasks.remove(fileName + listener.hashCode()); if (task != null) { task.cancel(); } } protected void fireFileChangeEvent(FileChangeListener listener, String fileName) { listener.fileChanged(fileName); } class FileMonitorTask extends TimerTask { FileChangeListener listener; String fileName; File monitoredFile; long lastModified; public FileMonitorTask(FileChangeListener listener, String fileName) { this.listener = listener; this.fileName = fileName; this.lastModified = 0; monitoredFile = new File(fileName); this.lastModified = getLastModified(); } private long getLastModified() { if (monitoredFile.exists()) { return monitoredFile.lastModified(); } else { return -1; } } @Override public void run() { long lastModified = getLastModified(); if (lastModified != this.lastModified) { this.lastModified = lastModified; fireFileChangeEvent(this.listener, this.fileName); } } } public interface FileChangeListener { public void fileChanged(String fileName); }}

Tuesday 12 October 2010

Java Socket Programming with AES Encryption

Server Side Code:
import java.io.*;
import java.net.*;

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class RealEchoServer{
public static void main(String[] args ){
int i = 1;
try{
ServerSocket s = new ServerSocket(9003);

for (;;){
Socket incoming = s.accept( );
System.out.println("Spawning " + i);
new RealEchoHandler(incoming, i).start();
i++;
}
} catch (Exception e){ System.out.println(e); }
}
}

class RealEchoHandler extends Thread{
DataInputStream in;
DataOutputStream out;
private Socket incoming;
private int counter;

public RealEchoHandler(Socket i, int c){
incoming = i;
counter = c;
}

public void run(){
try {


String key1 = "1234567812345678";
byte[] key2 = key1.getBytes();
SecretKeySpec secret = new SecretKeySpec(key2, "AES");
String msg = "Singapore Malaysia Japan India Indonesia HongKong Taiwan China England";
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] encrypted = cipher.doFinal(msg.getBytes());

in = new DataInputStream(incoming.getInputStream());
out = new DataOutputStream(incoming.getOutputStream());

boolean done = false;
String str="";
out.writeUTF("Connected!\n");
out.flush();
while (!done){
out.writeUTF(">");
out.flush();
str = in.readUTF();
System.out.println(in+":"+str);
if (str == null)
done = true;
else{
System.out.println("Sending Ciphertext : " + new String(encrypted));
out.writeUTF(new String(encrypted));
out.flush();
}
}
incoming.close();
} catch (Exception e){
System.out.println(e);
}
}
}

Client Side code:

import java.io.*;
import java.net.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;

class RealSocketTest{
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{

String str = "";
String str2 = "";
DataOutputStream out;
DataInputStream in;

try {
Socket t = new Socket("127.0.0.1", 9003);
in = new DataInputStream(t.getInputStream());
out = new DataOutputStream(t.getOutputStream());
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));

boolean more = true;
System.out.println(in.readUTF());

while (more) {
str = in.readUTF();
System.out.print(str);
str2 = br.readLine();
out.writeUTF(str2);
out.flush();
str = in.readUTF();

System.out.println("Encrypted Info: " + str);

try {

String key1 = "1234567812345678";
byte[] key2 = key1.getBytes();
SecretKeySpec secret = new SecretKeySpec(key2, "AES");

Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher.DECRYPT_MODE, secret);
byte[] decrypted = cipher.doFinal(str.getBytes());
System.out.println("Decrypted Info: " + new String(decrypted));
}
catch(BadPaddingException e){
System.out.println("Wrong Key!");
}
catch(InvalidKeyException f) {
System.out.println("Invalid Key!");
}
}
}
catch(IOException e){
System.out.println("Error");
}
}
}

This is just a proof of concept please feel free to customize yourself..Enjoy ;)