Wednesday, 27 July 2016

Code Coverage with Tests in IntelliJ

Right, your using IntelliJ and you wanted to find the coverage for your code before you checked your code into your version controlling system. It's easy, just follow the steps below to tell you your code coverage:
  • Based on whether you've created Unit Tests or Integration Tests, you might want to test the coverage of either. In this case, am assuming its the Integration Test Coverage that is required.

    When you right click on the file in the Project window, you would see the following options for that file. Select the Run with Coverage option

  •  Once the tests have completed successfully, you would now see the below for each file that has been covered as part of the test. You get a summary of how much coverage there is for each file.

  • If you would like a more detailed analysis, you can click into each file to see the exact coverage. What is highlighted in green below has been covered and what is red is not covered.

Happy testing!

Wednesday, 8 June 2016

Integer Arrays in Bash

For reference I am on Ubuntu 15.10. This is something again I really struggled with hence thought it best to document

If you are one of those trying to use an Integer Array in a bash script, for example if your trying to identify how many days in a month for a particular year you might want to store in 2 integer arrays, one for a leap year and the other for a normal year. In my case I was trying to find the day of the year from the date provided.

Again what I found out there was a comma separated values, hence my array looked like this

  DAYS_IN_MONTHS=( 31,28,31,30,31,30,31,31,30,31,30,31 )
  DAYS_IN_MONTHS_LEAP_YEAR=( 31,29,31,30,31,30,31,31,30,31,30,31 )

But when I kept looping through the array as below, it still didn't work

  for((i=0;i<limit;i++))
    do
      if [ $[$year % 400] -eq 0 ]; then
        current=${DAYS_IN_MONTHS_LEAP_YEAR[$i]}
      elif [ $[$year % 4] -eq 0 ]; then
        if [ $[$year % 100] -ne 0 ]; then
          current=${DAYS_IN_MONTHS_LEAP_YEAR[$i]}
        else
          current=${DAYS_IN_MONTHS[$i]}
        fi
      else
        current=${DAYS_IN_MONTHS[$i]}
      fi
   dayOfYear=$((dayOfYear+current))
  done

When I did an echo on DAYS_IN_MONTHS[$i] within the loop it seemed to be displaying the entire array as the first element.

Totally confused as to why it wasn't working, am sure all of you know about how important spaces are in bash, I finally figured it was a space issue.

When I changed the arrays into the below, I was now getting individual elements but except the last element, everything had a comma(',') suffixed. 

  DAYS_IN_MONTHS=( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 )
  DAYS_IN_MONTHS_LEAP_YEAR=( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 )

So the next logical step was to remove the ',' from each element as below and that made it work.

  DAYS_IN_MONTHS=( 31 28 31 30 31 30 31 31 30 31 30 31)
  DAYS_IN_MONTHS_LEAP_YEAR=( 31 29 31 30 31 30 31 31 30 31 30 31)

Hope that helps someone?

Sunday, 5 June 2016

key=value: command not found

For reference I am on Ubuntu 15.10.

When you use the source on command line have you ever encountered key=value: command not found this error? Or even in a bash script?

$ source <filename>
key=value: command not found

Most of the information on the Ubuntu website takes you in the direction of executing this command in the wrong shell. I was running a bash script with the above command throwing the above error. So according to what I found the first line of your bash script should have been #!/bin/bash and not #!/bin/sh which is exactly what I had.

I then ran the same command on the bash shell and got exactly the same error. Now that I knew this was not my shell, I had to figure out what the cause was.

Also instead of running a source <filename> you can apparently do a . <filename> and this also resulted in exactly the same error.

'source' apparently is supposed to be the long version of '.' command. On the bash prompt one can do:

$ source ~/.bashrc

or


$ . ~/.bashrc

It took me hours of debugging to finally figure out what I was doing wrong, and hence why I decided to document it hoping it might be useful to someone out there.

You need to understand what a source does before you can debug the issue. The problem with source is, its a shell built-in which means that there's no documentation available for it through man. On a terminal type the below:

$ man source
No manual entry for source

Now try the below
$ type source
source is a shell builtin


And when you try source on its own
$ source
bash: source: filename argument required
source: usage: source filename [arguments]

Right, so how do I get more information on source and what does a source actually do?

Since I was in bash, and source is a shell builtin the next thing is to do a man bash, and search for a source in the manual.

 $ man bash
       source filename [arguments]
              Read and execute commands from filename  in  the  current  shell
              environment  and return the exit status of the last command exe‐
              cuted from filename.  If filename  does  not  contain  a  slash,
              filenames  in  PATH  are  used  to find the directory containing
              filename.  The file searched for in PATH need not be executable.
              When  bash  is  not  in  posix  mode,  the  current directory is
              searched if no file is found in PATH.  If the sourcepath  option
              to  the  shopt  builtin  command  is turned off, the PATH is not
              searched.  If any arguments are supplied, they become the  posi‐
              tional  parameters  when  filename  is  executed.  Otherwise the
              positional parameters are unchanged.  The return status  is  the
              status  of  the  last  command exited within the script (0 if no
              commands are executed), and false if filename is  not  found  or
              cannot be read.


Or as quoted from http://superuser.com/questions/46139/what-does-source-do

"info source

BASH BUILTIN COMMANDS
       Unless otherwise noted, each builtin command documented in this section
       as accepting options preceded by - accepts -- to signify the end of the
       options.   The  :, true, false, and test builtins do not accept options
       and do not treat -- specially.  The exit, logout, break, continue, let,
       and  shift builtins accept and process arguments beginning with - with-
       out requiring --.  Other builtins that accept  arguments  but  are  not
       specified  as accepting options interpret arguments beginning with - as
       invalid options and require -- to prevent this interpretation.
       : [arguments]
              No effect; the command does nothing beyond  expanding  arguments
              and  performing any specified redirections.  A zero exit code is
              returned.

        .  filename [arguments]
       source filename [arguments]
              Read and execute commands from filename  in  the  current  shell
              environment  and return the exit status of the last command exe-
              cuted from filename.  If filename does not contain a slash, file
              names  in  PATH  are used to find the directory containing file-
              name.  The file searched for in PATH  need  not  be  executable.
              When  bash  is  not  in  posix  mode,  the  current directory is
              searched if no file is found in PATH.  If the sourcepath  option
              to  the  shopt  builtin  command  is turned off, the PATH is not
              searched.  If any arguments are supplied, they become the  posi-
              tional  parameters  when  filename  is  executed.  Otherwise the
              positional parameters are unchanged.  The return status  is  the
              status  of  the  last  command exited within the script (0 if no
              commands are executed), and false if filename is  not  found  or
              cannot be read."


Also quoting from stackoverflow "@robinst: Sourcing the file using . or source has the problem that you can also put commands in there that are executed. If the input is not absolutely trusted, that's a problem (hello rm -rf /)."

And that told me what the problem was. In the end what it was is that if your key contains a hyphen '-' instead of an underscore '_' then you would encounter this error. Obviously my key had a hyphen which was getting converted into a command probably with a corresponding parameter

If you want to try this, do the following:
$ vi ~/test
and enter the below
key-1=value1
and save the file

Now try the following in your terminal
source ~/test
and you would see the error below
key-1=value1: command not found

Friday, 5 February 2016

Java - Interning

public static void main(String[] args) {

    Long long1 = new Long(1234);
    Long long2 = long1;

    // Does this compare references or actual values? 
    if (long1 == long2) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }
 
    // Displays "Equal"
 
    long2 = new Long(1234);

    // Let's create a new object with the same value to see if this works.
    if (long1 == long2) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }

    // Displays "Not Equal" 
 
    // Let's compare the Long wrapper with its equivalent primitive. 
    if ((new Long(1234) == 1234) && (Long.valueOf(1234) == 1234)) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }

    // Displays "Equal" 

    long1 = Long.valueOf(1234);
    long2 = Long.valueOf(1234);

    // We've now used valueOf() instead of creating a new Long, just to see if it works. 
    if (long1 == long2) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }

    // Displays "Not Equal"   
 
    // Numbers in the range [-128, 127] are cached. 
    long1 = (Long.valueOf(127);
    long2 = (Long.valueOf(127);

    if (long1 == long2) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }

    // Displays "Equal" 

    // So let's prove it for numbers greater than 127. 
    if ((Long.valueOf(128) == Long.valueOf(128))) {
        System.out.println("Equal");
    } else {
        System.out.println("Not Equal");
    }
 
    // Displays "Not Equal" 
 }

Thursday, 4 February 2016

Java - Difference between System.gc() and Runtime.getRuntime().gc()

public static void main(String[] args) {
    // Some code here
    // Invoke the Garbage Collector here.
     System.gc();

    // Some more code here
    // Invoke the Garbage Collector again.
     Runtime.getRuntime().gc();
}
 
In the above code, both calls seem to invoke the Garbage Collector. So what is the difference between System.gc() and Runtime.getRuntime().gc()?

Looking at the API documentation for System.gc() it invokes Runtime.getRuntime().gc()which means they are the same and System.gc() is only a convenience method.

Java 8 - Syntax to represent Lambdas

Below is the syntax for representing a Lambda expression :
parameter(s) −> expression(s)
where
  • parameter(s) has the following rules:
  1. Optional type declaration
  2. Optional comma, only for more than one parameter
  3. Optional brackets, only for more than one parameter
  • expression(s) has the following rules:
  1. Optional curly braces
  2. Optional return keyword
As quoted from the Oracle site:

"Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methods—methods without a name."

Java 8 - List of New Features

Among the loads of features added in Java 8, a summary of the most significant features is provided below:
  • Lambda Expressions - enables you to treat functionality as a method argument
  • Method References - easy to read lambda expressions for methods
  • Default Methods -  new functionality added to interfaces
  • Stream API -  functional style operations on collections of elements 
  • Performance Improvement for HashMaps with Key Collisions
  • Java Tool Updates - New jdeps and jjs commands.
  • New Date Time API - New package for Date and Time
  • java.io and java.util Changes - Updates to these packages
  • Nashorn Javascript Engine
For a more detailed information on all the updates, follow this link to the Oracle site.

More information provided on my blog as well. Follow the Java 8 link in the Labels section at the bottom of this post for more information. Oh, and feel free to drop some comments, whether you find the posts helpful or not.

Happy coding!

Tuesday, 26 May 2015

ECHO in a Command Prompt

Contents:

Introduction

As per the DOS shell, the ECHO command brings up the following when you type HELP ECHO

C:\>help echo

Displays messages, or turns command-echoing on or off.
  ECHO [ON | OFF]
  ECHO [message] 

Type ECHO without parameters to display the current echo setting.

Open a new Command prompt window and try the following:

ECHO without parameters

C:\>echo
ECHO is on.

ECHO [ON | OFF]

To turn Echo Off, try the below
C:\>echo off
_
You would notice that the prompt with the current path has now disappeared. Test the setting by typing in echo and press Enter. You would see the below:
 
echo
ECHO is off.

To turn Echo off, type the below and press Enter. You should now see your prompt with the current path being displayed:

echo on
C:/>

ECHO [message]

  • ECHO Static String

On the command prompt, try the below:
C:\>echo Hello World
Hello World

C:\>echo "Hello World"
"Hello World"

C:\>echo 'Hello World'
'Hello World'


In short, anything that follows the Echo will be displayed. You dont have to quote it. If you add quotes, you notice that the quotes themselves are also displayed.
  • ECHO with Variables

If your using variables, which you might do in a Command Prompt, then the below is useful

C:\>set STRING="HELLO WORLD"
C:\>echo %STRING%
"HELLO WORLD"

If your using Environment Variables for instance:
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.8.0_45
 


Thursday, 15 January 2015

Hibernate Errors - Unknown column 'column_name' in 'where clause'

Just thought I'd share this.

While writing your hibernate queries, if your Restriction and ProjectList contain the same column you could get "Unknown column 'column_name' in 'where clause'" something like below

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'y17_' in 'where clause'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1031)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1837)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1961)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2543)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1737)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1888)
    at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
    at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:1787)
    at org.hibernate.loader.Loader.doQuery(Loader.java:674)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
    at org.hibernate.loader.Loader.doList(Loader.java:2213)
    ... 86 more


My code is as below:

criteria.add(Restrictions.in("code", accommodationCodes)); 

and later
 
projectionList.add(Projections.property("name"), "name");
projectionList.add(Projections.property("code"), "code");


Basically when your restriction and projection contain the same column, you will see this error. To get around this, all you have to do is change

criteria.add(Restrictions.in("code", accommodationCodes));

to

criteria.add(Restrictions.in("this.code", accommodationCodes));

Thursday, 12 June 2014

Version Control/Revision Control - Introduction

We are thinking of migrating to GIT from Subversion, hence I thought let me include a guide to version control systems. I might in a later post also including the steps we have thought of for the migration hoping this might be a guide for someone


Coming back to what I would mention as part of this post, here's a quick guide to what Version Control is all about. Version control also know as Revision Control is the process of managing changes to any kind of information that is capable of changing or having revisions. The kind of information we deal with in the Software Industry could range from anything like Requirements Documents, Design Documents, Software Code, Test Case Documents, System Configuration Information and a lot more.

So how do we deal with different versions of documents and if many different people in the team are using the same document and updating the same section of the document. For example, if you had 2 developers working on the same piece of code and writing 2 different bits of functionality which affected the same method? How would you deal with the changes every time you need to release the code. You would have to do individual merges of code from everyone's machine and retest different bits of functionality to ensure nothing's broken.

All of this can be automatically taken care of if you were using a centralised repository, where every time someone makes a change, all you have to do is sync your local code with the repository version and you've pulled in the latest code. If there is a conflict with the same sections being modified by 2 or more different people, the changes have to be merged in manually. But usually the job becomes easier if your using diff tools to compare the differences.

There are other advantages for the Release process while using Version Control systems but I won't go in there in this post. It's more about the branches and tags as part of the Release process but that could be a separate topic altogether. 

So there are various Repository tools which support Revision Control or Version Control. Some examples of the most common ones are

Microsoft Visual Source Safe - Licensed cost
IBM Rational ClearCase - Licensed cost
CVS - Free
Apache SVN - Free
GIT - Free

In addition most suites provide for version control. Spreadsheet and document tools have an inbuilt versioning control system, which allows for changes between multiple users. They also do provide a mechanism for merging in 2 or more versions of the document into a single one. Since the repository may not have any inbuilt mechanism for comparing various kinds of documents, the merge tools are usually third parties for the various kinds of documents that you may have. The merge is usually not a functionality that the Repository provides.The document once merged and updated  can then be stored in the Repository that your using.

Hope you liked this short introduction to Version Control or Revision Control. Please feel free to leave any comments or feedback.


Wednesday, 4 June 2014

Introduction/Welcome Note

I have been wanting to do this for a few months now, but only got the motivation to this today.

This blog would be an amalgam of the technical knowledge that I have worked on, and hopefully helps other people too?

Anyways welcome to my blog, and hope you enjoy your stay here.

Comments/Suggestions are more than welcome.