Showing posts with label simple code. Show all posts
Showing posts with label simple code. Show all posts

16 October, 2015

Java Programming Tutorial - Unit 2 - Methods and Variables

Let's start from where Unit 1 left off.  During the first steps, we instructed our computer to write "Hello World!" to the display.  Through that unit, we went through quite some material, despite it being so simple.  In this unit, we'll cover more practical points rather than theoretical ones, so get ready to write some more code this time!

Variables

So, what is a variable?  As the name clearly indicates, it is something that varies.  A variable is just a label which you can use to store something.  Let's say we want to store our user's name, we create a new label named username and assign the user's input to this label.  A user types in their name and we instruct the computer to store the input somewhere which can be addressed using the word "username".

To better understand and appreciate how useful that little label is, try imagining having hundreds of such variables all without a human-friendly name.  You d not need to go far, older languages had no such concept and used exclusively memory addresses.

With this knowledge, you can now think of your computer's memory as being a large room full of P.O. Boxes.  Each P.O. Box may be referred to by its number.  In modern languages you can give each P.O. Box its own unique name too, so it's easier for you to know what you're working with.

The next bit is theoretical, however its good to know about variable terminology.
Java is known as being strongly-typed.  This strongly named description simply means that each variable can have one type, and one type only.  If we declared our username variable as being of type text, it can only contain text.  If we had another one for storing a number, it can only store a number.  It's a restriction, but it's convenient.  There are language that have variables whose types change during runtime, or weakly-typed.  It's convenient too, but its easier to shoot yourself in the foot if you're new to it.

Let's make use of a variable in a more practical example.  In this task, we want our text to be defined as a variable, rather than passing a direct value to System.out.println.



As you can see, the change is minor.  In the new line, the only thing which may be new is the String label.  A String is simply a series of characters; it is a type of variable which you'll find in the vast majority of programming languages.

Variable types

Now that you have declared your first variable, and hopefully got to understand the relation between the type of the variable and the content it stores, it is safe to introduce the list of primitive types in Java.  As you now know, Java is object oriented and everything is defined as a class.  This implies that every instance in our program is an object.  However, this is not entirely true, since objects need to be made up of something.  If we keep going deeper into what constitutes and object, we find that there are only 8 primitive types.  Each primitive type is made up of some number of bits.  These are as follows; afterwards we'll go through them:

  • boolean - no specific number of bits, but practically 1
  • byte - 8 bits
  • char - 16 bits
  • short - 16 bits
  • integer - 32 bits
  • long - 64 bits
  • float - 32 bits
  • double - 64 bits
As you can see (assuming you're familiar with bits, the basic units of information), all types are practically increasing sizes of numbers.  No letters, no images, nothing but numbers.  Later I'll explain how everything can be made from these primitives, but first let's see how we can organise them into roughly three categories.

First we have the boolean type.  This can have just two values, 1 or 0.  Effectively we use true or false in Java, and is mostly used for setting states and flags.

Next come the natural numbers.  All primitives from the byte to the long can fall under this category.  Values stored by these types cannot have any values after the decimal point.  One thing to note about the char type is that it does store a numeric value, however it is treated as a character.  Note also that it is a 16-bit unicode.

Finally we have the real numbers; the float and double.  Double, as the name implies, is just double the size of a float.  It is usually much more practical to work with a double unless you're working on a high performance system where memory is precious (not all systems have gigabytes of memory to waste).

Primitive types can be easily declared or have a value assigned to them.  If you want an integer with a value of 10, simply enter:

int myNumber = 10;


Composites

Now that you have the most granular types, it is possible to mix and match to create more complex types.  A composite is basically another name for an object.  The String type, for example, is a composite.  In order to explain this composite, we need to introduce another programming term; arrays.  An array is just a contiguous series of memory cells, each containing a value of the same type.  Java has native support for arrays supports defining new arrays during runtime (older languages did not support this directly).  The next snippet shows how we can use an array of characters to emulate a String, albeit in a less practical way.




Unlike primitives, composites, or the proper name, objects, are created using the new keyword.  The declaration also follows this convention:
Type myTypeVariable = new Type();

As you can see, there is the type, the name, followed by the assignment to a new instance of the class (or type).  Note though, that the String is an exceptional case in Java and can be declared like a primitive.  This is only an exception and does not apply to any other class.

Probably the String is not enough, so let's go through some more examples.  Let's say we want to show a picture.  What constitutes a picture?  Pixels, the number of pixels in width, and in height.  Width and height are just numbers.  The pixels are an array of the Pixel object (so we also have nested composites).  And after that, what is in each pixel?  Three values for the primitive colours Red, Green and Blue;  again, three numbers.

Let's define our own Picture type.  First, we need a Pixel.  Then we'll create a Picture and we'll find its area.  Using this area, we'll set the value of the pixels in our Picture, since initially this is null.




Now we'll create the program "body".  The main class this time will create the image, the pixel array, and print out the area.  Note how we concatenated the text and a variable using the '+' symbol.  I'll explain the operators later on in this unit.



So you see, pretty much anything can be reduced to a number.

Operators

As I mentioned earlier, I'll give an introduction to operators.  These are not so complex so there is not much else to learn about them.

Operators are the symbols used in code, such as the '+', '-', etc.  The plus can be used for concatenating anything.  For example, let's say we have variables a and b.  a + b could mean the following:
If a and b are primitive, the result is a primitive.  If any of a or b is not a primitive, the result is always a String representation.

Other operators are only reserved for primitives:
  • The minus '-' used to subract;
  • The star '*' is used to multiply;
  • The slash '/' is to divide.  The value is rounded if not of types float or double;
  • The percent '%' used for obtaining the modulo;
  • The hat '^' is used for bitwise XOR;
  • The pipe '|' is used for bitwise OR;
  • The ampersand '&' is used for bitwise AND;
  • The exclamation mark '!' is used for NOT;
  • The greater than '>' and less than '<', for...well greater or less than;
  • The double greater and less than ('<<' and '>>') for bit shifting;
You shall not be using many of these in the early days.  However you should be familiar with the computing terms used here (such as shifting and bitwise operations).

Methods

We mentioned something about methods during the first unit, mostly trying to relate them to the methods in your recipe books.  This time, we shall add more methods to our little picture program.  At first it might seem like overkill to have too many methods for a simple task, but as your project grows you'll come to appreciate shorter and more frequent methods.

So, the first task - adding new methods.  But why, what are they going to do?  Imagine we want our program to accept a user input.  For this task, we'll use methods that were written by others - we'll be calling those methods.  Afterwards we'll break up our program into smaller methods so that later on we can follow better programming practice.  In this case we'll write our own methods too.

The program

Our next task will be to add on to the Hello World Picture program.  This time the area will be calculated by the picture, rather than us having to calculate it in our main program.  We'll also let the user specify the width and height of the picture.  This user input will need some processing, as we shall see next.

First, we'll extend the Picture class so that it can support its own methods.  We shall call this PictureExtended to avoid confusion for now.



Next we'll upgrade the main program.  As you can see, it has many more methods and the functionality is more granular.  If we had two pictures for example, we could still call the same createPicture, thus avoiding duplicate code.



Static vs not static

Note how we put static in front of methods in the main class, while we did not put any in the PictureExtended.  Now that we do have some methods and classes, it is safe to explain it.

Static methods are those methods that can be called without having an instance of the enclosing class.  For example, we never declare a new System or Stream class, but we call println on  System.out variable (which is of type Stream).  This is because it is declared static.  However, we cannot call getArea() on PictureExtended by itself.  We must have a new PictureExtended and place it in a variable.  We are then able to call it from the variable.

This is basically the difference between static and non-static; if it is static, it can be called without an instance of the enclosing class;  However, it cannot access the non-static members of the class.  Let's say we make the getArea() static, in that case, we cannot access the width and height values of the PictureExtended instance.

Accepting user input

We are able to accept user input via the Scanner class.  Again, this is just like System, a class already provided with Java (although we had to create a new Scanner, unlike System).  Note how we passed System.in to it, telling it that we expect to receive input from the standard system input; the keyboard.

The difference from System is that Scanner resides in what is known as a package which is different from ours.  We will go through packages in a later Unit, however note how we needed to import the class.  The import statement has to be at the very top, outside the class declaration.

Conclusion 

This was quite a long unit and covers quite a lot.  We created new classes, instances of these classes, or objects, static methods and imported some other ones too.  In the next units we shall go over further interesting bits of programming in Java, such as loops, cases and conditionals.

Other tutorials (which are just as good or better) may hold off explaining the details of classes and objects initially.  I believe that this might send off the wrong message about Java.  It is understandable that it is initially complicated, however it will embed the idea that in Java one should follow an object oriented methodology, otherwise the code will not be up to standard.  Not that it is incorrect, but as projects grow, not following conventions will make Java very frustrating.

So, as a precaution, I'm giving out fairly detailed descriptions of why classes and objects before going further into the traditional loops and conditionals.  Hopefully the descriptions coupled with the actual code will make it more natural.

Thank you!

10 October, 2015

Java Programming Tutorial - Unit 1 - Hello World!

You've probably already seen this little "hello, world" thing somewhere on the Internet.  It is the most popular phrase to write to the display when learning a new programming language and has been around since the 70's.

Before we start heading into the development part of this unit, we shall install what is known as the Java Development Kit (JDK).  The JDK is an excellent set of of tools that includes compilers, runtimes, libraries - a lot of tools and buzzwords.  It's enough to know that it is necessary if you plan on programming in Java.

Installing the JDK

A explained in Unit 0, the JDK is compiled for every platform and architecture.  As a result, you'll have to select the JDK for your system.  I would assume you are running Windows, but I'll also consider Linux.  If this is already too much, just follow the steps which I label as for Windows (although I'd suggest you read up a bit on Operating Systems and general computing before proceeding).

Pre-flight checks

Before you go through a 100MB+ download, make sure you do not have a JDK installation already.  To check if you do, follow these steps:

On Window (or if you're unsure) press the Windows key (the flag icon on your keyboard) and R simultaneously.  The run dialog will open up and in it type cmd, which will open the console.  On Linux or UNIX systems, open the terminal as specified in your distribution (I expect you know this by now).

In your console (whether it is Windows or Linux), enter javac -version.  This is the command for the Java Compiler, so no there are no typos there.  If you get some meaningful output (i.e. a version number such as javac 1.8.0_4), then you can skip this installation part.  If you get an error on the lines of "not found", then you'll need to install the JDK.

Downloading the JDK

Selecting and download the JDK


The JDK setup is trivial; download it, and install it.  That's all there's to it.  So first of all, head to Oracle's website and select your version.  If you're totally unsure, just select Windows x86.  In case you're simply not sure if your system is 32 or 64 bit, do the following (if you system was made less than 4 years ago it's probably 64 bit):

Windows
Windows architecture
  • Right-click on "Computer"
  • Select "Properties"
  • Under "System", the "System type" tells you whether it is 64 or 32 bit (refer to image). 






Linux/UNIX
  • Open terminal;
  • Type uname -i
  • If it is i586, i686, or any 86, then it's 32 bit.  If it's 64 bit you'll get x64.
  

A note on Ubuntu and its derivatives

If you're working on a Ubuntu (or Mint, elementary or other derivatives) an excellent and very short guide can be found on webupd8.  I suggest following that guide for JDK on Ubuntu.

GUI Installation

Once downloaded, it is only a matter of running it and clicking next, however this setup is unfortunately bundled with unwanted software too.  So before hitting next, make sure you uncheck any field that tells you to install toolbars or whatever.  These are absolutely unnecessary and are included only for marketing.

Installed 

Now that the JDK is set up we're ready to do some work.  Despite the elaborate system, the development kit is a very simple to install.  From the installation comment, "The Java Standard Edition Development Kit includes both the runtime environment (Java Virtual Machine, Java platform classes and supporting files) and development tools (compilers, debuggers, tool libraries and other tools)" so as you see, its a great platform to work with.

Make sure everything is fine by again running javac -version.  This should print out the version number of the Java compiler.

Hello, world!

Everything is now in place and all that remains is your first class!  First what?  Java is a pure object-oriented programming language (with brand new elements of functional features since Java 8).  These are a lot of buzzwords for now, so I'll keep it simple and then elaborate on these as we go along in the series.

For now suffice it to say that everything you do in Java in contained in what is known as a class.  If you're interested, read up on object oriented programming, but for the first few units we'll keep it low.

Our first program will look like the following.  I'll explain each line afterwards.

Comments

The first thing to note is the fairly natural language in this snippet.  This is the easiest concept to grasp.  Comments in code help make your code more understandable and easy to follow.  It is of utmost importance to document your code especially when your projects get larger.  One day you'll just leave it out and when you look at your code after a month you'll regret it - so it's better to get used to it right now.

Comments can be identified by being wrapped between /* and */ (a single star, I'll explain the double ones in the code too).  Alternatively, for a single line of code, it is enough to start it with //.  Java is adamant about standard and correct coding and documentation, so much so that a particular category of comments are know as JavaDocs.  

JavaDocs are basically the multi-line documentation blocks (those between /* and */) with a very small difference and requirement.  JavaDocs have an extra * after the opening /* and are to be written in specific areas. 

After defining the other basic parts of the code, I'll go into more details on JavaDoc.  For now, it is fine to understand that we can write normal text in our code to help us understand what is happening.  Note that the compiler will ignore your comments, so complaining in code is futile :P

Class

As explained earlier, everything in Java is defined as a class.  Classes are a blueprint for an object in an object oriented system.  For now, it is not that important however it is wise too keep this in mind.  

In our case, we have just one class named HelloWorld.  You may have noted the 'public' keyword.  This will make more sense later on, so for now think of it as a requirement for your program to compile.  

In Java the file must be named as the class, so our program here must be saved to a file named HelloWorld.java.  This 'limit' actually makes thing much simpler - you don't have to remember a bunch of names for the same program.

Method

Methods are where we define functionality.  Think of this as the method in your food recipe; it tells you how to put things together to get something done.  In an object oriented system, objects (which are instances of classes, I'll explain this soon) are made up of values and methods.  Methods operate on these values to return some other value.  This concept will be explored in the next unit, however it is important to note that these values are called variables.

But let's get back to methods.  In our case we have just one method, named main, and in it we explain what to do to print our "Hello World!".  In Java a method named main is the primary starting point of the program.  Think of programs as a water hose - the main method is the point at which the water starts flowing; the origin.  This main method, though, has some extra details which we will include but will be explained later on in the series.  As you can see, we started it again with public, followed by static and finally void.  It also has a String args[] in the brackets.  Let's dissect this declaration:
  • public static are keywords for the VM which will be explained later in the series
  • void is the return type.  Remember from the definition we said that methods work on variables to return a value.  In some cases, there is no value returned by the method after it runs.  In those cases we say that the method does not return a value, so the declared return type is void.  Return values, etc are not important for now, but I'm mentioning the terms so you can get used to such concepts in context.
  • main defines the name of method.  For now it is best to use unique names, however as we'll see later on, we can use duplicate names with some limits.  You'll use the name to call the method.
  • (String args[]) is defining the method as taking one parameter or argument.  Arguments are given to your method when it is called.  In the recipe book, think of it as the book instructing you to put 100g of flour in the bowl.  The 100g is a parameter to the method "put flour".  This defines context and extra information for the method to work on.  The method can access the parameter as if it were a variable.
System.out.println 
This might seem a bit complex but let's analyse it like we did for the main.  It is good to go over this again later on after we cover more topics, so you can better 'get it'.  It is OK and expected that you will not understand the specifics right away.  However, we shall go through the line:
  • System is a class, just like our very own HelloWorld.  This class is provided with Java, so we did not have to write it.  There are various methods and variables in this class.
  • out is a variable, or member, defined in the class System.  It is not important to know the specifics, but the name is indicative enough as pointing to the output of the program.  So up till now we accesses the output of our program from the System class.  Note that a variable can also be another class.  What you need to recall now is that a variable is an instance of a class (i.e. an object, whereas the class is the type of the variable).
  • println is, finally, a method inside the out class.  This is the one which does the writing, and as you can see, we gave it a parameter, which is the text to write.
As I said, try to get the idea, but for now we'll keep it very simple and it is enough to know that System.out.println("my text"); will print "my text" to the output.

Structure Summary

So let's wrap this up after which we'll compile and run our hello world!  

Recall that in Java everything is a class.  Each class defines methods and variables (we haven't used these yet).  Variables can be other classes too.  When we create an instance of the class (which we haven't yet neither), it is known as an object.

In our basic case, we have just one class named HelloWorld with a single method named main.  Here's the pattern now: the JVM is calling HelloWorld.main().  It does this behind the scenes and as you can see it is identical to the way in which we called System.out.println().  The pattern is <class><dot><method>.  It is possible and normal to have multiple classes in one call, such as the System.out.println, which has two classes.

Going back to the JavaDoc, you can now see how the @param args is referring to the parameter passed to main.  So what we are doing in JavaDoc is explain the use of each parameter in a method.  Note also how the JavaDoc blocks are explaining the building blocks; the classes and the methods that we define.

Again, it is not vital to know these details yet, however as we go along they will start making a lot more sense.

Compiling

Compilation is fairly straightforward in Java.  Let's go back again on this process as explained in Unit 0.  Compilation in Java converts our code into byte code.  We'll use javac to accomplish this, after which we will run it using the java command which will fire up a JVM to execute the byte code.

So, in order to compile, open up your console or terminal and navigate to the directory which contains your HelloWorld.java.  For example if it is at C:\Users\james\mycode, enter cd C:\Users\james\mycode.  The same goes for Linux and UNIX systems.

Once inside the directory, enter javac HelloWorld.java

This will not do much other than compile your code silently and that's it unless you have some compilation errors.  You should note a new file now, called HelloWorld.class.  This is not a source file now but an executable for running in the JVM.  That's all there's to compilation in Java, so now onto the best part of this unit - running the program.

Running

Running your program is even simpler than compiling it.  All you need to do, in the same directory where you have the HelloWorld.class, is enter java HelloWorld in your console.  Note that we do not add the .class extension.  We are running the class, not the file per se.

If everything went well, you should see your first code running perfectly on your system, shouting Hello World! at you!  Do not underestimate this simple code.  It's where almost everyone began.  It would be ideal to experiment a bit, that's the key for your success.  Note my explanations, but doing extra reading will help you grasp concepts which you may not have correctly understood in your first reading.

Conclusion

This is your first step in a very long and never ending journey.  Do not expect that a few years will go by and you'll be done learning.  Programming is a very active field and it is best to keep looking for new concepts, languages, methodology, etc.  But this is the vital first step.  

The code for this unit may be found on the github repository.

Soon I'll be putting up Unit 2, where we shall be going into variables and more methods.  Some text in this first hands-on unit may be disorientating for the absolute beginners, but do not give up.  In a few weeks you'll be much more proficient in Java!

    29 September, 2015

    Intelligent Input Processing

    Hello again after quite a long time!  Quite a lot has happened over the past few years, from starting and graduating from University, finding a job in another company and travelling around the world.  I have also been involved in some small side projects, some of which have actually gained some traction.

    One such project which I did some basic parts of is a a system for maintaining a list of classified vehicle listings for used (2nd hand) and new cars...or any other kind vehicle.  The interesting part is the way a new listing can be added with minimal effort.  Typically people *hate* filling long forms, and entering the details of a car is no exception.  Even if the form is actively trying to help the user by showing suggestions, it still is not as streamlined as just typing text or actually filling out a hand-written form.

    So here I found the thing I hated about forms - having to switch between inputs and having to think about the value I should enter next.  I don't want to think about it, I just want my form to fill up, by itself if possible.  A little experiment lead to the development of a small but quite helpful feature which tries to offload this (minor) effort from the user.

    As the data was a simple table, we could predict what the user is going to enter; some details on a car.  There aren't too many attributes when you think about it - a make and model, year, colour, engine and transmission.  You could also do away with some of them, even though it might hurt search rankings.  The result was that a form may be populated by simply parsing the semi-natural text taken from one big text box.  The user no longer had to enter different and specific values in each entry - just one descriptive sentence where order does not matter and mistakes may be easily fixed.  All we needed is some initial data to "teach" the system what to expect.

    We now have a very clean solution for entering listing details where a short description relieves us from having to think about each individual attribute of a car (what an epic case of 1st world problemism).

    By some luck, this little experiment has made it through to a website and is now available for many users to enjoy.  Let's hope these kinds of little experiments from professionals and enthusiasts keep getting better and more popular so one day we may have a more user-oriented internet, rather than a machine-oriented one.  Oh by the way, the website making use of this little tech is http://www.pickacarmalta.com!

    20 December, 2011

    Remote Desktop Viewer - The cheap way [Part 1]

    Microsoft RDP, RemoteFX, VNC.  That is the real stuff.  Solutions such as those will allow you to secure your connections, log you in to your desktop, compress the connection, etc.  But have you ever thought if it is possible to implement something rudimentary, totally in Java.  Actually it is possible.  But it's nothing much, and what I'll be doing here is a very, very basic implementation of an idea.  Obviously one can go on and enhance it, but it's almost totally impossible to produce a real solution, since Java does not have direct access to the OS, so for example you cannot remotely log-in, as you would for example using ssh.  Well it might be possible, but it would be an overkill.

    As I said, I will simply implement an idea, so even though I know we won't be building the next Remote Desktop protocol, it is still interesting.

    First we shall lay out some basic requirements.  Basically we will build a server and a client.  The server shall receive a request, it will then grab a screen shot, and send it back.  Meanwhile the client will wait for the server to reply with the image, and will then draw it.  This will go on until we disconnect.

    So create three packages first, com.jf.rd, com.jf.rd.client and com.jf.rd.server.  Obviously you can name them whatever you want, but ideally you should have xxx.xxx.client and .server.

    We'll start off with the server.  That way we can define what we expect from the client and what we intend to send back.

    Now, in the server package create the JRDServer class.


    package com.jf.rd.server;




    public class JRDServer
    {
    public static int PORT;

    public static String USER;
    public static String PASS;

    /**
    * Parameters:
    * Port, User, Password
    * @param args
    */
    public static void main(String[] args)
    {
    if (args.length < 3)
    {
    System.out.println("Usage: JRDServer Port User Password");
    System.exit(0);
    }

    PORT = Integer.parseInt(args[0]);
    USER = args[1];
    PASS = args[2];

    System.out.println("JRD Server sdtarted.  Will listen for connections on " +
    "port " + PORT);

    JRDServer server = new JRDServer();

    server.start();
    }

    private ConnectionListen listen;

    public JRDServer()
    {
    this.listen = new ConnectionListen(this);
    }

    public void start()
    {
    System.out.println("Service Thread starting...");
    listen.startServer();
    Thread srv = new Thread(listen);
    srv.start();
    }

    public void stop()
    {
    System.out.println("Service Thread stopping...");
    listen.stopServer();
    listen.destroy();
    }
    }


    This class is basically an entry point to the server.  I expect some basic Java knowledge so I will describe this only briefly.  We start the server by passing 3 arguments; the port to which we will bind, a username and a password.  The port is the real necessity, and as yet the user and password will not be really used, and will be there so that one day we can implement some sort of security.

    There are also the start and stop methods.  start will initialise a listener class which will be running on a separate thread.  That way we can serve our clients in a parallel fashion and also prevent any user from blocking us to the rest of the application in a manner which will stop us from stopping the server.

    stop simple stops the listener class and releases its resources.

    Next up is the listening class.  This class will loop while the server is running and every time a connection is requested, an other, separate thread is created and the client is served.


    package com.jf.rd.server;


    import java.io.IOException;
    import java.net.ServerSocket;


    public class ConnectionListen implements Runnable
    {
    private boolean running;
    private ServerSocket serv;

    public ConnectionListen(JRDServer server)
    {
    try
    {
    serv = new ServerSocket(JRDServer.PORT);
    }
    catch (IOException e) 
    {
    System.err.println("The ServerSocket could not be initialised.");
    System.err.println("Reason : " + e);
    }
    }

    public void startServer()
    {
    running = true;
    }

    public void stopServer()
    {
    running = false;
    }

    @Override
    public void run()
    {
    while (running)
    {
    try
    {
    Connection conn = new Connection(serv.accept());
    Thread tr = new Thread(conn);
    tr.start();
    }
    catch (IOException e) 
    {
    System.err.println("A connection could not be accepted.");
    System.err.println("Reason : " + e);
    }
    }
    }

    public void destroy()
    {
    try
    {
    serv.close();
    }
    catch (IOException e) 
    {
    System.err.println("The ServerSocket was not closed.");
    System.err.println("Reason : " + e);
    }
    }
    }


    This time, a server socket is passed as a variable to the constructor. This is the socket which will listen for and accept connections.  The run method, which is the implementation of the Runnable class is what will be running on a separate thread.  Therefore we can simply put a while loop and, kind of, forget about it, since it won't be blocking us (the main thread).  It shall keep on looping until the running flag is false.  So when we start the server we must set running to true and then start it.  To stop it - well - set it to false, and the looping will stop.

    Of course, if we won't be listening for any more connections, we should close the server socket.

    Finally, the Connection class is created.  Once this is done, the server is basically complete.  Now I should explain what will happen when this is actually run.  Any client that shall connect to this server will receive a byte stream resulting from a screenshot.  It is irrelevant if the client is a web browser, a mobile app or a simple socket.  Also, we won't be checking what the client is actually requesting, so as you can see, the username and password are irrelevant.   That means that you should either practice, and implement an authentication system (easily done) or simply avoid running this server if you fear someone might connect to it and, sort of, spy on you (aye, this is easier).

    So, to the connection class.

    package com.jf.rd.server;


    import java.awt.AlphaComposite;
    import java.awt.Dimension;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.Robot;
    import java.awt.Toolkit;
    import java.awt.image.BufferedImage;
    import java.io.BufferedInputStream;
    import java.io.InputStream;
    import java.io.PrintStream;
    import java.net.Socket;


    import javax.imageio.ImageIO;


    public class Connection implements Runnable
    {
    private static final int IMG_WIDTH  = 960;
    private static final int IMG_HEIGHT = 600;

    private Socket connSock;
    private static final int BUF_SIZE = 2048;
    static final byte[] EOL =
    { (byte) '\r', (byte) '\n' };
    private byte[] buf;


    public Connection(Socket connSock)
    {
    this.connSock = connSock;
    buf = new byte[BUF_SIZE];
    }


    @Override
    public void run()
    {
    try
    {
    InputStream is = new BufferedInputStream(connSock.getInputStream());
    PrintStream ps = new PrintStream(connSock.getOutputStream());


    for (int i = 0; i < BUF_SIZE; i++)
    buf[i] = 0;


    int nread = 0, r = 0;


    outerloop: while (nread < BUF_SIZE)
    {
    r = is.read(buf, nread, BUF_SIZE - nread);
    if (r == -1) return;
    int i = nread;
    nread += r;
    for (; i < nread; i++)
    {
    if (buf[i] == (byte) '\n' || buf[i] == (byte) '\r')
    break outerloop;
    }
    }


    System.out.println("Done reading.");


    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Rectangle screenRectangle = new Rectangle(screenSize);
    Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(screenRectangle);
    int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
    image = resizeImage(image, type);

    ImageIO.write(image, "JPG", connSock.getOutputStream());


    ps.flush();


    connSock.close();
    }
    catch (Exception e)
    {
    System.err.println("Error, somewhere...");
    e.printStackTrace();
    }
    }


    private static BufferedImage resizeImage(BufferedImage originalImage,
    int type)
    {
    BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
    g.dispose();
    g.setComposite(AlphaComposite.Src);
     
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.setRenderingHint(RenderingHints.KEY_RENDERING,
    RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
     
    return resizedImage;
    }


    }


    There it is then.  The Main screen grabber and sender.  We're not doing much here;  just receiving a request and then write "Done reading" when the process finishes, and then a picture is sent.  The resizeImage method is used to reduce the size of the image so that we do not send an image the size of your screen resolution.  That would be slow and besides, you can also specify what "resolution" you intend to receive.  The socket is also closed here, that's important too.  The lines between printing "done reading" and ImageIO.write are grabbing the screen using the AWT (Advanced Window Toolkit), so what this means is that you must have an OS that supports GUI (i.e. not headless, as it is known) and you must be logged in basically, since it grabs the screen as seen by the current user.  Therefore apart from the fact that we cannot remotely login, we also can't turn off the video card.  You can turn off the screen, obviously (lol).

    That was part one of this, erm, tutorial, or whatever it is.  I like doing these sort of mini programs when I am trying to solve other problems, that's why they are not at the bleeding edge of technology.  And then, when I'm done, I just write something about it, maybe someone out there learns something hehe.

    The next thing we'll do, is build a client application.  I currently plan on supporting only viewing, but eventually, we might spice it up a bit by adding cursor support so that you may click on the client and it will then be forwarded to the server and eventually consumed by the OS that is hosting the server.

    Also, the second part will probably come out either just before 2012, or probably in the first week of January, so until then, Merry Christmas and a Happy New Year! :D

    16 December, 2011

    Comparing two XML documents in Java

    How many times have you, for example, modified some XML file but wanted to make sure that only certain parts were changed?  Well it did occurred to me, a number of times.  Actually the problem is this:  I had a small application which modifies XML files in a graphical way and I wanted to ensure that nothing got messed up when I saved the file.  By "messed up" I mean tags changing their values or positions.

    So what I did was build a simple program which will take in two files (XML, naturally) and then map all the nodes and compare their paths and values.  Quite a simple task.


    So first, we'll start off with the usual Utilities class.  Static methods such as those reading a file should be placed here, ideally.


    package com.jf.xmlcomp.util;




    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.util.Scanner;


    import javax.xml.parsers.DocumentBuilderFactory;


    import org.w3c.dom.Document;


    public class Utils
    {
    public static String readStringFromFile(File file)
    {
    StringBuilder ds_text = new StringBuilder();
    String str_sep = System.getProperty("line.separator");
    try
    {
    Scanner ds_scan = new Scanner(new FileInputStream(file), "UTF-8");
    while (ds_scan.hasNextLine())
    ds_text.append(ds_scan.nextLine() + str_sep);
    ds_scan.close();
    }
    catch (Exception e) 
    {
    System.err.println(file.getPath() + " :: Not read");
    }

    return ds_text.toString();
    }

    public static Document stringToDocument(String str_doc)
    {
    Document ds_doc = null;
    try
    {
    ds_doc = DocumentBuilderFactory
    .newInstance()
    .newDocumentBuilder()
    .parse(new ByteArrayInputStream(str_doc.getBytes()));
    }
    catch (Exception e) 
    {
    System.err.println("String could not be converted to Document");
    }

    return ds_doc;
    }
    }


    We only have two simple methods here; one which reads in the contents of a file and one which converts an XML String to a W3C Document object.  I won't be detailing much about reading a file or converting a String as it is not the scope of this post.

    Next thing to do is create a very simple implementation of a Map, sort of.  Now those that actually know what a Map is will be frothing at their mouths, since what we will be doing is a simple ArrayList mapping and we won't even be using Generics, hashes or even collision tables.  The reason is that this is a simple post about creating a simple XML Comparator.

    So, to the SimpleMap thing...


    package com.jf.xmlcomp.util;


    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.Set;
    import java.util.TreeSet;


    public class SimpleMap
    {
    private ArrayList<String> keys;
    private ArrayList<String> values;


    public SimpleMap()
    {
    keys = new ArrayList<String>();
    values = new ArrayList<String>();
    }


    public void put(String s, String v)
    {
    keys.add(s);
    values.add(v);
    }


    public ArrayList<String> get(String k)
    {
    ArrayList<String> result = new ArrayList<String>();
    for (int c = 0; c < keys.size(); c++)
    if (keys.get(c).equals(k)) result.add(values.get(c));


    return result;
    }


    As you can see, we created the usual methods you'd find in a Map: the put and get.  The rest should be pretty easy; declaring the ArrayLists containing the keys and values and then initialising them in the constructor.

    The put method will simply add the new key and value Strings in the respective ArrayList while get, gets a little over-done.  In the get method we first set up a results ArrayList and then loop through the keys list and store every matching key.  The key won't be stored though, as they are of no use really; if you ask for door which is opened by a particular key, you will want to find a door.  So we get the index at which the key was found and then store the value found at the same index in the values list in the results list.  Finally the results list is returned.  Probably you now know that we can have the same key appearing more than once in this map.


    public ArrayList<String> keys()
    {
    return keys;
    }

    public ArrayList<String> getCompleteItemList()
    {
    ArrayList<String> res = new ArrayList<String>();
    for (String key : uniqueKeys())
    for (String val : get(key))
    res.add(key + " :: " + val);
    return res;
    }

    Following the mapping details are two other simple methods.  One simply returns the list of keys while the other will return all the items we have as a String of key :: value.  At first it might look like an over kill.  Getting only the unique keys only to loop over the values obtained by every key.  What happens if you use the normal key list and loop over it, is a repetitive amount of values.

    Let's say there are two keys named "a" and "b".  If we loop over the key list we get "a", "a", "b".  Now let's include the part which gets the values obtained from each key.  We will get two values for each key named "a", so eventually we'll end up with the values of a key named "a", twice.

    So to "fix" this, we will simple get each key once and then simply add the resulting values of each.  That way we can be totally sure that no key-value pair is repeated.

    Naturally we'll be needing the uniqueKeys method, so here it comes.




    public ArrayList<String> uniqueKeys()

    {
    Set<String> s = new TreeSet<String>(new Comparator<String>()
    {
    @Override
    public int compare(String o1, String o2)
    {
    if (o1.equals(o2))
    return 0;
    return 1;
    }
    });
    s.addAll(keys);

    ArrayList<String> result = new ArrayList<String>();
    result.addAll(s);

    return result;
    }


    This method will create a Set (which will not accept duplicates) and give it a String Comparator.  The compare method is overridden so basically you will have to write it ("you", as in "the programmer").  As these are Strings we are comparing, the equals method is needed (Don't even think about using "==" when comparing Strings.  Really, don't.)  Next, the key list is added to the set and it will automatically store each value once, so no duplicates.  Finally a new ArrayList is declared and the new modified set of unique keys are added to the list, and then it's returned.

    This is a rather quick and dirty way to get unique values from a List object.  This is basically our new Map, which should be used only in this project.  And nowhere else.


    package com.jf.xmlcomp;


    import java.io.File;
    import java.util.ArrayList;


    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;


    import com.jf.xmlcomp.util.SimpleMap;
    import com.jf.xmlcomp.util.Utils;


    public class XMLValueComp
    {
    private File xfile1;
    private File xfile2;

    private SimpleMap f1v;
    private SimpleMap f2v;

    public static void main(String[] args)
    {
    if (args.length < 2)
    printHelp();

    XMLValueComp xmlComp = new XMLValueComp(args[0], args[1]);

    xmlComp.compare();
    }

    public static void printHelp()
    {
    System.out.println("Usage: xmlcomp file1 file2");
    System.exit(0);
    }

    This is the main class for this project.  There are the two files which shall be compared along with the SimpleMaps for each of them.  The main class will accept two arguments; the two files.  If not enough arguments are passed, a help message is printed out, and the program exits.


    public XMLValueComp(String file1, String file2)
    {
    f1v = new SimpleMap();
    f2v = new SimpleMap();
    File f1 = new File(file1);
    File f2 = new File(file2);

    if (!f1.exists() || !f2.exists())
    {
    System.out.println("One of the files does not exist!");
    System.exit(0);
    }
    xfile1 = f1;
    xfile2 = f2;
    }


    Now we have the class constructor.  Doesn't do much except for initialisation and ensuring we are not comparing nothingness.  If the files do exist, then we will initilise them.  If they don't, the application will exit.


    public void compare()
    {
    Document doc1 = Utils.stringToDocument(
    Utils.readStringFromFile(xfile1));

    Document doc2 = Utils.stringToDocument(
    Utils.readStringFromFile(xfile2));

    if (doc1 == null || doc2 == null)
    {
    System.err.println("Could not build docs");
    System.exit(0);
    }

    buildMap(f1v, doc1);
    buildMap(f2v, doc2);


    ArrayList<String> uniques = new ArrayList<String>();


    uniques.addAll(f1v.getCompleteItemList());
    uniques.removeAll(f2v.getCompleteItemList());


    System.out.println("Unique to F1");
    for (String v : uniques)
    System.out.println(v);




    uniques = new ArrayList<String>();


    uniques.addAll(f2v.getCompleteItemList());
    uniques.removeAll(f1v.getCompleteItemList());

    System.out.println("\n\nUnique to F2");
    for (String v : uniques)
    System.out.println(v);
    }

    That the core of the application, where we shall be dealing with the real comparator part.  So first off, the documents are created from the String we got from the files.  After that, we shall perform the usual checking to make sure we don't have corrupted files, for example, in which case we'll report the problem and stop.  Then the Maps for each Document are built and a list of unique pairs is created.

    The duplicates from each document are removed by filling the unique list with the values from one document and then removing the ones which are found in the other document.  It is a quick way to remove the common nodes and getting only the ones that don't appear in both documents.  The same process is repeated for both documents, so eventually a list of unique items in document one and document two are printed separately.  If you compare a file with itself you can easily deduce that all the common nodes will be removed and the list of unique values will always be empty.


    private void buildMap(SimpleMap map, Document doc)
    {
    Element e = doc.getDocumentElement();


    mapNodes(map, e, "/" + e.getNodeName());
    }


    private void mapNodes(SimpleMap map, Element elem, String parent)
    {
    for (int x = 0; x < elem.getChildNodes().getLength(); x++)
    {
    Node n = elem.getChildNodes().item(x);
    String path = parent + "/" + n.getNodeName(); 

    if (n.getChildNodes().getLength() == 1)
    map.put(path, n.getTextContent());

    if (n.getNodeType() == Node.ELEMENT_NODE)
    mapNodes(map, (Element) n, path);
    }
    }


    The buildMap method is simply preparing some stuff for the mapNodes method.  The document element is passed as the root element to the mapNodes so that it can use recursion to obtain all nodes.

    The mapNodes will loop the current child nodes and store the value and path.  Every time an Element Node is encountered it will call itself and the children of that node are stored.  That will go on until all the nodes in the document have been traversed.

    You can now try it out by running it and passing in two paths that point to XML documents.  You should try it with the same document to ensure that it actually does not detect any differences.  Then you can go on to see if a modified XML document has kept its integrity :)

    As usual, the full code is available here.