Thursday, August 20, 2009

Practice Alien Number - Code Jam 2009

import java.util.*; import java.io.*; public class AlienNumber{ private static int digits = -1; private static int sourceIndex = -1; private static String targetNo = null; private static List sourcenos = new ArrayList(); private static List targetnos = new ArrayList(); private static boolean found = false; public static void main(String[] args)throws Exception{ BufferedReader br = new BufferedReader(new FileReader(args[0])); int noOfCases = Integer.parseInt(br.readLine().trim()); int i = 0; while(i < params =" br.readLine().split(" targetno =" params[0];" digits="="-1){" digits =" -1;" sourceindex =" sourcenos.size()-1;" sourcenos =" null;" digits="="-1){" digits =" -1;"> nos){ for(int j=0;j(); targetnos = new ArrayList(); found = false; System.gc(); } }

Thursday, March 5, 2009

Adding an Icon to your Web Page

Nowadays you would have seen web pages with icons; They are visible 

1. In the address box,
2. In the Favorites (Bookmarks) pane and menu,
3. Modern browsers also display them in tabs,
4. there is also an extension for Firefox, which displays favicons on Google search pages.

It is very easy to add an icon. You just have to create a small icon possibly 16 x 16 pixels and add the following code in your html page,

Between the head tag put link rel="shortcut icon" href="Name of the File"


If you want to an animation as your icon create your animation as a gif file and place it in the above tag.

http://coderpassion.comuf.com

Thursday, February 26, 2009

Robot in Java

java.awt.Robot can be used to automate Keyboard,Mouse and many other. Here is a small
example of a keyboard operation the Robot object can do. 

RobotTest.java

import java.awt.*;
import java.awt.event.*;

/*
 * @author Shazin Sadakath
 * 
*/

public class RobotTest{
public static void main(String[] args){
try{
Robot robot = new Robot();
robot.delay(500);
robot.keyPress(KeyEvent.VK_C);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_D);
robot.keyPress(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_R);
robot.keyPress(KeyEvent.VK_P);
robot.keyPress(KeyEvent.VK_A);
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_I);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_N);
}catch(Exception e){
System.err.println(e.getMessage());
}
}
}

open up a notepad and then run the RobotTest

$ java RobotTest

and then click on the opened up notepad.

Wednesday, February 25, 2009

Hello World using Java RMI

Java RMI (Remote Method Invocation) is a variation of Remote Procedure Calls implemented out and out with Java Programming language and integrated seamlessly into Java API. Java RMI uses JNDI (Java Naming and Directory Interface) to host Java Objects on a Remote Server and allow them to be accessed via multiple clients thus providing a distributed usage of those hosted Java Objects. These hosted Java Objects actually reside in one JVM. But they are hosted in a registry so that they can be used from other JVMs too. once a Java Object of one JVM is bounded in a registry Processes from other JVMs can access it and call all the methods of that Java Object. Parameters can also be passed into those objects as well as returned values can also be captured.

Here we discuss about a simple hello world application using Java RMI.

 

Greetable.java

import java.rmi.*;

/**

 * @author Shazin Sadakath

 *

 **/

public interface Greetable extends Remote{

            public String sayHello() throws RemoteException;

}

Greeter.java

import java.rmi.registry.*;

import java.rmi.*;


/**

 * @author Shazin Sadakath

 *

 **/

public class Greeter implements Greetable{

             public String sayHello(){

                          String greeting = “Hello, World!”;

                         System.out.println(greeting);

                         return greeting;

             }

}

RMIServer.java

import java.rmi.registry.*;

import java.rmi.*;

import java.rmi.server.*;

/**

 * @author Shazin Sadakath

 *

 **/

public class RMIServer{

              public static void main(String[] args){

             try{

                          String ip = args[0];

                          int port = Integer.parseInt(args[1]);

                          Registry registry = LocateRegistry.getRegistry(ip,port);

                          Remote obj = UnicastRemoteObject.exportObject(new Greeter(),0);

                          registry.rebind(”Greeter”,obj);

                          System.out.println(”RMI Server Started”);

               }catch(ArrayIndexOutOfBoundsException aie){

                         usage();

               }catch(Exception re){

                         System.err.println(re.getMessage());

               }

}


private static void usage(){

                System.out.println(”Usage: java RMIServer ”);

}

}

RMIClient.java

import java.rmi.registry.*;

import java.rmi.*;

/**

 * @author Shazin Sadakath

 *

 **/

public class RMIClient{

              public static void main(String[] args){

              try{

                          String ip = args[0];

                          int port = Integer.parseInt(args[1]);

                          Registry registry = LocateRegistry.getRegistry(ip,port);

                          Greetable greeter = (Greetable) registry.lookup(”Greeter”);

                          System.out.println(greeter.sayHello());

              }catch(ArrayIndexOutOfBoundsException aie){

                         usage();

              }catch(Exception e){

                         System.err.println(e.getMessage());

              }

}


private static void usage(){

               System.out.println(”Usage: RMIClient ”);

}

}

Starting the RMI Registry in localhost

$ rmiregistry 9999

Starting the RMI Server in localhost

$ java RMIServer 127.0.0.1 9999

Starting the RMI Client in localhost

$ java RMIClient 127.0.0.1 9999

 

RMI provides fast and reliable distributed application capabilities. Thus has become a major part in network based applications.

JFrame without Title Bar

JFrame is the most widely used GUI frame is Stand alone applications. Often coders need to display JFrame windows without the title bar. This code snippet shows how you can accomplish that.

JFrameTitleBarTest.java

import javax.swing.*;

/**

 * @author Shazin Sadakath

 *

**/

public class JFrameTitleBarTest{

              public static void main(String[] args){

                           JFrame jframe = new JFrame(”JFrame Title Bar Test”);

                           jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE);

                           jframe.setUndecorated(true);

                           jframe.setSize(400,400);

                           jframe.setLocationRelativeTo(null);

                           jframe.setVisible(true);

            }

}


Listing all Environment Variables and System Properties of a Java Application

When a Java Application initiates, by default it is loaded with some environment variables and system properties it can use. Using these environment variables and system properties ensures 100% platform independence. Following is a program which lists all the environment variables and system properties a Java Application can use.

EnvironmentVariables.java

import java.util.*;

/**

 * @author Shazin Sadakath

 * 

**/

public class EnvironmentVariables{

              public static void main(String[] args){

                         Map env = System.getenv();

                         Collection col = env.keySet();

                         System.out.println(”– Environment Variables –\n”);

                         for(String s:col){

                                   System.out.println(s + “=” + env.get(s));

                         }

                         System.out.println();

                         Properties props = System.getProperties();

                         props.list(System.out);

            }

}

Finding Protocol Type using Java

HTTP is the most widely used communication protocol of the internet. But nowadays HTTPS is also coming up and catching up with its secured connections. HTTPS provides encryption while transmitting data packets and provides a 3rd party verification of the server, confirming that a url is a valid one and that it actually represents the body which it claims to be representing. 

This java code snippet differentiates a given url by categorizing it as HTTP or HTTPS

ProtocolType.java

import java.net.*;

import javax.net.*;

import javax.net.ssl.*;

import java.io.IOException;

/**

 * @author Shazin Sadakath

 *

**/

public class ProtocolType{

              public static void main(String[] args){

                       try{

                                        URL url = new URL(args[0]);

                                        URLConnection connection = url.openConnection();

                                        connection.connect();

 

                                        if(connection instanceof HttpURLConnection){

                                                       System.out.println(”This is a valid HTTP Protocol”);

                                        }else if(connection instanceof HttpsURLConnection){

                                                       System.out.println(”This is a valid HTTPS Protocol”);

                                        }else{

                                                       System.out.println(”This is a unrecognized Protocol”);

                                        }

                       }catch(ArrayIndexOutOfBoundsException aiobe){

                                        usage();

                       }catch(MalformedURLException mue){

                                         System.out.println(”Not a valid URL”);

                       }catch(IOException ioe){

                                         System.out.println(”Can not Connect to ” + args[0]);

                       }

          }

 

           private static void usage(){

                           System.out.println(”Usage: ProtocolType \n Ex: ProtocolType http://coderpassion.wordpress.com”);

           }

}

If you are in a network which uses a proxy server to connect to the internet use

$ java -Dhttp.proxyHost= ProtocolType