Tuesday, March 31, 2015

Failed to connect to queue manager - WebSphere MQ Error in Java

"Failed to connect to queue manager" error comes in WebSphere MQ if any Client e.g. Java program is not able to connect to MQ server due to any reason. The reason is actually identified by reason code in error message e.g. code 2397 comes when SSL is enabled between client and server and Java client is not able to connect to server due to unknown or expired SSL certificates. If you are working in Java application which is using WebSphere MQ for messaging over SSL then you are bound to face some setup, certificate and keystore vs truststore related error. For first timers understanding SSL and MQ errors is nightmare, forget about solving them. I have gone through that and after spending hours on Google and Websphere MQ documentations, I managed to solve some of the problems we face while connecting to MQ over SSL from our Java application. In this article, I am listing down these errors and exceptions and their cause and solution for everyone's benefit. Next time you face any MQ SSL issue, hopefully you will find the right solution to solve these tricky errors. In this tutorial we will mainly looked at three errors :
  • Unable to find valid certification path to requested target
  • JMSWMQ2020: Failed to connect to queue manager
  • Remote SSL peer name error for channel 'ABC.XYZ'

I have mostly encountered these while working with Java application which was connecting to other legacy system using MQ for sending and receiving XML files, but useful to anyone who is using over MQ over SSL.

Monday, March 30, 2015

What is Effectively Final variable of Java 8

Apart from big three, Lambda expression, Stream API and new Date and Time API, Java 8 has also introduced a new concept called "effectively final" variable. A non-final local variable or method parameter whose value is never changed after initialization is known as effectively final. It's very useful in the context of the lambda expression. If you remember, prior to Java 8, we cannot use a non-final local variable in an anonymous class. If you have to access a local variable ( a method parameter or a variable decreed in the method itself) in Anonymous class, you have to make it final. This restriction is relaxed a bit with lambda coming up. Java designers have taken the need to make local variable final if it's not changed once initialized. This is really a good proactive step from them, they must have anticipated frequent use of lambda expressions as compared to the minimal use of Anonymous class and realized the pain to declare a local variable final every time in order to access it inside the lambda. The rule has not changed, any local variable still has to be effectively final to be used inside lambda expression or anonymous inner class, its just that you don't need to use final keyword anymore, saving a few keystroke. If you don't follow this then you will get following error: "local variables referenced from a lambda expression must be final or effectively final". Let's see some examples of effectively final variables with lambdas and anonymous class and how it make the life of Java developer easy. You can also read Cay S. Horstmann's Java SE 8 for Impatient to learn more about Effectively final variables in Java 8.

Friday, March 27, 2015

Parsing Large JSON Files using Jackson Streaming API Example

In last couple of JSON tutorials for Java programmers, we have learned how to parse JSON using JSON-Simple library, parsing JSON array to Java array using GSon, and in this tutorial we will learn how to parse a large JSON file in Java using Jackson's Streaming API. Jackson is one of the most popular JSON processing framework and provides three main model to parse and process JSON data including Streaming API, data binding and tree model. Out of these three, Streaming works at lowest level and can be used to parse huge JSON response upto even giga bytes of size. If you are familiar with XML parsing, then you know that how difficult it is to parse huge XML files with DOM parser because it fully loads the file in memory before you can process it. In case you have low memory e.g. Android devices you can't use that to parse XML. Thankfully, XML provides SAX and StAX parsers which are streaming based and can be used to process huge files without loading them completely in memory. Out of these two, StAX is even better because it allows pull based processing where client pulls data from parser instead of parser pushing data, which is the case with SAX parser. Jackson's Streaming API is similar to StAX parser. You can pull the data you want and ignore what you don't want. Though performance doesn't come without cost, using Streaming API is little difficult then using other Jackson model which provides direct mapping between Java and Jackson objects. You have to handle all JSON data by yourself while using Streaming API.

Thursday, March 26, 2015

How to reverse array in place in Java?

Reversing an array sounds pretty easy, isn't it? It does sounds like that, because all you need to do is create an array of same size, iterate through original array from end to start and populate your new array. Boom!!, you have got an array which has elements in reverse order of original array, but problem is you have used and additional array here, which makes space complexity of your solution O(n). You cannot use this solution if array is big e.g. an array of 10 million orders and you don't have enough heap space available. Can we make it better? Can we reverse array in Java without using an additional buffer? Even If you encounter this question in your programming job interview, you will be surely asked to reverse array in place, without using an additional buffer as earlier solution takes lot of space. So now your task is to write a Java program to reverse an array in place. For the sake of this problem, you can assume that its an integer array (during interview, you should ask these question to your interviewer, because asking right question to fill the gap in requirement is a trait of good programmer and highly appreciated on both telephonic and face-to-face interviews). Key point to understand here is that you need to reverse the same array, you cannot use another array but one or two variable is fine. You are also not allowed to use any open source library or Java API which can reverse the array directly e.g. any method from java.util.Arrays class except Arrays.toString()to print arrays in Java. So now the requirement is clear, what approach comes in your mind? how do you solve this problem?

Monday, March 23, 2015

10 difference between Java and JavaScript for Programmers

Programmers, developers and internet users  have always been confused between Java and JavaScript.  Many people still thinks that JavaScript is part of Java platform, which is not true. In truth, JavaScript has nothing to do with Java, only common thing between them is word "Java", much like in Car and Carpet, or Grape and Grapefruit. JavaScript is a client side scripting language for HTML, developed by Netscape, Inc, while Java is a programming language, developed by Sun Microsystems. James Gosling is Inventor of Java, popularly known as father of Java. While in today's world calling JavaScript just a client side scripting language would not be good, as its now been used in servers also using node.js and people are doing object oriented development in JavaScript, but that was what it was originally developed. There are several difference between Java and JavaScript, from how they are written, compiled and executed. Even capability of Java and JavaScript vary significantly. Java is full feature Object oriented programming language, used in almost everywhere, starting from programming credit card to server side coding. Android uses Java as programming language for creating Android apps, Swing is a Java API used to create desktop applications and Java EE is a Java platform for developing web and enterprise applications. On the other hand JavaScript is primarily used to bring interactivity into web pages, though there are other alternatives like Flash, JavaScript is the most popular one and regaining lots of ground lost earlier with introduction of powerful and easy to use libraries like jQuery and jQuery UI. You can use JavaScript to validate user input, create animation and cool effects in HTML page and can do lot of interactive stuff e.g. reacting on button click, mouse movement, image click etc. In this article, I will share some key differences between Java and JavaScript, mostly from a programmers perspective.

Thursday, March 19, 2015

5 ways to Convert Java 8 Stream to List - Example, Tutorial

One of the common problem while working with Stream API in Java 8 is how to convert a Stream to List in Java because there is no toList() method present in Stream class. When you are processing a List using Stream's map and filter method, you ideally want your result in some collection so that you can pass it to other part of program. Though java.util.stream.Stream class has toArray() method to convert Stream to Array, but  there is no similar method to convert Stream to List or Set. Java has a design philosophy of providing conversion method between new and old API classes e.g. when they introduced Path class in JDK 7, which is similar to java.io.File, they provided a toPath() method to File class. Similarly they could have provided convenient methods like toList(), toSet() into Stream class, but unfortunately they have not done that. Anyway, It seems they did thought about this and provided a class called Collector to collect the result of stream operations into different container or Collection classes. Here you will find methods like toList(), which can be used to convert Java 8 Stream to List. You can also use any List implementation class e.g. ArrayList or LinkedList to get contents of that Stream. I would have preferred having those method at-least the common ones directly into Stream but nevertheless there is something you can use to convert a Java 8 Stream to List. BTW, my research to this task also reveals several other way to achieve the same result, which I have summarized in this tutorial. If would suggest to prefer standard way, which is by using Stream.collect() and Collectors class, but its good to know other ways, just in case if you need.

Monday, March 16, 2015

Top 10 Popular Programming languages and their Creators

There are many programming languages out there in software world and they are still coming like Scala, Go, Closure etc, but only handful of them has managed to survive till date. These are the ones who has contributed immensely in software development. Since, programming language is single most important thing in software development world, it's often discussed, criticized and improved over the years. Programmers and developers, who created those programming language are icons of programming world and sometime I feel sad when a guy using a programming language doesn't know, who is behind that. Though it happens less often with more popular programming language like Java, where everybody knows James Gosling as father of Java, not every developer know who created Perl, Pascal, Lisp or Erlang. These thoughts motivates me to collect and share, names of programmer and designers, behind 10 of the most popular and successful programming languages.  On my search I bump into a nice info-graphic, which I have shared with your guys at the bottom of this post. The infographic also puts together 10 of the most popular programming language of last 50 years, I thought to share with you guys.

Friday, March 13, 2015

How to find Largest Prime Factor of a Number in Java - Programming Kata

One of the common programming kata to learn coding is write a program to find the largest prime factor of a number. Like any other programming problem, you need to build the logic to solve this problem. Before solving the problem, let's revise the concept of number theory. Prime factors of a positive integer are the prime numbers that divide the number exactly i.e. without any remainder, and prime factorization is the process of finding all prime numbers when multiply together make original number.  A positive integer can have multiple prime factors, our challenge is to find the largest prime factor of a number. For example, 6 has two prime factors 2 and 3, your program should return 3, because that's the largest prime factors. In one of earlier problem, we have learned how to find prime factor of a number in Java and we will use the similar logic here, but instead of returning a list of prime factors we will only return the largest prime factor.

Thursday, March 12, 2015

How to delete a directory with files in Java - Example

Deleting an empty directory is easy in Java, just use delete() method of java.io.File class, but deleting a directory with files is unfortunately not easy. You just can't delete a folder if it contains files or sub folders. Calling delete() method on a File instance representing a non empty directory will just return false without removing the directory. In order to delete this folder, you need to delete all files and sub directories inside this folder. This may seem cumbersome, but unfortunately there is no method which can delete directory with files in Java, not even on Java 7 Files and Paths class. So there is two choices, either you write your own method to recursively delete all files and folder before deleting a directory or alternatively you can use an open source utility library like Apache Commons IO which will do this for you. BTW, If you have to do this without using any third party library than you can use the example shown in this tutorial. You know what, I have asked this question couple of times to Java developers and only 3 out of 10 knows that you cannot delete directory with files in Java. I am not surprised because this is the kind of detail which is not obvious. Until you do it, you don't know this. Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder, as shown in first example of this tutorial. Java 7 got much better with files and directory support but there also unfortunately no direct method to delete a directory with files. Though, In JDK 7 you could use Files.walkFileTree() and Files.deleteIfExists() to delete a tree of files.

Monday, March 9, 2015

Java 8 Date Time - 20 Examples of LocalDate, LocalTime, LocalDateTime

Along with lambda expressions, streams, and several minor goodies, Java 8 has also introduced brand new Date and Time API, and in this tutorial, we will learn how to use Java 8 Date Time API with simple how to do task examples. Java's handling of Date, Calendar and Time is long been criticized by the community, which is not helped by Java's decision of making java.util.Date mutable and SimpleDateFormat not thread-safe. Seems, Java has realized a need for better date and time support, which is good for a community which already used to of Joda Date and Time API. One of the many good things about new Date and Time API is that now it defines principle date-time concepts e.g. instants, duration, dates, times, timezones and periods. It also follows good thing from Joda library about keeping human and machine interpretation of date time separated. They are also based on the ISO Calendar system and unlike their predecessor, class in java.time packages are both immutable and thread-safe. New date and time API is located inside java.time package and some of the key classes are following :