Tuesday, 11 October 2016

Lambda expression in Java 8


Lambda expressions, also known as closures, function literals, or simply lambdas
Lambda expression is being one of the biggest feature of the Java 8 that are massively increasing the capability  of Java to functional programming . Its use is very simple to use at the same time easy to simple to understand.

Its look like :

     functional interface =   parameter --> expression body  gives output of the expression operation

(arg1, arg2...) -> { body }

(type1 arg1, type2 arg2...) -> { body }

Following are some examples of Lambda expressions.
(int a, int b) -> {  return a + b; }

() -> System.out.println("Lambda Expression unveiled");

(String s) -> { System.out.println(s); }

() -> 30

() -> { return 3.1415 };


  • Lambda expression is being mainly used to define the inline implement of a functional interface which is having only one  method.
  • Lambda expression eliminates the need of anonymous interface and define an inline implementation of the functional interface.
  • Any interface can have a lambda expression associated with it if satisfies the following 3 conditions ->:
  1. Interface must be a functional interface i.e., its should have only one method.
  2. Number of parameters in the lambda expression must match the number of parameters of the functional interface single method.
  3. Return type of the lambda expression must match the return type of single interface method.
  • we can annotate the interface with @FunctionalInterface, a new annotation for Java 8 that says we have a functional interface
  • Just like in the javascript , function are treated as an first order function and are treated as a part of functional programming , same is the lambda expression are treated in the Java8.


In the Javascript function are not mandatory to have a return value and can have only expression body E.g. ,

function mathOperation(a , b){
}

There are 4 type of lambda expressions  is presented as follows :


       
1. With type declaration 
(int a, int b) -> a + b; 
2. Without type declaration
 (a, b) -> a - b; 
3. With return statement along with curly braces
 (int a, int b) -> { return a * b; };

4. Without return statement and without curly braces.
(int a, int b) -> a / b;



  • A lambda expression  is essentially an object , one can assign this object to a variable and pass the lambda expression for other operation. 
Example1

public class LambdaExpression  {
@FunctionalInterface
public interface NumberComparator {
public boolean compare(int a1, int a2);
}
public static void main(String[] args) {
NumberComparator numberComparator = (a1, a2) -> {return a1 > a2;};
boolean result = numberComparator.compare(4, 3);
System.out.println("result=" + result);
}
}
Output: 

result=true


Example2 :  Sorting on the List of a class Employee


/**
 * @author sachin
 *
 */
class Employee{
String name;
Integer age;
Employee(String name,Integer age){
this.name = name;
this.age = age;
}
}
public class LambdaExpression  {
public static void main(String[] args) {
List<Employee> empList = new ArrayList<>();
empList.add(new Employee("John", 23));
empList.add(new Employee("Adam", 26));
empList.add(new Employee("Rollins", 28));
empList.add(new Employee("Richard", 26))
// old way of sorting  on name using anonymous class
System.out.println("--- sorting on the name using anonymous class using comparator --- ");
Collections.sort(empList, new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return o1.name.compareTo(o2.name);
}
});
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
// new way of sorting  on name using lambda expression
System.out.println("\n--- sorting on the age using lambda expression with type removing the anonymous class --- ");
//Anonymous Inner class replaced with Lambda expression with type declaration and sorting on age
Collections.sort(empList, (Employee e1 ,Employee e2) -> e1.age.compareTo(e2.age));
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
System.out.println("\n--- sorting on the age using lambda expression without type removing the anonymous class --- ");
//Anonymous Inner class replaced with Lambda expression with type declaration and sorting on age
Collections.sort(empList, ( e1 , e2) -> e1.age.compareTo(e2.age));
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
System.out.println("\n--- sorting on the name using sort of the List and lambda expression --- ");
//Anonymous Inner class replaced with Lambda expression without type declaration and sorting on name
Collections.sort(empList, (Employee e1 ,Employee e2) -> e1.age.compareTo(e2.age));
empList.sort((e1,e2) -> e1.name.compareTo(e2.name));
for (Employee employee : empList) {
System.out.println(employee.name + " " + employee.age);
}
}
}
Output : 
--- sorting on the name using anonymous class using comparator --- 

Adam 26
John 23
Richard 26
Rollins 28
--- sorting on the age using lambda expression with type removing the anonymous class --- 
John 23
Adam 26
Richard 26
Rollins 28
--- sorting on the age using lambda expression without type removing the anonymous class --- 
John 23
Adam 26
Richard 26
Rollins 28
--- sorting on the name using sort of the List and lambda expression --- 
Adam 26
John 23
Richard 26
Rollins 28
------------------------------------------      


Lambda expression is a brilliant feature added in the Java to remove the uses of anonymous class and make a robust feature towards functional programming. Functional interfaces which is another great feature added in the Java makes the lambda expression more useful and easy to understand .

Enjoy the Lambda expression !!!!

Saturday, 8 October 2016

com.mongodb.MongoInternalException: org.springframework.dao.InvalidDataAccessResourceUsageException

Exception in the mongoDB related document  size : 
------------------------------------------------------------------------------------------------------------------

com.mongodb.MongoInternalException: Size 19534568 is larger than MaxDocumentSize 16793600.
org.springframework.dao.InvalidDataAccessResourceUsageException: Size 19534568 is larger than MaxDocumentSize 16793600.; nested exception is com.mongodb.MongoInternalException: Size 19534568 is larger than MaxDocumentSize 16793600.
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:77)
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2002)
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:460)
at org.springframework.data.mongodb.core.MongoTemplate.doUpdate(MongoTemplate.java:1077)
at org.springframework.data.mongodb.core.MongoTemplate.updateFirst(MongoTemplate.java:1051)
--------------------------------------------------------------------------------------------------------------------------------

Solution : Above mentioned exceptions occurred when your document size exceeds the default BSON size limit of 16 MB and MongoDB supports no more than 100 levels of nesting for BSON documents in Mongo 3.0. [reference]

Its being made limited to avoid excessive use of RAM or during data transfers avoiding excessive bandwidth  consumption of the network. But 16 MB is still good number to store documents in a collection. 

Note :  A record in a MongoDB collection and the basic unit of data in MongoDB. Documents are analogous to JSON objects but exist in the database in a more type-rich format known as BSON.

Going beyond storing the BSON threshold limit , if one require to store say 100 MB or 2.5 GB  size of file [as in case of Video, Audio streaming files etc] then MongoDB provides a way to solve this challenge.  GridFS  API feature is one of the main  and  brilliant feature of MongoDB. Using this one can store any huge size of data as its stored the file into chunks of 255KB and store the file in the DB.


When to Use GridFS

In MongoDB, use GridFS for storing files larger than 16 MB.
In some situations, storing large files may be more efficient in a MongoDB database than on a system-level filesystem.
  • If your filesystem limits the number of files in a directory, you can use GridFS to store as many files as needed.
  • When you want to access information from portions of large files without having to load whole files into memory, you can use GridFS to recall sections of files without reading the entire file into memory.
  • When you want to keep your files and metadata automatically synced and deployed across a number of systems and facilities, you can use GridFS. When using geographically distributed replica sets, MongoDB can distribute files and their metadata automatically to a number of mongod instances and facilities.
Do not use GridFS if you need to update the content of the entire file atomically. As an alternative you can store multiple versions of each file and specify the current version of the file in the metadata. You can update the metadata field that indicates “latest” status in an atomic update after uploading the new version of the file, and later remove previous versions if needed.
Furthermore, if your files are all smaller the 16 MB BSON Document Size limit, consider storing the file manually within a single document instead of using GridFS. You may use the BinData data type to store the binary data. See your drivers documentation for details on using BinData.


Check the Max size of BSON  : We can check it on Mongo Shell by issuing following command

db.isMaster().maxBsonObjectSize/(1024*1024);


Enjoy the coding and MongoDB!!!

Friday, 7 October 2016

java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException

java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: 
Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext

Above exception occurs when we start the tomcat server and shows the state of conflicting of jars in the library or dependencies.

Usually adding  commons-digester3-3.2.jar from Apache Commons Digester. If you are using Maven you can add will solve the issue.
<dependency>
    <groupId>commons-digester</groupId>
    <artifactId>commons-digester</artifactId>
    <version>2.1</version>
</dependency>
But if your project having common.logging jars along with commons-digestor library 
this exception would again.

So you need to remove common.logging jars from the library or pom.xml from the project.

Same I have tried and worked perfectly  and tomcat was starting successfully.

Monday, 3 October 2016

Finding fibonacci number series in java


Fibonacci series : a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, 13,21,34 ,55,89 etc.

Solution1 using Recursion : 


/**code to get nth fibonacci number **/
public static int fibonacciNumbers(int n){
if(n <= 0 ||  n == 1){
return 1;
} else {
return fibonacciNumbers(n-1) + fibonacciNumbers(n-2);
  }
}
public static void main(String[] args){
int numberOfFibonacci = 15;
long start = System.currentTimeMillis();
java.util.List<Integer> fibnocList = new ArrayList<>();
for (int i = 0; i <= numberOfFibonacci; i++) {
fibnocList.add(fibonacciNumbers(i));
}
System.out.println(fibnocList);
long end = System.currentTimeMillis();
System.out.println("total time taken=" + (end -start)  +  " ms");
}
Output :
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
total time taken=1 ms
Note : Till 40th element its able to print fibonacci numbers after that time of execution
increase exponentially.
Time complexity is O(n) & Space complexity O(n).


Solution2 using  without Recursion : 



       
/**printing the series of fibonacci number upto length n  **/

public static void fibonacciSeries(int n){
int[] fibArray = new int[n];
if(n < 0 ){
System.out.println("invalid value");
} else {
  for (int i = 0; i < n; i++) {
  if(i== 0 || i==1){
  fibArray[i] =1;
  } else {
  fibArray[i] =  fibArray[i-1] + fibArray[i-2];
  }
}
  }
System.out.println("fibonacci number upto lenth n=" + n + " and series=" + Arrays.toString(fibArray));
}
public static void main(String[] args){
long start = System.currentTimeMillis();
fibonacciSeries(20);
long end = System.currentTimeMillis();
System.out.println("total time taken=" + (end -start)  +  " ms");
}
Note : Time complexity O(n) and space complexity is in place as using the arrays.
Output: 


fibonacci number upto lenth n=20 and series=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
233, 377, 610, 987, 1597, 2584, 4181, 6765]
total time taken=0 ms


In both the solutions number 2 solutions is best possible solution with respect to time and space complexity.

Enjoy the code and enjoy the journey of Java!!!!

Sunday, 2 October 2016

Finding all permutations of a String in Java


There are many ways of finding the permutations of a string . From the mathematics point of view there can be n! permutations where n is number of  character in the string.

Solution1  :

Use recursion.
  • Try each of the letters in turn as the first letter and then find all the permutations of the remaining letters using a recursive call.
  • The base case is when the input is an empty string the only permutation is the empty string.

       
public static void perm(String s){
if(s ==null || s.isEmpty()){
return;
}
perm("", s);
}
public static void perm(String prefix , String s){
if(s.length() == 0){
System.out.println(prefix);
} else {
int stringLength = s.length();
for (int i = 0; i < stringLength; i++) {
perm(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1));
}
}
}
public static void main(String[] args){
perm("abc");
}
output :
abc
acb
bac
bca
cab
cba
Time Complexity would be : O(n*n!) as for each element you required n-1 permutations of the
string so overall n! permutations.
Space complexity would be : O(n)
Note 2: Time taken to execute the method for various length of string:

for n=10 and 10!=3628800 number and total time taken to complete the output is = 93.31 sec
for n=9 and 9!=362880 number and total time taken to complete the output is = 6.312 sec
for n=8 and 8!=40320 number and total time taken to complete the output is = 365 ms
for n=7 and 7!=5040 number and total time taken to complete the output is = 92 ms
for n=6 and 6!=720 number and total time taken to complete the output is = 43 ms
for n=5 and 5!=120 number and total time taken to complete the output is =4 ms
for n=4 and 4!=24 number and total time taken to complete the output is = 1 ms
for n=3 and 3!=6 number and total time taken to complete the output is = 1 ms
for n=2 and 2!=2 number and total time taken to complete the output is = 0 ms

Solution2 :
Use recursion and swapping.
  • Try each of the index in turn as the current index and then find all the permutations of the remaining letters using a recursive call and swapping the element to the current index.
  • The base case is when the input  is an 0 index the only permutation is the permutated string.

private static void doPerm(StringBuffer str, int index){
    if(index <= 0)
        System.out.println(str);          
    else {
    int n = str.length();
        int currPos = n-index;
doPerm(str, index-1);
        for (int i = currPos+1; i < n; i++) {
            swap(str,currPos, i);
            doPerm(str, index-1);
            swap(str,i, currPos);
        }
    }
}
private  static void swap(StringBuffer str, int pos1, int pos2){
    char t1 = str.charAt(pos1);
    str.setCharAt(pos1, str.charAt(pos2));
}
public static void main(String[] args){
long start = System.currentTimeMillis();
String str = "abcd";
StringBuffer strBuf = new StringBuffer(str);
    doPerm(strBuf,str.length());
long end = System.currentTimeMillis();
System.out.println("total time taken=" + (end -start)  +  " ms");
}
Time Complexity would be : O(n*n!) as for each element you required n-1 permutations of the
string so overall n! permutations.But the use of String buffer and in memory swapping
the elements reduces the execution time.
Space complexity would be : O(n)
Note 2: Time taken to execute the method for various length of string:

for n=10 and 10!=3628800 number and total time taken to complete the output is = 33.31 sec
for n=9 and 9!=362880 number and total time taken to complete the output is = 3.312 sec
for n=8 and 8!=40320 number and total time taken to complete the output is = 185 ms
for n=7 and 7!=5040 number and total time taken to complete the output is = 42 ms
for n=6 and 6!=720 number and total time taken to complete the output is = 13 ms
for n=5 and 5!=120 number and total time taken to complete the output is =4 ms
for n=4 and 4!=24 number and total time taken to complete the output is = 1 ms
for n=3 and 3!=6 number and total time taken to complete the output is = 1 ms
for n=2 and 2!=2 number and total time taken to complete the output is = 0 ms
This solution is seems to be more  optimal solution as compare to solution 1.So 
highly recommended. 

solution 1 & solution 2 are taking same time upto 5 elements in the string but as we grow larger say upto 10 characters , solution 2 fit the most with respect to the time complexity and taking 1/3rd time as compare to solution1. It uses the technique to swap the elements in memory and use of string buffer reduces the time.
Solution 2 is highly recommended for finding the permutations of the string.

Two solutions are being mentioned and compare with the time . Clearly 2nd solution is much more optimal solution and its uses in memory swapping the element and making permutation of the other string excluding the current index character. Above two solutions gives all the permutations of a string while to remove the duplicates output need to be write in a Set to avoid any duplicates.

Solution 3 without recursions and without duplicates :  



      
public static Set<String> generatePermutation(String input){
Set<String> set = new HashSet<String>();
if(input == null){ return null; }
if (input == "") {return set;}
Character a = input.charAt(0);
if (input.length() > 1){
input = input.substring(1);
Set<String> permSet = generatePermutation(input);
for (String x : permSet){
for (int i = 0; i <= x.length(); i++) {
set.add(x.substring(0, i) + a + x.substring(i));
}
}
} else {
set.add(a + "");
}
return set;
}
public static void main(String[] args){
long start = System.currentTimeMillis();
String str = "AACC";
System.out.println(generatePermutation(str));
long end = System.currentTimeMillis();
System.out.println("total time taken=" + (end -start)  +  " ms");
}
Output :
[CACA, ACAC, ACCA, AACC, CCAA, CAAC]
total time taken=1 ms
Note : No duplicates are in the output and this is the most optimal solution for
finding the permutations  of a string.       
 


Enjoy coding and enjoy Java!!!!!

Tuesday, 30 August 2016

Virus affected folder having files is not displaying - How to see the files on Windows


In case of virus affected folders are many time doesn't show the content in the folder. If one open the folder properties then number of files are shown but on entering folder , no file is visible.

To resolve it following 2 steps are to be followed : 

1 .  Show hidden Files,Folders and Drives : 

Go to Control Panel  --> Appearance  and Personalization  --> Folder Options -- > Show hidden files and folders -- > Click on radio button [Show hidden files,folders and drives] 

Now all the hidden files , folders and drives would be visible.

In case of  files are still missing in the folder though size of the folder is showing number of files present in the folder --> follow the step2 

2. Displaying the hidden files of the folder due to affect of  Virus : 

a ) Use some antivirus to scan the folder to clean up the virus.
b)  Go to Start --> Run --> Type cmd and press Enter.

Assuming your drive letter as F: where a folder is affected by virus and folder is not displaying any files though they are exist in the folder.

Copy this command :

attrib -h -r -s /s /d f:\*.*

copy the above command --> Right-click in the Command prompt to paste it --> Enter

Now check your drive for the files in the folder -- > It will display entire files in the folder.

Enjoy the virus free access of the files in your drives. Don't forget to protect your system with an antivirus.

Friday, 12 August 2016

Generating the Pdf from HTML

Generating PDF from PDF template is a time & memory consuming process. It's sometime not feasible to use it while processing larger data set.

One of the very good features of creating PDF using HTML is appropriate and simple to use and easy to maintain.

There are many libraries are available for reference  PDF library link 

I will be discuss here itextpdf library of creation as it is simple and easy to maintain. For the Maven based project pom entry :

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->    
<dependency>
    &lt;d&gt;<groupid>com.itextpdf</groupid>
    <artifactid>itextpdf</artifactid>
    <version>5.5.9</version>
</dependency>
   
 

Following is the code snippet to use for conversion of html into pdf :
import com.itextpdf.text.Document;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfWriter;
@SuppressWarnings("deprecation")
public static void createPDFUsingHtml(String htmlFilePath,String outputPDFFilePath){
try {
Document document = new Document();
OutputStream file = new FileOutputStream(outputPDFFilePath);
PdfWriter writer = PdfWriter.getInstance(document,file );
///if want to keep password encrypted then add password here else passwordless pdf will be created
writer.setEncryption("".getBytes(), "".getBytes(),PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
String htmlcontent = readFile(htmlFilePath);
htmlWorker.parse(new StringReader(htmlcontent));
document.close();
} catch (Exception e)
{
e.printStackTrace();
}
}

When run a main  program on the html  test.html


   
public static void main(String[] args){
createPDFUsingHtml("/Users/test/test.html", "/Users/test/test.pdf");
}

Output of the created pdf : test.pdf

Your PDF is ready with a very  simple way and doesn't require any extra effort of creation of the pdf template. Instead just make a simple HTML  template which can be created from any online tool .
Just make your html ready and then your PDF will be created immediately.

Enjoy Coding !!!!



Wednesday, 10 August 2016

Reading file in Java


Reading file data is something used day to day life of a developer. Java had continuously  worked on the improvisation of file reading and writing as these are heavy process sometime and memory consuming.

Lets take case by case :

1. Reading a file data using FileReader : 

Method to used :

public static String readFile(String filePath) {
  StringBuilder sb = new StringBuilder();
  BufferedReader br = null;
  try {
   br = new BufferedReader(new FileReader(filePath));
   String line = br.readLine();
   while (line != null) {
    sb.append(line);
    sb.append("\n");
    line = br.readLine();
   }
  } catch(Exception e){
   e.printStackTrace();
  } finally {
   if(br!=null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return sb.toString();
 }   


2. Reading a file data using NIO: 

Method to used :

public static String readFileUsingNio(String filePath){
String content = null;
try {
content = new String(Files.readAllBytes(Paths.get(filePath)));
} catch (Exception e) {
e.printStackTrace();
}
return content;


There are other libraries available of apache common etc where utility of reading file is given.

But as an Architect I feel adding Non Blocking I/O  features in Java 7  is being one of the finest revolution in the I/O  operation . It is always recommended to use Java features are they are fully trusted and robust. Using lesser third party libraries is always advisable as lesser dependencies means lesser chances of getting the bug and code maintainability remains cleans.