Sunday, 14 December 2014

Linked List Implementaion in Java

In this post I want to share the Linked List implementation in Java. Primarily operations such as insert,delete,finding length,printing length of linked list is covered via different set of operations.

Insert and Delete method covers all 3 scenario which are
1. Insert/Delete at beginning 
2. Insert/Delete at end
3. Insert/Delete at middle

Here we use 2 classes to do this. Below is the ListNode.java file 

package abhishek.linkedlist;

public class ListNode {
private int data;
private ListNode next;
public ListNode(int data){
this.data=data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}

}

Following class LinkedListOperation will use ListNode to implement various operations supported by linked list

package abhishek.linkedlist;

public class LinkedListOperation {
static ListNode headnode;
public static void main(String[] args) {
insert();
System.out.println("Linked List After Insertion");
printlist();
delete();
System.out.println("Linked List After Delete");
printlist();
}
public static void insert(){
ListNode node = new ListNode(10);
headnode =inserttoll(headnode,node,1);
ListNode node1 = new ListNode(20);
headnode =inserttoll(headnode,node1,1);
ListNode node2 = new ListNode(30);
headnode =inserttoll(headnode,node2,1);
ListNode node3 = new ListNode(100);
headnode =inserttoll(headnode,node3,4);
ListNode node4 = new ListNode(50);
headnode =inserttoll(headnode,node4,4);
}
public static void delete(){
headnode = deletefrmll(headnode,1);
headnode = deletefrmll(headnode,2);
}
public static ListNode inserttoll(ListNode headnode,ListNode node,int p){
if(headnode==null)
return node;
int size = listlen(headnode);
if(p>size+1 || p<1){
System.out.println("Invalid Position Valid is 1 to "+(size+1));
return headnode;
}
if(p==1){
node.setNext(headnode);
return node;
}else {
ListNode prevNode = headnode;
int count =1;
while(count<p-1){
prevNode = prevNode.getNext();
count++;
}
ListNode currNode = prevNode.getNext();
node.setNext(currNode);
prevNode.setNext(node);
}
return headnode;
}
public static ListNode deletefrmll(ListNode headnode,int p){

int size = listlen(headnode);
if(p>size+1 || p<1){
System.out.println("Invalid Position Valid is 1 to "+(size+1));
return headnode;
}
if(p==1){
ListNode node = headnode.getNext();
headnode =null;
return node;
}else {
ListNode prevNode = headnode;
int count =1;
while(count<p-1){
prevNode = prevNode.getNext();
count++;
}
ListNode currNode = prevNode.getNext();

prevNode.setNext(currNode.getNext());
currNode = null;
}
return headnode;
}

public static int listlen(ListNode headnode){
int len = 0;
while(headnode!=null){
len++;
headnode = headnode.getNext();
}
return len;
}
public static void printlist(){
String str = "{";
ListNode lheadnode = headnode;  
while(lheadnode!=null){
str = str + lheadnode.getData() + " ";
lheadnode = lheadnode.getNext();
}
System.out.println(str.trim()+ "}");
}
}

Output for the above code is 

Linked List After Insertion
{30 20 10 50 100}
Linked List After Deletion
{20 50 100}


Saturday, 6 December 2014

Java Program to find factorial of a number using BigInteger Class

Below program showcase the use of BigInteger class in java to find factorial of a given number x. 
Few constraints are 
T is the no of testcases which is first line of input followed by t lines having single Integer n.
1<=t<=100.
1<=x<=100.

Given x in above range the number is very small. But when we take into account its factorial,neither int or long can hold the result for us .(Try finding factorial of 50 using int or long) 

It is here when BigInteger Class in java becomes handy. Try closer look how we perform various arithmetic operations differently. Here is the code

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;

/**
 *
 * @author Abhishek
 */
public class Factorial {
    public static void main(String[] args)throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String str=br.readLine();
                String str1;
                int n;
                int t = Integer.parseInt(str);
                if(t<1 ||t>100)
                {

                        System.exit(0);
                }
                BigInteger[] result = new BigInteger[t];

                for(int i=0;i<t;i++){
                        str1 = br.readLine();
                        n = Integer.parseInt(str1);
                        if(n<1 || n>100)
                        {

                                System.exit(0);
                        }
                        BigInteger bi = new BigInteger(str1);
                result[i] = Factorial.fact(bi);
                }
                for(BigInteger res:result){
                System.out.println(res);
        }
        }
 
   
 public static BigInteger fact(BigInteger pnum){
        BigInteger lfact;
     
        if(pnum==BigInteger.ZERO)
            return BigInteger.ONE;
        else
        {
            lfact=pnum.multiply(fact(pnum.subtract(BigInteger.ONE)));
        }
        return lfact;
}
}

Lets see the output for t=2 and x=100,99
2
100
99
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000

Are you surprised looking at the factorials of 99,100

Friday, 5 December 2014

Java program to find First Non Repeated Occurrence using lambda expressions

This following program illustrate 4 different ways to find solution to the above problem. we will get back to find solution using  lambda expressions through fourth function.
Remember to set compiler path as java 8.

  NonRepeated.find("abhishek") will get it through indexOf and lastindexOf build in functions.
  NonRepeated.findsec("learnNShare") NonRepeated.findsec("learnNShare") are same only      difference is we are using HashMap and LinkedHashMap  respectively which in our case is not  making any difference.

  Finally findfourth("letseethistimel", System.out::print); makes use of lambda expressions to arrive at  solutions without making  use of second loop or build in functions.

  For now the complexity of each function is left to user to find. I will work on same and update this     post in near future.

/**
 *
 */
package com.abhishek.string;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.function.*;
import java.util.stream.Collectors;
import static java.util.function.Function.identity;
/**
 * @author Abhishek
 *
 */

/*
 * Java program to find First Non Repeated Occurrence using lambda expressions
 *
package com.abhishek.string;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.function.*;
import java.util.stream.Collectors;
import static java.util.function.Function.identity;
public class NonRepeated {

public NonRepeated() {

}

public static void main(String[] args) {

try {

//Hard coding input to illustrate various methods
char ch = NonRepeated.find("abhishek");
Character ch1 = NonRepeated.findsec("learnNShare");
Character ch2 = NonRepeated.findthird("learnNShare");
System.out.print(ch+" "+ch1+" "+ch2+" ");

//using java 8 feature lambda expression
findfourth("letseethistimel", System.out::print);
} catch (Exception e) {

e.printStackTrace();
}

}
public static char find(String pstr){
for( char ch: pstr.toCharArray()){
if(pstr.indexOf(ch)==pstr.lastIndexOf(ch)){
return ch;
}
}
return '/';
}
public static Character findsec(String pstr){
int len = pstr.length();
Character ch ;
HashMap<Character,Integer> chmap = new HashMap<Character,Integer>();
for(int i=0;i<len;i++){
ch = pstr.charAt(i);
if(chmap.containsKey(ch))
chmap.put(ch, chmap.get(ch)+1);
else
chmap.put(ch, 1);

}
for(int i=0;i<len;i++){
ch = pstr.charAt(i);
if(chmap.get(ch)==1)
return ch;
}
return null;
}
public static Character findthird(String pstr){
int len = pstr.length();
Character ch = 'a';
LinkedHashMap<Character,Integer> chmap = new LinkedHashMap<Character,Integer>();
for(int i=0;i<len;i++){
ch = pstr.charAt(i);
if(chmap.containsKey(ch))
chmap.put(ch, chmap.get(ch)+1);
else
chmap.put(ch, 1);

}
for(int i=0;i<len;i++){
ch = pstr.charAt(i);
if(chmap.get(ch)==1)
return ch;
}
return ch;
}
public static void findfourth(String pstr, Consumer<Character> callback) {
pstr.chars()
.mapToObj(in -> Character.valueOf((char) in))
.collect(Collectors.groupingBy(identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(entry -> entry.getValue() == 1L)
.map(entry -> entry.getKey())
.findFirst().map(cnt -> { callback.accept(cnt); return cnt; } );
}
}

Output will be
a l l h


Tuesday, 2 December 2014

Input validation using OWASP ESAPI Library in Java

Small java project with single class to showcase how OWASP ESAPI can be used.

Here the input is read from JSON file which can be thought of as JSON request to web application in real time scenario.


1.     Project is maven converted . So the pom.xml will be as shown below
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>InputValidation</groupId>
       <artifactId>InputValidation</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <build>
              <sourceDirectory>src</sourceDirectory>
              <plugins>
                     <plugin>
                           <artifactId>maven-compiler-plugin</artifactId>
                           <version>3.1</version>
                           <configuration>
                                  <source>1.7</source>
                                  <target>1.7</target>
                           </configuration>
                     </plugin>
              </plugins>
       </build>
       <dependencies>
              <dependency>
                     <groupId>commons-codec</groupId>
                     <artifactId>commons-codec</artifactId>
                     <version>1.9</version>
              </dependency>
              <dependency>
                     <groupId>org.owasp.esapi</groupId>
                     <artifactId>esapi</artifactId>
                     <version>2.0_rc9</version>
              </dependency>
              <dependency>
                     <groupId>com.googlecode.json-simple</groupId>
                     <artifactId>json-simple</artifactId>
                     <version>1.1</version>
              </dependency>
       </dependencies>
</project>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
  (adsbygoogle = window.adsbygoogle || []).push({
    google_ad_client: "ca-pub-3320597435647728",
    enable_page_level_ads: true
  });

</script>
2.     In order to set regex pattern on which esapi works , it is required to supply ESAPI.properties and Validation.properties which can be found at below location
https://svn.apache.org/repos/asf/ofbiz/tags/REL-12.04.02/framework/base/config/ESAPI.properties
https://svn.apache.org/repos/asf/sling/tags/org.apache.sling.xss-1.0.6/src/main/resources/validation.properties
Note we need to place these in project resource folder. With same name . We can change these files as per or need.
3.     Simple JSON fed input has below content.
{
                                "userId":"select * from dual"
}

4.     Java program to validate this JSON input through OWASP api is below
package com.valid;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Validator;

public class StringValidation {
       private static final String filePath ="E:\\Abhishek\\Imp\\testjson.json";
       public StringValidation()  {
       }
       public static void main(String[] args) throws IOException {
              String luserId = null;
              try {
                     FileReader reader = new FileReader(filePath);

                     JSONParser jsonParser = new JSONParser();

                     JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
                     luserId = (String) jsonObject.get("userId");
              }
              catch (FileNotFoundException ex) {
                     ex.printStackTrace();
              } catch (IOException ex) {
                     ex.printStackTrace();
              } catch (ParseException ex) {
                     ex.printStackTrace();
              } catch (NullPointerException ex) {
                     ex.printStackTrace();
              }
              Validator lvalidator = ESAPI.validator();
              boolean lstatus = lvalidator.isValidInput("userInput", luserId, "SafeString", 100 , false);
              if(lstatus){
                     System.out.println("Proceed");
              }else
              {
                     System.out.println("Something Fishy");  
              }
       }
}
5.      Output for above code is as below
Attempting to load ESAPI.properties via file I/O.
Attempting to load ESAPI.properties as resource file via file I/O.
Found in 'user.home' directory: C:\Users\..\esapi\ESAPI.properties
Loaded 'ESAPI.properties' properties file
Attempting to load validation.properties via file I/O.
Attempting to load validation.properties as resource file via file I/O.
Found in 'user.home' directory: C:\Users\..\esapi\validation.properties
Loaded 'validation.properties' properties file
Dec 02, 2014 2:09:49 PM org.owasp.esapi.reference.JavaLogFactory$JavaLogger log
WARNING: [SECURITY FAILURE Anonymous:null@unknown -> /DefaultName/IntrusionDetector] Invalid input: context=userInput, type(SafeString)=^[.\p{Alnum}\p{Space}]{0,1024}$, input=select * from dual
org.owasp.esapi.errors.ValidationException: userInput: Invalid input. Please conform to regex ^[.\p{Alnum}\p{Space}]{0,1024}$ with a maximum length of 100
       at org.owasp.esapi.reference.validation.StringValidationRule.checkWhitelist(StringValidationRule.java:144)
       at org.owasp.esapi.reference.validation.StringValidationRule.checkWhitelist(StringValidationRule.java:160)
       at org.owasp.esapi.reference.validation.StringValidationRule.getValid(StringValidationRule.java:284)
       at org.owasp.esapi.reference.DefaultValidator.getValidInput(DefaultValidator.java:214)
       at org.owasp.esapi.reference.DefaultValidator.isValidInput(DefaultValidator.java:152)
       at org.owasp.esapi.reference.DefaultValidator.isValidInput(DefaultValidator.java:143)
       at com.valid.StringValidation.main(StringValidation.java:53)

SecurityConfiguration for ESAPI.Authenticator not found in ESAPI.properties. Using default: org.owasp.esapi.reference.FileBasedAuthenticator
Something Fishy
So in this way we validated a malformed user input.