Linux Firewall
23 Apr 2009
My trusty and old firewall script. Simple but effective, deny all incoming connections except SSH and already established connections. It is a good starting point to customize it to your needs.
#!/bin/sh
#
#reject other connections...
/sbin/iptables -P INPUT DROP
/sbin/iptables -P FORWARD DROP
#accept loopback interface
/sbin/iptables -A INPUT -s 127.0.0.1 -d 127.0.0.1 -i lo -j ACCEPT
#accept established connection to pass
/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
#enable clients to connect to ssh
/sbin/iptables -A INPUT -m multiport -p tcp --dport ssh -j ACCEPT
#log activity (uncomment if needed)
#/sbin/iptables -A INPUT -j LOG -m limit
Java & OS X Integration
19 Apr 2009
Apple provides an Application class that allows you to integrate your application with the OS X environment. It allows Java applications to behave more like native OS X applications.
Handling Quit
Following snippet will install an window listener and run your clean up code before the application is exited. However when user selects Quit instead of hitting the close button, clean up code will not run.
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
//do something here
System.exit(0);
}});
In order to handle quit menu item. Apple's Application class class provides handlers, but these classes are Apple only, so you should not try loading them when you are not OS X. So wrap them in a class and load that class only when you are on OS X and use standard window listener on other operating systems.
import com.apple.eawt.*;
import com.apple.mrj.*;
public class MacApplication extends Application {
public MacApplication() {
addApplicationListener( new ApplicationAdapter(){
public void handleReOpenApplication(ApplicationEvent event) {
}
public void handleQuit( ApplicationEvent event ) {
//do something here...
System.exit(0);
}
public void handleAbout(ApplicationEvent event){
}
});
}
}
Now when Quit menu item is selected your application will run your clean up code.
Hiding your application
When you close a window on a Mac OS X, application is kept running and only the window is hidden. In order for our application to act more like a native application we should also implement this. Fortunately Application class provides a handler for that too.
public void handleReOpenApplication(ApplicationEvent event) {
mainFrame.setVisible(true);
}
Now when the dock icon is clicked your application will be visible and when closed, it will be hidden. Don't forget to set your main frame's default close operation to hide.
Knowing your OS
If you are not on OS X, you shouldn't load MacApplication class. On Mac OS X mrj.version system property is always set you can check it's value to see if you are on OS X. If it's set create your application object.
if(System.getProperty("mrj.version") == null){
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
//not on a mac cleanup
System.exit(0);
}});
}else{
MacApplication macApplication = new MacApplication();
}
Resources
Intercepting Links in Firefox
19 Apr 2009
While working on a Firefox extension i needed to intercept links Firefox is about to open and stop it on certain conditions. While it seems like an easy task it took more time then i thought due to not much information was available online. I saw the question asked multiple times with no definitive answer. Correct recipe turns out to be using a observer and listen for an "http-on-examine-response".
Following script will listen all request and you will have a chance to stop the transmission based on your rules.
var observer = {
observe: function(subject,topic,data){
var httpChannel =
subject.QueryInterface(Components.interfaces.nsIHttpChannel);
var contentType = httpChannel.getResponseHeader("Content-Type");
var channel = subject.QueryInterface(Components.interfaces.nsIChannel);
var url = channel.URI.spec;
url = url.toString();
if ( isDownloadable( url ) == true
&& contentType.indexOf("html") == -1 ){
window.getBrowser().stop();
download( url );
//alert("Wait a moment!\n"+ url );
}
//alert("Topic sent: " + topic);
}
};
var observerService =
Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(observer,"http-on-examine-response",false);
I am no extension guru, so maybe it is not the best way to do it but it gets the job done.
Compiling Java apps that use MRJ on a non-Apple computer
19 Apr 2009
I use multiple OS's for development mostly OS X and Linux. If you create an application that plays well with OS X. It will work with Linux , Mac or windows but you can't compile it under a non Apple machine because it uses non standard apple libraries (com.apple) not available under Linux or Windows. To overcome this problem we can use the Java Reflections API. Following these tips Java & OS X Integration you can stick all your Mac specific code under a single class and you can load it using reflections api. when you do that compiler will not compile about missing libraries since you are not accessing any Mac specific classes until runtime, as long as you are not trying to compile that Mac specific class.
try{
Class klass = Class.forName("macOs.MacApplication");
Class[] paramTypes = {
String.class,
String.class };
Constructor cons = klass.getConstructor(paramTypes);
Object[] args = {
"test",
"this" };
Object theObject = cons.newInstance(args);
}catch( Exception e ) {
}
References
Back Up and Restore a MySQL Database
17 Apr 2009
This is a personal reference, cause I keep forgetting the commands to backup and restore, my MySQL databases.
Backup
mysqldump -u user -p --opt db_name > backup.sql
For compressed backup,
mysqldump -u user -p --opt db_name | gzip -9 > backup.sql.gz
Restore
mysql db -u user -p < backup.sql
For compressed backup,
gunzip < backup.sql.gz | mysql db -u user -p
Using Netcat for File Transfers
15 Apr 2009
Netcat is like a swiss army knife for geeks. It can be used for just about anything involving TCP or UDP. One of its most practical uses is to transfer files. Non *nix people usually don't have SSH setup, and it is much faster to transfer stuff with netcat then setup SSH. netcat is just a single executable, and works across all platforms (Windows,Mac OS X, Linux).
On the receiving end running,
nc -l -p 1234 > out.file
will begin listening on port 1234.
On the sending end running,
nc -w 3 [destination] 1234 < out.file
will connect to the receiver and begin sending file.
For faster transfers if both sender and receiver has some basic *nix tools installed, you can compress the file during sending process,
On the receiving end,
nc -l -p 1234 | uncompress -c | tar xvfp -
On the sending end,
tar cfp - /some/dir | compress -c | nc -w 3 [destination] 1234
A much cooler but less useful use of netcat is, it can transfer an image of the whole hard drive over the wire using a command called dd.
On the sender end run,
dd if=/dev/hda3 | gzip -9 | nc -l 3333
On the receiver end,
nc [destination] 3333 | pv -b > hdImage.img.gz
Be warned that file transfers using netcat are not encrypted, anyone on the network can grab what you are sending, so use this only on trusted networks.
Setting Up Static ARP Table on Mac OS X
13 Apr 2009
On any LAN there is a danger of someone performing a man-in-the-middle attack against your traffic. One way to prevent this type of attack is setting up static entries, for hosts you are likely to communicate in your arp table.
Start by deleting all entries on you arp table,
sudo arp -s -d
Then add the hosts you are likely to communicate,
sudo arp -s 192.168.16.106 0:1e:58:b1:64:40
Or you can pass arp command a file containing all the entries,
arp -f file.name
This will save you from inputting them one by one, entries in the file should be in the following format,
hostname ether_addr
Java Single Instance Application
12 Apr 2009
Sometimes you want only one instance of your application running, at any one time. Java does not provide any API to detect if another instance of your application is running or not.
However there are two popular ways of forcing single instance,
- Acquire a lock on some magic file.
- Start listening on a socket.
Both techniques has pros and cons.
Socket Technique
With this technique we start listening on a port, only one process can listen on a socket so after first instance of our application binds itself to the socket other instances will get BindException, which means we are already running.
try{
ServerSocket socket =
new ServerSocket(9999, 10, InetAddress.getLocalHost());
}catch(java.net.BindException b){
System.out.println("Already Running...");
}catch( Exception e ) {
System.out.println(e.toString());
}
Cons of this approach is that some virus scanners will give a warning when an application starts listening on a socket, depending on your user base this could be interpreted badly. You should pick a port number thats not commonly used and high or you won't even get a single instance of your application running.
Lock Technique
We try to acquire a lock on a file in the applications data directory or on the applications main class file, if we can't, then it is safe to assume we are already running, and act accordingly.
try{
RandomAccessFile randomFile =
new RandomAccessFile("single.class","rw");
FileChannel channel = randomFile.getChannel();
if(channel.tryLock() == null)
System.out.println ("Already Running...");
}catch( Exception e ) {
System.out.println(e.toString());
}
Downside with this approach is it prone to I/O errors. Both techniques work and both has, ups and downs, pick the one that fits your situation.
So It Begins
10 Apr 2009
First entry would of course have to be a test entry.. so.. testing.. 1.. 2.. 3..