Thursday 15 May 2014

Stemming English words in Java with Netbeans

Hi..
 Here I have shared the java code for stemming the english words . This code reduces the inflected (or sometimes derived) words to their stem, base or root form, eg: information->inform. All you need to do is to make use of the attached .jar file in your netbeans library and run the code.

Procedure:

1. Create a new Java Application Project in Netbeans.

2. Add the JAR file attached "org.tartarus.snowball"(download link at bottom) to the Netbeans Project Library.

3. Use the following code and make changes wherever needed (Eg. Input file name, Output file name, Path etc)

import java.io.*;
import java.util.regex.Pattern;
import java.util.Scanner;
import org.tartarus.snowball.*;

public class EnglishStemmer_porterstemmer {

public static void main(String[] args) throws Exception{
        String a,s,line,token;
        //read the input file
 FileReader file_to_read=new FileReader("C:/sample.txt"); // you can change file path.
 
    Scanner filesc=new Scanner(file_to_read);//scanner for file
    FileWriter fstream = new FileWriter("C:/sample_stem_out.txt");  // after run, you can see the output file in the specified location
    BufferedWriter out = new BufferedWriter(fstream);
 
    while(filesc.hasNextLine())
    {
    line=filesc.nextLine();
    Scanner linesc=new Scanner(line);//scanner for line
 
        while(linesc.hasNext())
        {
         token=linesc.next();
         a=EnglishSnowballStemmerFactory.getInstance().process(token);//method to access the porter stemmer for english
         out.write(a);
         out.write(" ");
        }
        out.newLine();
        linesc.close();
    }
    filesc.close();
   // a=EnglishSnowballStemmerFactory.getInstance().process("information");
    //System.out.println(a);
    }
}


4. Run the example program provided to understand the usage.



.Jar file Link:
https://drive.google.com/file/d/0B6sz85c3IPh9RWdlVTNndU1CcWc/edit?usp=sharing.

Sample Input and output:
https://drive.google.com/file/d/0B6sz85c3IPh9TEtqMVdQZ1VpSG8/edit?usp=sharing
https://drive.google.com/file/d/0B6sz85c3IPh9Y2JsUm14aTE4QWs/edit?usp=sharing

Wednesday 14 May 2014

Interview Java Programs solved

1. Find the count of largest common subsequence in the given two strings.
Eg. "Hetlloxhihi" , "jeyllorhiki"
largest common sequence is "llo".
So output is 3.

public class longestcommonsub {
    
    public static void main(String args[])
    {
        char arr1[]="howareue".toCharArray();
        char arr2[]="howsocrue".toCharArray();
        int count2=0,count1=0;
        int j=0,k=0;
        for(int i=0;i<arr1.length;i++)
        {   
            if(count2==count1)
            {
            j=k;
            }
            else
            {
                count2=count1;
            }
            while(j<arr2.length)
            {
                if(arr1[i]==arr2[j])
                {
                count1++;
                    j++;
                    k=j;
                    break;
                }
                else
                    j++;
            }
        }
        System.out.println("output is" +count1);
        
    }
}


output:

output is 5.


2. Find the Count of largest increasing sequence of number in the given array of number.
       Eg. input: 0,2,13,4,6,5
            Output : 4 ( bcoz - 0,2, 4,5)

public class LogestSeq {
 
    public static void main(String args[])
    {
        int arr[]=new int[]{0,2,13,4,6,5};
        int arr1[]=new int[15];
       int temp;
        int len=arr.length;
        int pos=0;
        for(int i=0;i<len;i++)
        {
            arr1[i]=arr[i];
        }
         for(int i=0;i<len;i++)
        {
            for(int j=0;j<len;j++)
            {
               if(arr1[i]<arr1[j])
               {
                   temp=arr1[i];
                   arr1[i]=arr1[j];
                   arr1[j]=temp;
               }
                 
            }
        }
         for(int i=0;i<len;i++)
             System.out.print(arr[i]+",");
         System.out.print("\n");
         // for(int i=0;i<len;i++)
            // System.out.print(arr1[i]+",");
        int count=0,j,max=1;
        //j=arr[0];
        for(int k=0;k<len;k++)
        {
        for(int i=k;i<len;i++)
        {
            temp=arr1[i];
            for(j=0;j<len;j++)
            {
                if(temp==arr[j])
                {
                    break;
                }
                 
            }
         
            if(j>=pos)
            {
               count++;
            pos=j;
            }
        }
        if(count>max)
        {
            max=count;
            count=0;
        }
        }
       System.out.println("\n"+max);
     
    }
}


Output: 
4

3. Program to find the  maximum count of number of continuously occurring character in the given string.

For eg.

Input : " aaaxxbbbbbyyyy"
Output: "5

public class max_letter {
    public static void main(String args[])
    {
        char arr[]=new char[100];
        String x="hhee@@@iiiiiii";
        arr=x.toCharArray();
        int len=arr.length;
        int i=0,count=1,index=0,max=0;
        while(i<len-1)
        {
         
            if(arr[i]==arr[i+1])
            {
                count++;
                if(i==len-2)
                {
                if(max<count)
                {
                    max=count;
                    count=1;
                    index=i;
                 
                }
                }
            }
            else
            {
                if(max<count)
                {
                    max=count;
                    count=1;
                    index=i;
                 
                }
            }
             
         
         
            i++;
         
        }
        System.out.println("max="+max+"letter="+arr[index]);
}
}

output: max=7   letter=i


4. Program to find the longest substring in the given line of string.

Eg. Input:   " Hi i am sangeeth"
      Output: sangeeth   ( as sangeeth is of 8 length)

public class strnl {
    
    public static void main(String args[])
    {
        String arr="Hell hr are umberlajhj";
        char arr1[];
        arr1=arr.toCharArray();
        int i=0,max=0,count=0,index=0;
        //System.out.println(arr1.length);
        while(i<arr1.length)
        {
            if(arr1[i]!=' ' )
            {
                i++;
                count++;
                if(i==arr1.length-1)
                {
                 if(max<count)
                {
                    max=count+1;
                    index=i-count;
                }
                }
            }
            else if(arr1[i]==' ')
            {
                if(max<count)
                {
                    max=count;
                    index=i-count;
                }
                count=0;
                i++;
            }
                         
        }
System.out.println("max="+max);
for(int j=0;j<max;j++,index++)
    System.out.print(arr1[index]);

    }
    }
output: max=10
             umberlajhj

5. Find the Nth Largest number in the given set of Array.

ex. Input : { 32,2,100,7,3}
N= ? = 3.
OUTPUT: 7 ( 3RD LARGEST NUMBER)

public class NthLarge {
    public static void main(String args[])
    {
        int arr[]=new int[]{1,45,6,3,99,100,1000,409};
        int n,max=0,j=0;
        int temp=0;
        Scanner in=new Scanner(System.in);
        System.out.println("Enter the Nth value");
        n=in.nextInt();
        while(j<n)
        {
            max=arr[0];
         
            for(int i=0;i<arr.length;i++)
            {
            if(j==0)
            {
                if(arr[i]>max)
                    max=arr[i];
            }
            else
            {
                if(arr[i]>max && arr[i]<temp)
                    max=arr[i];
            }
             
            }
            temp=max;
         
            j++;
        }
        System.out.println("max="+max);
    }
}

Output:
Enter the Nth value
3

max=100

6. Print the numbers of array in the given order after partitioning it in the given size.
// enter partition in array. then partition order to print output.
// eg. 12345 - size =2 , partiton={12},{34},{5} .order = 3,2,1=> o/p => 53412

import java.util.Scanner;


public class Programming {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
         int arr[]=new int[10];
         System.out.println("Enter size and then array elements");
         Scanner in=new Scanner(System.in);
         double h=(double)in.nextInt();
       for(int i=0;i<(int)h;i++)
       {
         arr[i]=i+1;
       }
       int arr2[]=new int[6];
     
      int p,q;
      q=in.nextInt();
      double x=Math.ceil(h/q);
      System.out.println(x);
   
       System.out.println("enter order up to"+(int)x);
      for(int i=0;i<(int)x;i++)
      {
       
          arr2[i]=in.nextInt();
      }
       //System.out.println("enter order");
      int intx=(int)x;
       int temp=(intx*q)-q;
       for(int i=0;i<intx;i++)
       {
         int j=arr2[i];
        p=((j*q)-q);
        //System.out.println("j="+j+" p="+p);
     
          if(p==temp && (((int)h%q)!=0))
          {
        for(int k=0;k<((int)h%q);k++)
        {
              System.out.print(arr[p++]);
        }
       
           }
          else
          {
        for(int k=0;k<q;k++)
        {
              System.out.print(arr[p++]);
        }
       }
System.out.println("-");
    }
    }
 
}

output: 

Enter size and then array elements are assigned automatically
8
Enter partitoning size
3
enter order up to3
3
1
2
78-
123-
456-

7. Remove the even elements in the given array by replacing it with zeros and print the modified sequence by moving zero to tail.

Input: 1 ,2 ,4, 5,7
Output: 15700

public class even_rem {
    public static void main(String args[])
    {
        int arr[]=new int[100];
        int len;
        int i,j=0;
        Scanner in=new Scanner(System.in);
        System.out.println("Enter no of elements");
        len=in.nextInt();
        for(i=0;i<len;i++)
          arr[i]=in.nextInt();
        for(i=0;i<len;i++)
        {            
           if(arr[i]%2==0)
            {
                arr[i]=0;
             
             }
            else
            {
                arr[j]=arr[i];
                if(i!=j)
                {
                 arr[i]=0;
                }
                 j++;
            }
     
        }
         for(i=0;i<len;i++)
        {
           System.out.print(arr[i]);
        }
    }
}

8.  Print the matrix in spiral pattern.

public class spiralArray {
   
    public static void main (String[] args)
    {
        System.out.println("hello");
        int arr[][]=new int[25][25];
        int i,j;
        Scanner in=new Scanner(System.in);
        System.out.println("Enter no of elements- 3 or 5 or 7");
        int len=in.nextInt();
        for(i=0;i<len;i++)
        {
            for(j=0;j<len;j++)
            {
                arr[i][j]=(i+1)*(j+1);
                     
             }
        }
        System.out.println("Array elements");
        for(i=0;i<len;i++)
        {
            for(j=0;j<len;j++)
            {
                System.out.print(arr[i][j]+" ");
                     
             }
            System.out.println();
        }
        i=len/2;
        j=len/2;
        int count=1;
        System.out.println("Spiral print");
         System.out.println(arr[i][j]);
         
        while(i!=0&&j!=0)
        {
         j--;count=count*2;
        for(int ctr=0;ctr<count;ctr++,i++)
        {
        System.out.print(arr[i][j]+" ");
       
        }
        i--;j++;
        System.out.println("...");
       
       // System.out.println("i"+i+",j"+j);
       
       for(int ctr=0;ctr<count;ctr++,j++)
        System.out.print(arr[i][j]+" ");
         System.out.println("...");
         i--;j--;
        // System.out.println("i"+i+",j"+j);
       
         for(int ctr=0;ctr<count;ctr++,i--)
        System.out.print(arr[i][j]+" ");
         System.out.println("...");
         i++;j--;
        // System.out.println("i"+i+",j"+j);
       
        for(int ctr=0;ctr<count;ctr++,j--)
        System.out.print(arr[i][j]+" ");
         System.out.println("...");
         j++;
         //System.out.println("i"+i+",j"+j);
    }
    }
   
}

Enter no of elements- 3 or 5 or 7
5
Array elements
1 2 3 4 5 
2 4 6 8 10 
3 6 9 12 15 
4 8 12 16 20 
5 10 15 20 25 

Spiral print
9
6 8 ...
12 16 ...
12 8 ...
6 4 ...
2 3 4 5 ...
10 15 20 25 ...
20 15 10 5 ...
4 3 2 1 ...

Thursday 2 January 2014

Simple Web service with Net beans 6.8 and above

Here is the procedure to create a simple web service to understand how it works for a beginner or for a college student to do a basic exercise on java webservices using NetBeans IDE. I have used Netbeans 7.4 to create this and tested the same with netbeans 6.8 to 7.4 ( april 2014).

Requirement:
1.Install netbeans 6.8 full package with included glassfish server or tomcat server.
Link: https://netbeans.org/downloads/
2. Basic Java programming skills and to know to work with Netbeans.


STEP BY STEP PROCEDURE(VERY SIMPLE):

1. Open Netbeans IDE and go to File -> New Project -> Java Web & Web Application.
2.Provide a Name for the project (say for SampleWebService) and give next to complete the wizard.
   (Either tomcat or glassfish server must be selected as default) and if not download, install and retry).
3.Right click the ProjectName(SampleWebService)->New->Java Package
4.Enter name for Package( say for SamplePackage) and click Finish to close the wizard.
5.Right click the Source Package under Project Tab and select New->Other.
6.A new window opens. In that, under Categories-> Web Services and under File Types->Web Service and click Next.



7.Enter WebServiceName(E.g Calculator) and PackageName (as SamplePackage) and click Finish.

Once these are done, You would see something like this .


8.From WebService under ProjectTab right click Addition(Calculator)->Add Operation.
9.Under Add Operation dialog box enter Name(E.g Addition) and Return Type( as int) or  from Browse Tab.
10.Under Parameters Tab click Add tab to add variables.
11.Select Name and Type for the variables.For e.g. to add numbers add variables a and b and their type as Integer.



12. Click Ok and close the window.
13.Add the necessary code in the java file for calculation of numbers.



14.Now right click the SampleWebService and Deploy.
Its done!!
15.Create a simple servlet "myservs" in separate java package (eg."servs") which you will be using the calculator webservices.

TESTING THE WEBSERVICE:

15.To test the webservice right click the Calculator(WebService) ->Test WebService.
16.Enter numbers for calculation to test the web service.
17. Once the test is passed, web service is ready. 



NOTE: You can create the web service alone in separate application also and use it in your current web application.

Reference to web service:
18. Now you need to create the Web Service client  i.e a reference to the originally created web service . You can access the service only through references.
19. Right click on the web application project(SampleWebService) -> New -> Other-> and under web services , click on web service client.
20.Under WSDL and Client Location, Choose the project button and browse for the web service you want to make use of (Eg.SampleWebService->Calculator)  and enter some different package name(eg.mypack) .Then click finish. The web service could be from same project or different project.
21. You will see a "Web Service References" node in project tree . Expand it to see the service( function ) you want to use in your web or POJO application.
22. Just drag and drop the the service "Addition"(RedColor) under CalculatorPort to the servlet window(eg. here its "myservs") right side. You do not need to type any code as you will see that a new module Addition added in servlet code area where the service is called using a port object.
23. All you need to do is - make a call to the function passing necessary parameter( two numbers in this example .eg. addition(1,2))  from your servlet code.


24. Create a JSP call to servlet (eg. a simple href link to servlet to test) .Now DEPLOY AND RUN THE APPLICATION. Its done.




Please share your difficulties or error in the comment.

NOTE TO EXPERTS: I have given simple way of using webservice in java netbeans for beginners. Kindly ignore if there is any technical mistake and please make a comment to let me know about it.