Thursday, 20 September 2012

Random Key Generator

Sometimes we do need some sort of random key , say for example :

* Sending some unique password / key for one time authentication
* Generating some random user name
* Generating one time password
* validate email / mobile number

and so on ...

So why to bother every time writing some code for generating random number. Here is solution :

Download Random Generator Jar

Just include this jar file and use utility functions :

Example :


package testing;

import com.affiance.yim.gaurav.random.RandomKeyGenerator;

public class Testing {
public static void main(String[] s) {
System.out.println(RandomKeyGenerator.getRandomAlbhabeticKey(10));
System.out.println(RandomKeyGenerator.getRandomAlphaNumericKey(10));
System.out.println(RandomKeyGenerator.getRandomNumericKey(10));
}
}


Functions take a parameter, length of key you want to generate.

Enjoy Coding !















keywords for SEO  : java j2ee random secret unique key password alphanumeric alphabetic numeric length

Monday, 2 July 2012

Android Emulator Networking


Android Networking Issues :

connect form host to emulator , connect from emulator to host machine , ping host from emulator , ping emulator from host , server running in emulator and connect from through host, server running in host machine and connect from emulator


One of the simplest (but time eater) scenario I have faced is networking between your Android emulator and your Host machine.
Two problems I have faced are :

1) Connect Emulator to a Server running in host machine
2) Connect Host Machine to Server running in emulator


Out of these two, second one became real headache for me. But atlast solution I found was so simple.

**********************************************************************


Solution 1  : Connect emulator to server running in host machine :

For emullator , IP address of host machine is 10.0.2.2

So you can use this IP to connect to your host machine, for example:

Let us assume a web application ""sample" is running at port 8084 in your host machine.

Type

http://10.0.2.2:8084/sample

and press enter, it will print your desired output.


**********************************************************************


Solution 2:

Connect Host machine to server running in emulator :

By default emulator IP is 10.0.2.15 , but problem you will be facing is you can not connect using this IP and even
you can not ping this IP.

So solution I found was port redirection, very simple to do :

Assume one instance of emulator is running

Steps:

i) open command prompt
ii) type " telnet localhost 5554 "  ans press enter  
iii)type " redir add tcp:fromPort:whichPort " and press enter

Step 3 here redirect your request, mean any request you will make using localhost:fromPort will deliver to emulator:toPort

iv) you can del redirection using command :

redir del tcp:fromPort

v) If you are working with udp, then use udp instead of tcp in command


Sunday, 1 July 2012

Java : Inheritance and Interfaces , A magic or what ?




In Java usually we see there are event listeners ( say OnClickListener, OnTouch, OnDataArrived  or any other ) , what we do is simply pass reference of our object to required method and it automatically calls
appropriate methods of our class based on events. Most of people think it as magic or do not think it at all. Now we are going to see after all how does it work !

All this thing is based on mainly two imoprtant properties of Java : Inheritance and Polymorphism.

To understand how the main stuff happens, you must have clear idea of these two properties. Let us dive into both one by one.

Inheritance :

Inheritance can simply be defined as inheriting properties of a class by another class. It is important to note we can inherit only  " public ,default and protected members " in same package and
only " public and protected members " in other packages. Take an example :

package first;               

public class Animal {
int defaultInt;
protected int protectedInt;
protected int age;

public void printAge(){
System.out.println("printing Animal's age");
}

public void animalSound(){
System.out.println("animal sound @@@@");
}

}


public class Dog extends Animal {

public void checkDefault( ) {

defaultInt = 9;                                                    // valid because Dog inhertis Animal and because of same package

}

public void checkProtected() {

protectedInt = 9;                                                            // valid because Dog inhertis Animal and because of same package


}

public void printAge(){
System.out.println("printing dog's age");
}


public void sound(){
System.out.println("bhow bhow");
}

}


***************************************************************************************

package second;
import first.Animal;

public class Cat  extends  Animal {


public void checkDefault( ) {

defaultInt = 9;                                                    // not valid because of different package

}

public void checkProtected() {

protectedInt = 9;                                                            // valid because Cat  inhertis Animal


}

public void printAge(){
System.out.println("printing cat's age");
}

public void sound(){
System.out.println("meaau meaau");
}

}



***************************************************************************************
Java allows us to define an object by :

ClassName object = new ClassName();

and

SuperClassName object = new SubClassName();                                    // valid , but we are restricting our object to call only methods and properties present in class SuperClassName

but

SubClassName object = new SuperClassName();                                    // invalid

***************************************************************************************



***************************************************************************************
***************************************************************************************

Now coming to Polymorphism :

Simplest Definition will be : one name , multiple behavior.

Like we can have more than one same name function in a class, only diefference we  make is between their parameters.

These functions are called overloaded functions.

But there is one more term called overriding, it come into existance during inheritance. (I am not gonna explain overriding in detail here)

Simply Overriding mean having same signature of a function in both superclass and subclass with rules specified by Java.

As we saw above Java allows us :

SuperClassName object = new SubClassName();

considering above Animal example:

Animal animal = new Cat();

but now we can not call any cat specific function, since our reference is through Animal. We are restricted to call only functions present in Animal.

i.e :   animal.sound()                              // it is invalid

            animal.printAge()                       // is valid

            animal.animalSound()                // is valid

as expected
            animal.animalSound() will print "animal sound @@@@"

            but what do you expect on calling :

            animal.printAge();                      // printing animal's age   ??

but here polymorphism comes into picture

and output is :   printing cat's age

it mean in Java at compile time we can call only those methods which are present in Reference class, but at runtime if Actual class of which object was initialized ( using new )
overrides function, Java calls overridden function.

And that is how EventListener works in Java.

As you might have noticed almost all EventListeners are interfaces which incorporates some abstract functions that you might be interested if that event happens. So what actually happens is when we implement any
such interfacewe do implement all those functions. and I assume you are familiar with following term:

 ( YourClass impements OnClickListener )

button.setOnClickListener(this);              // assuming you are having any button in your class and want to know when its click event happens, this way you register your class and binds

Now have you ever wondered what magic happens at the other end (In Button class) , how button class knows about your object and passes proper events to your implemented function

Answer is polymorphism that we saw just in above example (Animal)

In Button class , It do nor need your object but it needs OnClickListener Object and since your class is implementing the same, so it becomes the required

Now in Button Class any whenever event happens, it just simply calls

clickListener.onEvent();

and due to polymorphism, your class function gets called.


Any question , you can email me at : khannasahab.gaurav@gmail.com

**********************************************************************************

Thursday, 12 April 2012

Java bypass proxy with code

Setting proxy in / with java code

As We normally use httpconenction class for url connection. Sometimes it can create problem, specially
when you are working in a System in which internet is blocked by any proxy. So you have to authenticate yourself by giving username and password .

Before your credentials you need to tell JVM which proxy you have and it is running on which port. This can be accomplished by following two lines.

   System.setProperty("http.proxyHost", PROXY);
            System.setProperty("http.proxyPort", PROXY_PORT);

Now we need to authenticate ourselves which can be done by using simple one line code given below :

            Authenticator.setDefault(new MyAuthenticator());

Here MyAuthenticator is authenticator class used to authenticate user, username and password, just
overide getPasswordAuthentication() function, i.e :


public class MyAuthenticator extends Authenticator {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {

        return new PasswordAuthentication("UserName", "Password".toCharArray());
    }
}


Copy and paste above Authenticator class in your project and replace username and password with yours.

                     Note:  Do all above task before making your URLConnection

Java Client http / https connection

Hi,

If you are facing as simple problem as hitting an URL through java code and getting response back, you are at right place. It is damn simple. Just follow steps given below :

1 ) Include myclient.jar file in your project.  click here to download jar file

2) Make an object of ClientURLConnection.

3) Pass URL you want to hit.

3) Set method you want to send request (GET or POST)

4) Add parameters (key-value pair) , if any you want to send along with request.

5) Call method yourObject.getInputStream()

And it is done !! Now do not waste time here and complete your task :)


Saturday, 3 September 2011

File Handling Became Easy In Java!!

Wanna copy file from one directory to other ! Wanna copy entire directory from one place to another ! Finding File I/O difficult to understand !

Here is the Jar file to rescue!!



Just  Include this Jar  file in your project and use MyFileUtil class.


Here is the example:

/**
*  call copyFile method to copy any file from one directory to other.
*  call copyDirectory to copy entire directory from one place(in computer) to
*  another (in computer).
*/


Download !

Sunday, 20 March 2011

Serialization In Java

Why Serialization..

Used to send object from one program to other or more generic (from one place to other).

Simple example is from server to client.

How . .

First of all you must have data to send.

It must be object of any type.

We have two sides now..

    1) Source ( will send data (server) )

    2)Destination ( will receive data (client) )

Even the last terms are not correct , in many cases we want bidirectional communication.

    Eg.  Send data from client to server for storing in database ,

    Process some result and send data back to client.

So we can conclude client and server are not appropriate terms , more generic terms will be Sender and Receiver.

At a time client can be sender or receiver (Depends upon the situation and need).

Same for server

So now we are ready to speak technically

First of all to send / communicate between wo medium , we should have a way

  (In fact how can you talk with somebody without a phone)

Lets Do It :

Now we will try to make medium :)

In java that medium is "Stream"

It can be output stream as well as input stream.

Remember we are not categorizing both parties as client and server , but there is

 Java  servlet ( Server) at one end and simple Java class (Client)  at other end.

..(Client side)

First of all for making connection we must have IP address / host address of server.

    (How can you  post  a letter without home address)

Make a http connection using IP address .

Always Try To Take Advantage of OOPS.

So make separate class to make http connection (Remember the chaos of public, protected and private and specially our own default).

Here we go ..

/*

  class for making http connection , all you need to do is call getHttpConnection() methos by passing the address with which you want to make connection.

*/

public class HttpConnection {

    public URLConnection getHttpConnection(String servletUrl) throws MalformedURLException {

        try {

            /*

             * Attempt to establish a conncetion to the servlet URL

             */

            URL url = new URL(servletUrl);

            URLConnection connection = url.openConnection(java.net.Proxy.NO_PROXY);

 /*

             * This connection does both input and output; Therefore set the

             * appropriate flags to true.

             */

            connection.setDoInput(true);

            connection.setDoOutput(true);

            connection.setUseCaches(true);

            connection.setDefaultUseCaches(true);

            /*

             * Set the content type of the Http request to octet-stream as

             * the e-mail message is going to be sent as an Object

             */

            connection.setRequestProperty("Content-Type","application/application");

          return (connection);

        } catch (Exception e) {

            System.out.println(e);

            return (null);

        }

    }

}

-----------------------------------------------------------------------------------------------------------------------

Hey Don’t Be afraid of that large code

It requires two line explanation

Here the code is saying ,

“Please Connect me to given URL (IP address) with some attributes I am telling you”

Here is the one line code

Let previous code class name is HttpConection.

java.net.URLConnection connection=null;

Httpconnection createconnection = new HttpConnection();

Connection =  createConnection. getHttpConnection(pass Ip address as string);

Now connection is established , all we need the stream to write or read.

(imagine u have telephone wire till your home but your home telephone is not working)

Suppose you want to send some data / object here to server , u need an object output stream to create and using that you can send.

(equivalent to calling someone and saying hello first)

ObjectOutputStream out=null;

 out = new ObjectOutputStream(connection.getOutputStream());

 out.writeObject("Ping");

  out.flush();

  out.close();

Now we send our object ( remember String is also an object)

Now one side part is done..

It is upto servlet how does it handle

If u want to handle then have a look :

        ObjectInputStream ois = new ObjectInputStream(request.getInputStream());

        try {

            String receive = (String) ois.readObject();

            System.out.println("received: " + receive);

            System.out.println("-----------------------");

        } catch (ClassNotFoundException ex) {

            Logger.getLogger(fetchFromDataBase.class.getName()).log(Level.SEVERE, null, ex);

        }

        ois.close();

Now suppose servlet make some processing and want to send back data to client

Simple my dear , same concept

Use output stream , Don't worry i won't say you to write ..

ObjectOutputStream objectOutputStream = new ObjectOutputStream(response.getOutputStream());

 objectOutputStream.writeObject( object to write);

            objectOutputStream.flush();

            objectOutputStream.close();

Now same thing data is available at client side

What are you thinking (use input stream)

ObjectInputStream ois = new ObjectInputStream(connection.getInputStream());

            Data result = (Data)ois.readObject();

    ois.close();

(Data is the type of object we send from servlet , Hey it is not as easy as you are thinking now, there are some precautions )

    Object class must be same on both sides (client and server).
    If possible copy from one side to other, don’t show your art between.
    Caution : package name of the class must be same  in both sides.
    Cast every time you are retrieving object eg.
    Data dataobject = (Data) inputStream.readobject();

                                                 ..eNjOy..



you can download ppt from here :

http://www.mediafire.com/download.php?16ctcya6sfnysw6