Tuesday 28 August 2012

Top 10 Tricks To Fool Your Java Professor

Trick #2

This week's trick will teach you how to find loopholes in existing programs for this you need to have deep understanding about how the underlying code works and how the Platform on which the code is running works.

Let me explain you this with an help of an example:-

Let us consider the simple and very basic example, our challenge is to write code which will tell us whether the given number is odd or not, so lets give a name to this program
ODD OR NOT
when given this challenge most people write this code:

If one can catch the flaw in this code then h/she is a Java Expert


public class OddOrNot
{
 static boolean isOdd(int no){
  return (no % 2) == 1;
 }
 public static void main(String[] arge){
  System.out.println(isOdd(7));
 }
}

Sadly if you are not the one, then i suggest you to read further


There are 2 flaw's in this code 
  1. Performance penalty (Mod operations are always less preferable)
  2. Code fails as soon as you pass a negative odd number 
Now you know the flaw, then you should be keen to know what best solution can be written for this type of challenges, stay connected....


why code fails ?
This is because, the java's truncating integer division operator[JLS 15.17.2], it implies that when the remainder operation returns a non zero result, it has the same sign as its left operand.  

So now you know the hidden flaw of the above written code, yes it return -1 as soon as you enter any negative odd number.

So, What is the best way to solve this challenge?
USE Bit-Wise-And (&), If you can use bit-wise-and (&) instead of mod (%) operation then always prefer bit-wise-and (&) operation, to increase performance of your application.

public class OddOrNot
{
  static boolean isOdd( int no ){
   return ( no & 1 ) == 1;
  }
  public static void main( String[] arge ){
   System.out.println( isOdd( -7 ) );
  }
}

Working
 If you convert any odd decimal number to its binary equivalent than you will get answer as pattern xxx1 i.e. any odd number ends with 1 and any even number ends with 0 so when we do 1 & 1 = 1 and when we do 0 & 1 = 0


This time you have learned another technique to impress your Boss, friends, professor etc.

Wait for the next trick #3
happy coding

Sunday 26 August 2012

Understanding java.io.StreamCorruptedException: invalid type code: AC

We can transport Objects in Java in two ways

  1. Using Serialization 
  2. Using RMI ( Remote Method Invocation ) 
last night i was using 1st approach to transport Objects from my server to client, while doing so my code throws 
java.io.StreamCorruptedException: invalid type code: AC

Lets see first what Javadoc has to say about this 
StreamCorruptedException :-  Thrown when control information that was read from an object stream violates internal consistency checks.
 Do you understand any thing ???

No ???

Then, continue reading ...

 So lets look at this exception closely 


This exception (java.io.StreamCorruptedException: invalid type code: AC) only occurs when any one use's a new ObjectOutputStream to write to an existing ObjectInputStream that you have already used a prior ObjectOutputStream to write to. These streams have headers which are written and read by the respective constructors, so if you start another ObjectOutputStream you will write a new header, which starts with - guess what? - 0xAC, and the existing ObjectInputStream isn't expecting another header at this point so it barfs.

So now I guess you have enough understanding about this Exception and next time you will not commit this mistake, and hence this will escape you from wasting enormous amount of time figuring out why this exception is thrown

So the bottom line is

  1. Always use only one ObjectOutputStream & corresponding ObjectInputStream through out the life of Socket
  2. If you are writing data over Socket using ObjectOutputStream then read that data only using  ObjectInputStream otherwise Exception could be thrown
  3. If you want to forget about what you have written then do 
    objectOutputStream.reset();
    


Wednesday 22 August 2012

Top 10 Tricks To Fool Your Java Professor

Trick #1



  1. Is your java professor always yells at you ? 
  2. Does he/she always tells you that you don't know anything about Java ?

If the answer is yes then this post is for you

Its Payback time


Next time when you meet your professor in viva or in general ask him/her a simple question 

Q. can you show me a simple program which print a NUMBER 0123 ?

if your professor is smart enough he/she will write this code 

System.out.println(123);

and gives you a explanation about why he/she has not written 0 (zero) 

if your professor in dumb (which 80% are) will end up with this code


System.out.println(0123);
So, when he will execute this code he will get output as 83
CONFUSED ???

This is because if any number is padded with initial 0 then that number is treated as Octal in Java so when you execute above code the JVM will convert the Octal to Decimal and print 83 on stdout.

So when you will explain this to your professor without the help of Google then he will be impressed :)

The problem is that most people just learn the syntax of a language and not its capability, learning syntax is very easy any moron can learn it within a month or so but learning capability takes almost years of expertise.

Wait for the next trick #2
till that time
stay hungry stay foolish

Monday 20 August 2012

IO-Utilities

Whenever I take any new project, I always require my Utilities library which provides me following features:

  1. Copying my library from dependency to  C Drive or  user's home directory in windows or *nix systems
  2. Compressing/Decompressing any Images or files for uploading or transferring it over network
  3. Getting extension of any file name in faster way
All this features can be achieved using just one library, and using this library is dam easy...even you can attach a listener to listen the processing i.e.
  • Name, count, size, compression level, copying from & copying to path of the file which library is processing ..

To attach a listener use this code



import fileutilslibrary.CopyEvent;
import fileutilslibrary.FileUtils;
import fileutilslibrary.Listener;
import fileutilslibrary.ZipEvent;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Naved Momin<naved.spartans.rocks75@gmail.com>
 */
public class Demo2 implements Listener{

    void start( ) throws IOException{
        FileUtils.getInstance().addListener(this);
     
        FileUtils.zipMyFolder(new File("C:\\Users\\Admin\\Desktop\\imgToVideo/RemoteDesktop"),
                  new File("C:/Users/Admin/Desktop/HMS Latest/RDnew.zip"),9);
                 

     
    }
    public static void main(String[] args) {
 
        try {
            // TODO code application logic here
            new Demo2().start();
        } catch (IOException ex) {
            Logger.getLogger(Demo2.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void copyListener(CopyEvent e) {
        //notification about copying event
    }

    @Override
    public void zipListener(ZipEvent e) {
        //notification about zip event
        System.out.println( "name " +e.getZipingFileName() +  "\n" + "size " + e.getZipingFileSize() + "\n" +
        " count " + e.getFileCount( ) + "\n" +
        "level  " + e.getCompressionLevel() );
    }
}

Various Methods:-


Copy a Directory


FileUtils.copyDirectory(src, dest);

Copy a File


FileUtils.copyFile(src, dest);

Zip Directory 


FileUtils.zipMyFolder(src, dest);

Zip Directory With Custom Compression Level


FileUtils.zipMyFolder(src, dest, compressionLevel);

Note: Compression level must be between 0-9, by default 0 is used

Zip File


FileUtils.zipMyFile(src, dest);

Zip File With Custom Compression Level


FileUtils.zipMyFile(src, dest, compressionLevel);

Note: Compression level must be between 0-9, by default 0 is used

UnZip File


FileUtils.doUnZip(src, dest);

Get File Extension (10x faster)


FileUtils.getExtension(path);

Reverse a String


FileUtils.reverse(str);

Get File Name 


FileUtils.getName(pathToFile);


Note: The library is written in pure Java code except the Wallpaper class which throws NotSupportedOSException if OS is not supported by the library for more information see Javadoc included in the download package.
This library is totally compatible with various 3rd party zip utilities like winrar, which means you can zip your files programmatically and still use winrar for unzip'ing the file or vice-versa is also possible. 

For any bug or suggestions mail me at naved.spartans.rocks75@gmail.com

This Library is License under GNU General Public License

Download latest builds





Friday 17 August 2012

Take Away ( Free Of Cost )

This week on take away i m giving away a software which i had sole'd to 4 peoples, 1 last year and 3 this year as a final year project (diploma),  The software performs following functions

  1. Encrypt any of your .png or .jpg files with AES (  Advanced Encryption Standard  )
Last year when i sole'd this project that guy asked me a smart question 
What if there is a spyware running on my computer which is capturing all my input or keystroke's ?
 So to solve this problem i have added a layer called second factor of authentication which is

SOMETHING YOU HAVE

now the software can defeat any keylogger's (remember keylogger's have types)

  1. The ones which only capture your keystokes
  2. another one is a bit advance and apart form capturing keystroke's they also capture your screen
So now even though that spyware software has your secret key which you have used to encrypt your image's, he/she will not be able to decrypt it until he/she has your "TOKEN"

TOKEN can be any thing your pen-drive, external hdd, or whatever which you can plug into system and prove that you are the one which actually encrypted the images, unless & until token has not been inserted the software will not perform decryption process.


So i m giving away the simple version of this software which only encrypts and decrypts without defeating keylogger's .
if you want the more advance version of this software then mail me at naved.spartans.rocks75@gmail.com

Always download latest builds

Thursday 16 August 2012

NTSystem VS System.getProperty("user.name")

Yesterday i was reviewing my friends code, In that i found a class called NTSystem my friend was actually using this class because of this method
public String getName(); //This method gets you the current logged in user
I asked him do you think this application will work in Linux and he replied yes of course then i smiled and said try it out he tried and call me this morning and said the application is throwing
ClassNotFoundException 

why so ?


Thing is that Beginners don't understand the working, they just somehow learn (in chalega ..chalega style) or copy the code from internet the things to know is, though Java is machine independent JVM is not .
JVM is exclusive made for each OS. 

Thats why when you use NTSystem class in windows it works like a charm but the code throws an Exception when you run it on some other OS just because the JVM don't know what NTSystem is !

If you had download the JDK for Linux, there you will not find the NTSystem class.

So the bottom line is if you want to get the current logged in user in Java always use 
System.getProperty("user.name");
This Method has 2 benefits

  1. Your code will be machine independent
  2. You will get the current logged in user 



Saturday 11 August 2012

Programatically setting wallpaper


Last week when i was doing random visit at forums I found a Question 
How to Programatically set wallpaper in windows" so i have written a code to solve this problem of that guy..... 
Setting wallpaper in windows is never this easy, all you need is my API to set & get wallpaper, this library is part of my Utilities framework and written in Java. After you have set my library in your classpath (For those who don't know how to set classpath), all you have to do is follow the below instructions


Things you should know before using this API



In windows platform when we set any image as a wallpaper, windows actually copy the image into directory "C:\Users\[username]\AppData\Roaming\Microsoft\Windows\Themes" and name it as "TranscodedWallpaper". So when ever you set any wallpaper try browsing this directory and see the result. If you haven't understand this no problem!
Go ahead and try the API you will understand the working...

  • To set wallpaper in windows just use this code 
new Wallpaper().setWallpaper( Path );
  • To get current wallpaper's path use this code
new Wallpaper().getWallpaper();

Current version 1.0 is for Windows only.

Note: Always download latest builds.