Java 8 – First Step Towards Functional & Declarative Programming

March 4, 2013 1 comment

Object Oriented Programming, the leading style of programming, has became very popular in the last few decades. Though OO existed even before the advent of C++, true potential of OO unleashed with the launching of C++

C++ is a mixture of structured and OO style. Bjarne Stroustroup invented C++ as part of a project he was working on. This project of his required better performance than what was offered by the conventional languages back then. He wasn’t trying to make something perfect, which is probably the reason behind the highly unpredictable behavior of C++, which it inherited from its parent “C”

JAVA entered flashily with their light weight client side programs called Applets. It was not very late, when people realized that there is more to this new coffee bean than just being a client side entity.

Apart from being a good OO solution, Java addressed the biggest challenge in C++, providing Garbage collection for automatically cleaning up the memory & portability regardless of platform. These two features triggered the evolution of a new era in which JAVA flourished as a platform as well as a language.

Pointers in C/C++ was considered complex and evil, so Java removed pointers. But, ask yourself, can a language work without pointers? It is not possible right. Java diplomatically renamed them as “References” and removed arithmetic operations on them. Smart, right? They didn’t expose unnecessary interfaces, and made the run time to carry out difficult things for you. I mean this is what abstraction and encapsulation is all about, which is blabbered all the time while talking about Java.

So, it turned out that everything became OO. People started thinking, talking & eating in terms of Objects. With Java, it became a monotonic idiom to define a class for doing anything. But, Why do we need to create a class every time I need to add something. Why do we always have to talk in terms of classes, when just a function/method would suffice. An example of such case would be a class with only static methods like java.lang.Math

The Imperative style of programming in Java started frustrating developers

JAVA Imperative Style Code (Java 7)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ImperativeStyleDemo {
    public static void main(String []args){
        List numbers = Arrays.asList(1, 2, 3, 4, 5);

        List modifiedNumbers = new ArrayList<>();
        for(Integer number: numbers){
            if(isEven(number))
                modifiedNumbers.add(ImperativeStyleDemo.doubleInteger(number));
        }

        for(String number: modifiedNumbers){
            System.out.println(number);
        }
    }

    public static String doubleInteger(Integer number){
        return String.valueOf(number*2);
    }

    public static Boolean isEven(Integer number){
        return number%2==0;
    }
}

I mean look at this code, just to display double of even numbers in a list, I had to explicitly tell the compiler to loop through and do all the ceremony for me. It might not look complex to a Java programmer, but it is fairly complex for a newbie.

Then, writing a thread safe code isn’t very easy. I never get it right, I mean, synchronized keyword has a lot of evil around it.

Isn’t it going the same way it went with the pointers in C++? Such complex details should be handled by the run time itself, without letting the programmer know about the complexities buried deep within.

So what’s next?

The idea lead to use the functional style of programming along with Object style, a hybrid language with declarative style of programming instead of imperative style.

But, there is more to JVM than what Java exposes and people always want to keep using that. Why would we want to lose the advantages of JVM just because the interface (Java Language) is not fulfilling our desires. So why not build a declarative functional style language using Java itself which use JVM as a platform. Cool right? This idea gave birth to many JVM languages including Groovy, Scala, Clojure, JRuby, etc

Now let’s look at some code in Groovy to do the same stuff

Groovy Declarative Style Code

[1,2,3,4,5].findAll { it % 2 == 0 }.each() {value->println "${value*2}"};

This is a declarative way of programming and there are many such examples available on internet.

Now the threat that JAVA will decay as a language has reached Oracle/Sun as well. So there has been a lot of work going on to address this stuff in Java 8. So let’s have a look to do the same stuff in Java 8

JAVA Declarative Style Code (Java 8 – Lambda Project)

import java.util.Arrays;
import java.util.List;

class DeclarativeStyle {
    public static void main(String []args){
        List numbers = Arrays.asList(1,2,3,4, 5, 6);

        numbers.stream()                         //A Fancy Collection
           .filter(DeclarativeStyle::isEven)     //Filter the data
           .map(DeclarativeStyle::doubleInteger) //Map new values
           .forEach(System.out::println);        //Iterate & perform the operation
    }

    public static String doubleInteger(Integer number){
        return String.valueOf(number * 2);
    }

    public static Boolean isEven(Integer number){
        return number%2==0;
    }
}

The first three method calls are just lazy calls, so the list doesn’t iterates till “forEach” is called. Plus, If you do a find operation on a list, then the iteration stops then and there if the element is found. So in a way, we can say that the iterations in Java 8 has been optimized a lot, though the same can be achieved using the existing implementations in Google Guava APIs

The most important thing to notice here is Immutability. The existing collection “numbers” isn’t tampered with in any of the operation. So every method call is pure and hence can be performed interchangeably using multithreading. Let’s have a look at this.

Using Stream (Sequential Flow)

import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class SequentialStreamDemo {
    public static void main(String []args){
        long start = System.currentTimeMillis();

        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        List modifiedNumbers = numbers.stream()
                .filter(SequentialStreamDemo::isEven)
                .map(SequentialStreamDemo::doubleInteger)
                .collect(toList());

        modifiedNumbers.forEach(System.out::println);

        long end = System.currentTimeMillis();
        System.out.println("Time taken =>"+(end-start)/1000f+" seconds");
    }

    public static String doubleInteger(Integer number){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return String.valueOf(number * 2);
    }

    public static Boolean isEven(Integer number){
        return number%2==0;
    }
}

This program takes around 4.063 seconds in my machine. There are four Even Numbers, so there is a delay of 4 seconds added deliberately by Thread.sleep()

Now let’s have a look at the parallel stream. Just change the class name to ParallelStreamDemo & method call to

Using Stream (Parallel Flow)

import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class ParallelStreamDemo {
    public static void main(String []args){
        long start = System.currentTimeMillis();

        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        List modifiedNumbers = numbers.parallelStream()
                .filter(ParallelStreamDemo::isEven)
                .map(ParallelStreamDemo::doubleInteger)
                .collect(toList());

        modifiedNumbers.forEach(System.out::println);

        long end = System.currentTimeMillis();
        System.out.println("Time taken =>"+(end-start)/1000f+" seconds");
    }

    public static String doubleInteger(Integer number){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return String.valueOf(number * 2);
    }

    public static Boolean isEven(Integer number){
        return number%2==0;
    }
}

Now we are using the parallel streaming which interns use a separate thread for every stream. Guess what, the time taken now turns out to be 1.067 seconds

We could’ve achieved the same in previous versions of Java as well, but it will require relatively high LOC.

Awesome, right. Finally Java people has started removing the ceremonial activities involved. Java 8 is not yet released, but we have early release versions in the market. So you can go and play around.

There is a lot more to Java 8 than what I mentioned, which includes, easy operations on the collections, using multi cores & threads without writing any complex synchronized code.

Hope it is not too late for Java to introduce this stuff in Java language.

Looking forward to more cool stuff

Powerpoint Notes To PDF

The below VBA Macro will send all the speaker notes of the Active Microsoft Powerpoint Presentation to separate PDFs (Slide1.pdf, Slide2.pdf, etc). The PDFs will be generated on the same path as the Active Presentation. Speaker Notes will be formatted to be placed at the top of the page with font size 9 and font color black.

This macro is supposed to work only when there are exactly two placeholders defined in the Notes Master of the Presentation (One for Slide Image & the other for the Speaker Notes)

Sub NotesToPDF()
	Dim prng As PrintRange
	DocName = ActivePresentation.Path & "\Slide"
	i = 1
	ActivePresentation.PrintOptions.Ranges.ClearAll
	For Each oSlide In ActivePresentation.Slides
		ActivePresentation.Slides(i)_
                                  .NotesPage.Shapes_
                                  .Placeholders(1).Delete
		
		If ActivePresentation.Slides(i)_
                                     .NotesPage.Shapes_
                                     .Placeholders.Count = 1 Then

			ActivePresentation.Slides(i)_
                                     .NotesPage.Shapes.Placeholders(1)_
                                     .Width = ActivePresentation.NotesMaster_
                                                                .Width / 1.1
			ActivePresentation.Slides(i)_
                                     .NotesPage.Shapes.Placeholders(1)_
                                     .Height = ActivePresentation.NotesMaster_
                                                                 .Height / 2.3
			
			ActivePresentation.Slides(i)_
                                          .NotesPage.Shapes.Placeholders(1)_
                                          .TextFrame.TextRange.Font.Size = 9
	
                        ActivePresentation.Slides(i)_
                                          .NotesPage.Shapes.Placeholders(1)_
                                          .TextFrame.TextRange.Font_
                                          .Color.RGB = RGB(0, 0, 0)
			
			ActivePresentation.Slides(i)_
                                          .NotesPage.Shapes.Placeholders(1)_
                                          .Top = ActivePresentation_
                                                       .NotesMaster.Height/30
			ActivePresentation.Slides(i)_
                                          .NotesPage.Shapes.Placeholders(1)_
                                          .Left = ActivePresentation_
                                                       .NotesMaster.Width*0.05
		End If
		
		Set prng = ActivePresentation.PrintOptions.Ranges.Add(i, i)
		ActivePresentation.ExportAsFixedFormat DocName & i & ".pdf",_
                            ppFixedFormatTypePDF, ppFixedFormatIntentPrint, _
                            msoCTrue, ppPrintOutputNotesPages, _
                            ppPrintOutputNotesPages, msoFalse, prng, _
                            ppPrintSlideRange, , False, False, False, _
                            False, False
		
                i = i + 1
	Next oSlide

	ActivePresentation.Close
End Sub

Connect C with MySQL Database

Here is a detailed & simple explanation on how to connect a C Program to MySQL Database on Linux

Install MySQL on Linux

1. Start your linux server in terminal mode
2. Install MySQL Server using the below command

apt-get install mysql-server

3. During the installation you will be prompted for a password. Choose a password
4. For setting the various security settings of MySQL type the following command in the terminal

mysql_secure_installation

5. You can verify MySQL installation by giving the following command in the terminal. It will take you to the MySQL Terminal

mysql -u root -p

Install necessary libraries

1. Type the following commands in the Terminal (Here we are installing the libraries to connect MySQL with C)

mysql_config --libs
mysql_config --cflags

2. If the mysql_config script is not installed then install the same by giving the following command. This script provides you with useful information for compiling your MySQL client and connecting it to MySQL database server

sudo apt-get install libmysqlclient-dev

Write your C Program

The below program connects to the “mysql” database and displays all the tables present in the DB. Put your logic and use it your way

#include <mysql.h>
#include <stdio.h>
main() {
	MYSQL *conn;
	MYSQL_RES *res;
	MYSQL_ROW row;
	
	char *server = "localhost";
	char *user = "root";
	char *password = "root"; /* set me first */
	char *database = "mysql";
	
	conn = mysql_init(NULL);
	
	/* Connect to database */
	if (!mysql_real_connect(conn, server, user, password, 
                                      database, 0, NULL, 0)) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		exit(1);
	}
	
	/* send SQL query */
	if (mysql_query(conn, "show tables")) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		exit(1);
	}
   
	res = mysql_use_result(conn);
	
	/* output table name */
	printf("MySQL Tables in mysql database:\n");
   
	while ((row = mysql_fetch_row(res)) != NULL)
		printf("%s \n", row[0]);
   
	/* close connection */
	mysql_free_result(res);
	mysql_close(conn);
}

You can refer MySQL C API to know about more functions and data structures used for MySQL

Compiling your program

gcc -o EXEName $(mysql_config --cflags) PRGName.c $(mysql_config --libs)

Executing the stuff

./EXEName

Maximum URL Size in HTTP GET Request

There is no thumb rule made for the maximum URL size of HTTP Get Request as per RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1 – Section 3.2.1). Limits are imposed by various browsers and respective servers. These limits must be considered collectively while passing the query string passed in the URL in any of the HTTP Requests. If the URL size exceeds the URL Size limit imposed by the respective browser, the request will not be passed to the server & unnecessary effort will be required to debug & handle this situation.

To avoid this kind of a situation, one must account for this possibility in earlier stages of development. I have compiled the limits and other basic information regarding the HTTP Get Request

Browser Maximum URL Size Remarks
Internet Explorer 2048 B Microsoft Internet Explorer has a maximum uniform resource locator (URL) length of 2,083 characters. Internet Explorer also has a maximum path length of 2,048 characters. This limit applies to both POST request and GET request URLs.If you are using the GET method, you are limited to a maximum of 2,048 characters, minus the number of characters in the actual path.
Mozilla Firefox >100 KB The address bar doesn’t shows any characters beyond 65,536 characters. But the URL Size can be more than that, though you cannot view it in the address bar. This holds for FireFox 1.5 up until the current FireFox version
Opera >200 KB The URL is completely visible in the address bar even at such a big range
Chrome,Safari >100 KB Both browsers are webkit based and seems to have almost same limit as firefox
Server Maximum URL Size Remarks
Apache >128 KB The size is changed using the LimitRequestLine setting of the server
IIS >16 KB Default value is 16 KB and maximum limit is 16 MB
Lotus Notes 4 KB

Let’s understand the basic difference between a GET Request and a POST Request. GET requests are made to request a particular resource from the server. Whatever information is required to fetch the desired resource are passed as query string parameters. While POST Requests are made to post some data to a particular resource for processing as well as request a response. We should not use GET Requests to have data posted to the server, it should only be used, as its name suggests, to get a particular resource from the server. There is a thin but very clear line between logical usage of both

Very long URLs are not recommended at all. For a web based application to be cross browser compatible, the Get Method must not be used for passing very long strings, containing more than 2000 characters. If you are facing a situation where you need to use URLs to contain huge number of characters, then give it another thought

Excel Adapter for JTable

Swings JTable doesnot support copy paste functionality from Microsoft Excel or any other spreadsheet application. So for copying the data from Excel to JTable (in the UI), you need to copy paste for each cell individually. Multiple rows/columns values cannot be copied from Excel to a JTable, at once. This feature should have been supported by Swings API itself, but unfortunately it isn’t

So I looked on the web for the solution & found this code snippet to get the desired functionality

ExcelAdapter enables Copy-Paste Clipboard functionality on JTables. The clipboard data format used by the adapter is compatible with the clipboard format used by Excel. This provides for clipboard interoperability between enabled JTables and Excel

Usage Instructions :-

  1. Pass your JTable instance to the ExcelAdapter class constructor. It will enable your JTable to paste the cell data copied from Excel using Ctrl+V
  2. JTable jTable1 = new JTable();
    ExcelAdapter excelAdapter = new ExcelAdapter(jTable1);

  3. Add a class “ExcelAdapter.java” with the below code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.datatransfer.*;
import java.util.*;

public class ExcelAdapter implements ActionListener{
    private String rowstring,value;
    private Clipboard system;
    private StringSelection stsel;
    private JTable jTable1 ;
    /**
    * The Excel Adapter is constructed with a
    * JTable on which it enables Copy-Paste and acts
    * as a Clipboard listener.
    */
    public ExcelAdapter(JTable myJTable){
        jTable1 = myJTable;
        KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C,
                                     ActionEvent.CTRL_MASK,false);
        // Identifying the copy KeyStroke user can modify this
        // to copy on some other Key combination.
        KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,
                                     ActionEvent.CTRL_MASK,false);
        // Identifying the Paste KeyStroke user can modify this
        //to copy on some other Key combination.
        jTable1.registerKeyboardAction(this,"Copy",copy,
                                     JComponent.WHEN_FOCUSED);
        jTable1.registerKeyboardAction(this,"Paste",paste,
                                     JComponent.WHEN_FOCUSED);
        system = Toolkit.getDefaultToolkit().getSystemClipboard();
    }

    /**
    * Public Accessor methods for the Table on which this adapter acts.
    */

    public JTable getJTable(){
        return jTable1;
    }

    public void setJTable(JTable jTable1){
        this.jTable1=jTable1;
    }

    /**
    * This method is activated on the Keystrokes we are listening to
    * in this implementation. Here it listens for Copy and Paste
    * ActionCommands. Selections comprising non-adjacent cells result
    * in invalid selection and then copy action cannot be performed.
    * Paste is done by aligning the upper left corner of the selection
    * with the 1st element in the current selection of the JTable.
    */

    public void actionPerformed(ActionEvent e){
        if (e.getActionCommand().compareTo("Copy")==0){
            StringBuffer sbf=new StringBuffer();
            // Check to ensure we have selected only a contiguous block of
            // cells
            int numcols=jTable1.getSelectedColumnCount();
            int numrows=jTable1.getSelectedRowCount();
            int[] rowsselected=jTable1.getSelectedRows();
            int[] colsselected=jTable1.getSelectedColumns();
            if (!((numrows-1==rowsselected[rowsselected.length-1]-
                rowsselected[0] &&
                numrows==rowsselected.length) &&
                (numcols-1==colsselected[colsselected.length-1]
                -colsselected[0] &&
                numcols==colsselected.length))){
                JOptionPane.showMessageDialog(null, "Invalid Copy Selection",
                "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE);
                return;
            }
            for (int i=0;i<numrows;i++){
                for (int j=0;j<numcols;j++){
                    sbf.append(jTable1.getValueAt(rowsselected[i],
                                       colsselected[j]));
                    if (j<numcols-1){
                        sbf.append("\t");
                    }
                }
                sbf.append("\n");
            }
            
            stsel  = new StringSelection(sbf.toString());
            system = Toolkit.getDefaultToolkit().getSystemClipboard();
            system.setContents(stsel,stsel);
        }
        
        if (e.getActionCommand().compareTo("Paste")==0){
            System.out.println("Trying to Paste");
            int startRow=(jTable1.getSelectedRows())[0];
            int startCol=(jTable1.getSelectedColumns())[0];

            try{
                String trstring= (String)(system.getContents(this)
                                 .getTransferData(DataFlavor.stringFlavor));
                System.out.println("String is:"+trstring);
                StringTokenizer st1=new StringTokenizer(trstring,"\n");

                for(int i=0;st1.hasMoreTokens();i++){
                    rowstring=st1.nextToken();
                    StringTokenizer st2=new StringTokenizer(rowstring,"\t");

                    for(int j=0;st2.hasMoreTokens();j++){
                        value=(String)st2.nextToken();
                        if (startRow+i< jTable1.getRowCount() && 
                                       startCol+j< jTable1.getColumnCount()){
                            jTable1.setValueAt(value,startRow+i,startCol+j);
                        }
                        System.out.println("Putting "+ value+
                                 "at row="+startRow+i+"column="+startCol+j);
                    }
                }
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }
}

Dynamic Print Screen

Here is a simple code to simulate the Print Screen function dynamically

The screenshot can be cropped by creating your own Dimension Object with manually entered height and width

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

/**
 * 	Capture the desktop to "desktop.jpg"
 */

class PrintScreen {
	public static void main(String[] args) throws Exception {
		Dimension size = Toolkit.getDefaultToolkit()
                                        .getScreenSize();
		BufferedImage img = null;
                img = new Robot().createScreenCapture(new Rectangle(size));
		ImageIO.write(img, "JPG", new File("desktop.jpg"));
	}
}

Determinant of N x N Square Matrix

Though it is not really a quest but I have seen people struggling for this. So, I wrote a simple & small Java method which does the job

All you need to do is, put this method inside some class (better make it static)

Pass the matrix along with its order and get the determinant output

 

@Params Square Matrix (Two dimensional array)
        Order of the matrix which is passed
@return Determinant of the passed matrix

public int determinant(int a[][], int n){
	int det = 0, sign = 1, p = 0, q = 0;

	if(n==1){
		det = a[0][0];
	}
	else{
		int b[][] = new int[n-1][n-1];
		for(int x = 0 ; x < n ; x++){
			p=0;q=0;
			for(int i = 1;i < n; i++){
				for(int j = 0; j < n;j++){
					if(j != x){
						b[p][q++] = a[i][j];
						if(q % (n-1) == 0){
							p++;
							q=0;
						}
					}
				}
			}
			det = det + a[0][x] *
                              determinant(b, n-1) *
                              sign;
			sign = -sign;
		}
	}
	return det;
}