Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Java md5 hash

For uni I wrote a little program that implements a sort of md5 hash. Just a 10 min program but quite nice and useful I would hope. It takes in a file and outputs the md5 sum and the file name. Used this to compare files on a computer with the version on a server. There must be better versions out there but it works

/*
* See
* http://java.sun.com/j2se/1.4.2/docs/api/java/security/MessageDigest.html
* Basically a wrapper for the sun class
*/

import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.util.Scanner;

public class mdFive {

/**
* This function is passed a File name and it returns a md5 hash of
* this file.
* !!!! MADE STATIC SO I HAVE ONE FILE !!!!!
* !!!! NEVER DO THIS PLEASE REMOVE !!!!!
* @param FileToMd5
* @return The md5 string
*/
public static String md5File(String FileToMd5){
String outPutString = new String();
try {
MessageDigest algoToCrypt = MessageDigest.getInstance("MD5");
Scanner fileToCrypt = new Scanner(new File(FileToMd5));
/* Just to be on the safe side */
byte[] fileBuffer = null;
while( fileToCrypt.hasNextByte()){
algoToCrypt.update(fileBuffer, 0, fileToCrypt.nextByte());
}
/* Int would be to small and apparentelly you have to use a sign and magnitude */
BigInteger bigInt = new BigInteger(1, algoToCrypt.digest());
outPutString = bigInt.toString(16);
fileToCrypt.close();
} catch (Exception e) {
/* Not a big enough error to exit but still should tell someone */
System.err.println("Error while creating MD5 sum");
}
return outPutString;
}

/**
* The main programm
* @param args The arguments from the command line
*/
public static void main(String[] args) {
if(args.length == 0){
System.out.println("A MD5 Hascher \nUsage java mdFive ");
}else{
System.out.println( md5File(args[0]) + " , " + args[0]);
}
}
}

Why we love java

Edd, Dave and Me just spend 2 hours figuring out how the java.util.Scanner class works. This was based on this little example
 1    public static void main(String[] args) {
2 Scanner sc = new Scanner(System.in);
3 System.out.println("1: ");
4 String l1 = sc.nextLine();
5 System.out.println("2: ");
6 int l2 = sc.nextInt();
7 System.out.println("3: ");
8 String l3 = sc.nextLine();
9 }
What would you expect this to do? Like everyone with some sort of logical thinking mind you would assume that this would ask you for some sort of a String which you terminate with Enter then for a number with again you terminate with Enter and then another String. Run it and have a look. You will be amazed. It never asks you for the '3:' value? So why is this? Because if you call nextLine it will still leave some stuff in the buffer. This is then not returned by nextInt() as it is a String. So you are prompted to insert a int. But when it comes to the third read it will notice it still has something in it's buffer and return that. Even if there is nothing
System.out.println("_" + l3 + "_");
will open your eyes. You have to love the bad design of the Java libraries. We had something similar in ruby where we passed in a String that was not chomped to exists?
File.exists?("temp.txt\n")
Another thing that caught us out in the scanner class is the hasNext. From the java source code of public boolean hasNext()
...
if (hasTokenInBuffer())
return revertState(true);
readInput();
...
So if there is something in the buffer return if not wait for input. That is really what you expect from this. I can see my self testing if there is something in the buffer with hasNext(). As this is what every sensible person would assume. But no, the people at Sun see this different. So what do we learn from this?
=> Before anything look at the api documentation as there is no standard here and you will read

* Returns true if this scanner has another token in its input.
* This method may block while waiting for input to scan.
* The scanner does not advance past any input.

Why there are two kinds of programmers

Nowadays Java is taught in most universities. After talking to many young programmers at work and reading this article on how to recognise a good programmer I have realised that you can’t call everyone a "programmer" anymore. You have to differentiate between people that program and people that know how to use libraries. At my work, people who only know Java and call them self computing professionals are laughed at (The story of an A student that didn’t know what a call stack was, is still told). This is due to the fact that if you write Java programs you actually only import the needed library and then use them. So when you learn Java you surely learn how the Object Oriented model works but that is about it. This is not specific to Java. If you look at Python, Perl or Ruby you can always see that all the low level stuff is already done for you. Just take the classic example of a linked list. I was talking to a German Computing student about the performance of a hash map to a linked list. It turned out he knew the concept but he had never programmed one before. He argued that nowadays programmers don’t have to know this because libraries will give this functionality to you. I don’t want to say that this is good or bad, but surly someone who doesn’t understand how pointers work will write different programs than someone who does. Maybe it is just a different approach. I learnt C way before any high level language. And even in Pascal I embedded Assembly to support my mouse. So I learnt programming from the bottom -> up. From low level (Assembly) to high level (Ruby). But library programmers will have to learn top to bottom, if they ever want/have to do something low level. So in short:

Library Programmers
  • Know very well how to use specific libraries for specific programming languages

  • Don’t really care too much about memory / CPU performance

  • “Get the job done” attitude

Low Programmers
  • Understand pointers (had the “pointer moment” as I call it)

  • Care, maybe too much, about performance

  • Care about writing “nice” programs


I still personally think that a bottom -> up approach will give you a more solid understanding of the high level languages.
I am starting to understand that programming is not about people that started with Pascal or Basic when they were nine. Programming has become a career choice. People are now studying computing because they think they can get a well paid laid back job afterwards. Of course this is annoying us passionate programmers that spent their childhood learning how to write slim quick code, because these are our values.
So if someone comes up to you and sais “I am a programmer, but I only know Java” Don’t condemn him right away. He is just a library programmer, if this is good or bad time will show.

Eclipse fu*king sweet feature

For Java programming I use eclipse because of laziness. Now I tripped over a really nice feature. If you press the key and hover over a method it becomes underlined by a little blue line. I normally used this to jump around in my own classes. Just now by accident I clicked on the String.concat method and eclipse showed me the source of java.lang.String. So I could actually read what the String class does. This is really sweet as through this you can actually learn how Java works.
Well done eclipse.
I have been trying eclipse with c{\ and,++} but it really couldn't convince me there. But Java and eclipse just work so nicely.

Buy the way, i tried NetBeans (6.0.1) and it is still utter crap.
bash-3.00$ strace -p 2564
Process 2564 attached - interrupt to quit
[ Process PID=2564 runs in 32 bit mode. ]
futex(0xf7fc9be8, FUTEX_WAIT, 2565, NULL

Math.random() really quite good

I am just writing some stuff in Java and I had to be shure that Math.random() was quite random. You never know with thees random methods. So here some gnuplot output of 200000 and 20000 runs.



And here is a little program where you can creatre a random String or StringBuffer with just characters.


 1 public class helloworld {
2
3 /**
4 * Just runs the method. If a arg is given with that if not with 16 chars
5 */
6 public static void main(String[] args) {
7 System.out.println(getRand((args.length > 0)
4 ? (Integer.parseInt(args[0])) : 16));
9 }
10
11 /**
12 * Return a random string
13 *
14 * @param how long the string should be
15 * @return the string could be a StringBuffer for performace
16 */
17 public static String getRand(int howLong){
18 /* Use string buffer as String+= is very slow */
19 /* Read Effective Java by Bloch, Josh*/
20 StringBuffer returnBuffer = new StringBuffer();
21 for (int i = 0; i < howLong ; i++) {
22 returnBuffer.append ((char) (Math.random() * 26 + 'a'));
23 }
24 return returnBuffer.toString();
25 }
26 }
27


Code coloring and highlighting done with http://alexonasp.net/codehighlighter/Default.aspx

doxygen => fu** javadoc

I am just looking at some tool for documenting a little C++ project I am doing. (A C++ wrapper for curl will be up shortly). And I had a look at doxgen. And it is brilliant. There is a little GUI tool called doxywizard that will generate the config file that you then can feed into doxygen. It is possible to create HTML, Latex, man, rtf and XML with little in line graphics and so on(Call graphs, Class diagrams, ...). I am loving it. Having used javadoc previously this is so much nicer and more configurable. And it can format the source code nicely so clicking on the function name can take you to the actual code, what I consider brilliant for open source projects. So have a look at it especially if you are using JavaDoc.

Jad the Java decompiler

I have been looking at how the Java class file is built and astonished how easy it is one great tool for decompiling java is jad. With knowing the JVM instructions you can really see what the java is trying to do. I found out loads of stuff about the internals of the JVM. A little example.

public class TextClass extends Object{

public TextClass(){
super();
}


public static void main(String[] args)
{
System.out.println("HEllO WORLD");
}
}
is identicall to

public class TextClass
{
public static void main(String[] args)
{
System.out.println("HEllO WORLD");
}
}

Java just adds all that stuff. Here is the decompiled class file

import java.io.PrintStream;

public class TextClass
{

public TextClass()
{
// 0 0:aload_0
// 1 1:invokespecial #8 Method void Object()
// 2 4:return
}
public static void main(String args[])
{
// 0 0:getstatic #16 Field PrintStream System.out
// 1 3:ldc1 #22 String "HEllO WORLD"
// 2 5:invokevirtual #24 Method void PrintStream.println(String)
// 3 8:return
}
}


You can find out loads of interresting stuff through this. Have a try :)

Java and Url in the Code

Hey, a nother funny fact about java
How thinks the code below will compile?

public static void main(String[] args)
{
http://www.ribalba.de/
System.out.println("Hello World");
}
It does. This is due to the : and the //
In Java you can have a label so the goto can work. This is defined through the : everything after this is seen as a comment because of the //
=> So you can post urls in your code where you want and javac will just ignore them

Java quicker than C++

Ok everyone thinks java is a slow bastar**. But how do you explain this:

didi@alpha ~/speedTest $ time java SpeedTest
Finisched with 2000000000 loops
real 0m16.606s
user 0m16.233s
sys 0m0.264s

didi@alpha ~/speedTest $ time ./speed
Finisched with 2000000000 loops
real 2m7.950s
user 2m6.292s
sys 0m0.180s


Here are the programms:

The c++ one
 1: 
2: #include iostream
3:
4: class MathObject {
5: public:
6: MathObject(){}
7: };
8:
9: int main()
10: {
11: for(int i=0; i < 2000000000 ;++i){
12: MathObject *mathObject = new MathObject();
13: delete mathObject;
14: }
15:
16: std::cout << "Finisched with 2000000000 loops" << std::endl;
17: return 0;
18: }


The Jave one
 1: public class MathObject
2: {
3: public MathObject(){}
4: }
5:
6: public class SpeedTest
7: {
8: public static void main(String[] args)
9: {
10: for(int i=0; i < 2000000000 ;++i){
11: MathObject mathObject = new MathObject();
12: mathObject = null;
13: }
14: System.out.println("Finisched with 2000000000 loops");
15: }
16: }


I assume, this is because the java jvm can only change a pointer for the new Obj but c++ has to scan through the heep to find a new memory address and becomes so much slower through doing so. So java is faster at some stuff.

Download the files under : http://www.ribalba.de/speedTest.zip