Tuesday, September 22, 2015

Maven How to add multiple source


If you have a project folder where you have multiple source directory something like

Then you need to include all the source folder into your maven's pom.xml
The easiest way to do is to include the below xml structure into your pom.xml


<project>
 <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>1.7</version>
        <executions>
          <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>add-source</goal>
            </goals>
            <configuration>
              <sources>
                <source>your source folder 1</source>
                <source>your source folder 2</source>
<source>your source folder 3</source>
              </sources>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

and then install







Monday, September 21, 2015

Setting Up A GitHub Project in Eclipse


What is GitHub
In a very simple term GitHub is a repository where you keep your project code on cloud.



Why you need a GitHub account ?
Suppose you have two computers where you do your programming stuff. Unless you have a gitHub repository set in both the computers Eclipse workspace are not in sync, you can manually sync them by copying the workspace content from one computer to the other with some kind of USB drive (which is a dirty way). You will also find GitHub important when you what to set your project environment to a third computer or you want someone to contribute in your project at the same time follow the project structure you have defined.

You can set up Git Hub repository for you Eclipse java project in 3 ways
1. Through Git Hub Desktop
2. Through Eclipse Egit plugin and using eclipse UI menu
3. Through Eclipse Egit plugin and using git console <command line>

Here mostly I will be covering the point # 2

Before we begin the very first step would be to open a free git hub account. To open your free account please visit https://github.com/

STEPS TO CONFIGURE YOUR EXISTING ECLIPSE JAVA PROJECT AS A GIT REPOSITORY PROJECT


  • Download the Git Eclipse plugin from eclipse market place


  • On your already created eclipse project right click and select share project. Now your project becomes a git project without a head

  • Once you click on share project you see a screen like this, on the window select "use or create repository" And finally click create repository and finish.


  • Now your existing Java project is turned into a git repository but with no HEAD and will look like this



  • Next step is to right click on your project, select team and select "Show repository view.


  • Select Show in repository view.

  • On the next screen select create remote. Enter the default name as 'origin' .


  • Select to configure Push or Pull. 

  • Now configure Push and Pull for the repository.Enter the URI from the git repository you have created. Finally click Finish.





  • At this point you should be all set to push your content to the Git repository or to pull content from the Git repository
  • Point to remember here - Before you make a push request to the repository to check in your existing project content into the main branch, open the git repository account and create a readme / or any file into the repository. Once you are done with that from the Eclipse project make a Pull request to pull the new file you have created in the repository. Now you are ready to make a push request.
  • Before push make sure you commit the files you want to check in 






  • At this point you should be all set to make further commit and Push to main branch and fetch from main branch. To configure Eclipse with Git on 2nd computer first clone the repository and the follow the similar steps.





Friday, September 18, 2015

Java Comparable interface example




 package CollectionFramework;  
 public class OFruit implements Comparable<OFruit> {  
      String name;  
      String colour;  
      int quantity;  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
      public String getColour() {  
           return colour;  
      }  
      public void setColour(String colour) {  
           this.colour = colour;  
      }  
      public int getQuantity() {  
           return quantity;  
      }  
      public void setQuantity(int quantity) {  
           this.quantity = quantity;  
      }  
      @Override  
      public int compareTo(OFruit fruit) {  
           return this.name.compareTo(fruit.getName());  
      }  
 }  



 package CollectionFramework;  
 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 public class ObjectSort {  
      public static void main(String[] args) {  
           // Comparable and Comparator interfaces  
           new ObjectSort().comparable();  
      }  
      public void comparable() {  
           OFruit fruit1 = new OFruit();  
           fruit1.setName("Palm");  
           fruit1.setColour("Red");  
           fruit1.setQuantity(10);  
           OFruit fruit2 = new OFruit();  
           fruit2.setName("Banana");  
           fruit2.setColour("Green");  
           fruit2.setQuantity(15);  
           OFruit fruit3 = new OFruit();  
           fruit3.setName("Orange");  
           fruit3.setColour("Yellow");  
           fruit3.setQuantity(20);  
           OFruit fruit4 = new OFruit();  
           fruit4.setName("StarFruit");  
           fruit4.setColour("Green");  
           fruit4.setQuantity(2);  
           List<OFruit> list = new ArrayList<OFruit>();  
           list.add(fruit1);  
           list.add(fruit2);  
           list.add(fruit3);  
           list.add(fruit4);  
           // Collections.shuffle(list);  
           Collections.sort(list);  
           for (int i = 0; i < list.size(); i++) {  
                System.out  
                          .println(list.get(i).getName() + '\t' + list.get(i).getColour() + '\t' + list.get(i).getQuantity());  
           }  
      }  
 }  

Micro Controller - Arduino - Holiday Light

Yet to add descriptions

At High Level this is a DIY construction of Holiday Light using Micro controller ATMEG 328/Popularly known as ARDUINO 



Java ArrayList sort examples use of Comparator interface

Example 01

 package CollectionFramework;  
 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.Comparator;  
 import java.util.Iterator;  
 import java.util.List;  
 public class ArrayLists {  
      public static void main(String[] args) {  
           Students student1 = new Students("John", "two", "abc", 12);  
           Students student2 = new Students("Allen", "two", "abc", 12);  
           Students student3 = new Students("bob", "three", "abc", 15);  
           Students student4 = new Students("amanda", "Four", "abc", 16);  
           Students student5 = new Students("Dave", "five", "abc", 16);  
           List<Students> studentList = new ArrayList<Students>();  
           studentList.add(student1);  
           studentList.add(student2);  
           studentList.add(student3);  
           studentList.add(student4);  
           studentList.add(student5);  
           studentList.add(new Students("sudas", "twelve", "XyZ", 21));  
           // studentList.sort(null);  
           Collections.sort(studentList, new Comparator<Students>() {  
                @Override  
                public int compare(Students o1, Students o2) {  
                     return o1.getName().compareToIgnoreCase(o2.getName());  
                }  
           });  
           Iterator<Students> sList = studentList.iterator();  
           while (sList.hasNext()) {  
                System.out.println(sList.next().getName());  
           }  
      }  
 }  
 class Students {  
      String name;  
      String grade;  
      String address;  
      int age;  
      public Students(String name, String grade, String address, int age) {  
           this.name = name;  
           this.grade = grade;  
           this.address = address;  
           this.age = age;  
      }  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
      public String getGrade() {  
           return grade;  
      }  
      public void setGrade(String grade) {  
           this.grade = grade;  
      }  
      public String getAddress() {  
           return address;  
      }  
      public void setAddress(String address) {  
           this.address = address;  
      }  
      public int getAge() {  
           return age;  
      }  
      public void setAge(int age) {  
           this.age = age;  
      }  
 }  

Example 02

 package CollectionFramework;  
 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.Comparator;  
 import java.util.List;  
 public class ComparatorExample {  
      public static void main(String[] args) {  
           String s1 = "Logitech";  
           String s2 = "Microsoft";  
           String s3 = "cooler Master";  
           String s4 = "Creative";  
           String s5 = "Zebronics";  
           String s6 = "iBall";  
           List<String> arrayList = new ArrayList<String>();  
           arrayList.add(s1);  
           arrayList.add(s2);  
           arrayList.add(s3);  
           arrayList.add(s4);  
           arrayList.add(s5);  
           arrayList.add(s6);  
           /*  
            * as long as all the names have same case the starting alphabet the  
            * sort method works Collections.sort(arrayList);  
            */  
           Collections.sort(arrayList, new Comparator<String>() {  
                @Override  
                public int compare(String s1, String s2) {  
                     return s1.compareToIgnoreCase(s2);  
                     // return 0;  
                }  
           });  
           for (int i = 0; i < arrayList.size(); i++) {  
                System.out.println(arrayList.get(i));  
           }  
      }  
 }  

Java compare the content of Array and ArrayList





 package sudas.study.example.one;  
 import java.util.ArrayList;  
 import java.util.Arrays;  
 import java.util.Collection;  
 import java.util.Collections;  
 import java.util.List;  
 public class CompareDataStructure {  
      public static void main(String[] args) {  
           CompareDataStructure compare = new CompareDataStructure();  
           compare.compareArray();  
           compare.compareArrayList();  
      }  
      // Method to compare content of ARRAYS  
      public void compareArray() {  
           String fruits1[] = { "Apple", "Banana", "Orange" };  
           String fruits2[] = { "Apple", "Banana", "Orange" };  
           if (Arrays.equals(fruits1, fruits2)) {  
                System.out.println("Content of Array SAME");  
           }  
           else{  
           System.out.println("Content of Array DIFFERs");  
      }  
      }  
      public void compareArrayList() {  
           List<String> arrayList1 = new ArrayList<String>();  
           List<String> arrayList2 = new ArrayList<String>();  
           String fruits1[] = { "Apple", "Banana", "Orange" };  
           String fruits2[] = { "Apple", "Banana", "Palm" };  
           for (int i = 0; i < fruits1.length; i++) {  
                String fruit = fruits1[i];  
                arrayList1.add(i, fruit);  
           }  
           for (int i = 0; i < fruits2.length; i++) {  
                String fruit = fruits2[i];  
                arrayList2.add(i, fruit);  
           }  
           // compare array lists  
           if (arrayList1.equals(arrayList2)) {  
                System.out.println("Content of ArrayList SAME");  
           } else {  
                System.out.println("Content of ArrayList DIFFERs");  
           }  
      }  
 }  
Output 
 Content of Array SAME 
Content of ArrayList DIFFERs

Monday, September 14, 2015

Java find if content of Column B is present in Column A

/* * This code is to compare content of one columns to other (For example if all elements in Column B is * present in Column A. e * BUG: this code has an issue right now. For NULL between the column cell it is * returning true */

If this is my excel sheet
The output would look like

Banana present in column A
Orange present in column A
Palm present in column A
Pinaple present in column A
Monkey not present in column A


 package jexel;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.util.ArrayList;  
 import jxl.Cell;  
 import jxl.Sheet;  
 import jxl.Workbook;  
 import jxl.read.biff.BiffException;  
 public class CompareColumns {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           CompareC C = new CompareC();  
           C.Compare1();  
      }  
 }  
 /*  
  * This is a code compare two columns between excel sheet Here I am comparing  
  * column A and column B. This is similar to index search  
  *   
  * BUG: this code has an issue right now. For NULL between the column cell it is  
  * returning true  
  */  
 class CompareC {  
      File file = new File("/Users/S_Das/Documents/Java/Test.xls");  
      String col1Content;  
      String col2Content;  
      public void Compare1() {  
           try {  
                Workbook workbook = Workbook.getWorkbook(new FileInputStream(file));  
                Sheet sheet = workbook.getSheet(0);  
                int rowNum = sheet.getRows();  
                ArrayList<String> list1 = new ArrayList<String>();  
                for (int i = 0; i < rowNum; i++) {  
                     Cell col1 = sheet.getCell(0, i);  
                     Cell col2 = sheet.getCell(1, i);  
                     col1Content = col1.getContents();  
                     col2Content = col2.getContents();  
                     list1.add(i, col1Content);  
                     // System.out.println("col2Content "+col2Content);  
                }  
                for (int i = 0; i < rowNum; i++) {  
                     Cell col1 = sheet.getCell(0, i);  
                     Cell col2 = sheet.getCell(1, i);  
                     col1Content = col1.getContents();  
                     col2Content = col2.getContents();  
                     /*  
                      * if (!(col2Content.isEmpty())) {  
                      * System.out.println(sheet.getCell(1, i).getRow() + " " +  
                      * sheet.getCell(1, i).getColumn() + " " + "empty"); }  
                      */  
                     if (list1.contains(col2Content) && (!(col2Content.isEmpty()))) {  
                          System.out.println(col2Content + " present in column A");  
                     }  
                     else if ((!(col2Content.isEmpty()))) {  
                          System.out  
                                    .println(col2Content + " not present in column A");  
                     }  
                }  
           } catch (BiffException | IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  

Friday, September 11, 2015

Java take input from console




 package Study;  
 import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStreamReader;  
 public class ConsoleInput {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           ReadFromConsole consolein = new ReadFromConsole();  
           consolein.read();  
      }  
 }  
 class ReadFromConsole {  
      public void read() {  
           System.out.println("enter");  
           try {  
                BufferedReader reader = new BufferedReader(new InputStreamReader(  
                          System.in));  
                String s = reader.readLine();  
                System.out.println(s);  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  

Java find OS environment variables



//System.getProperty("Propertname") **Platform Independent** 
//System.getenv("EnvName")       **Platform Dependent**
 package Study;  
 import java.util.Collection;  
 import java.util.Iterator;  
 import java.util.Map;  
 import java.util.Set;  
 public class SystemVariables {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           Variables var = new Variables();  
           var.getVariables();  
           var.getEnvVariables();  
      }  
 }  
 class Variables {  
      public void getVariables() {  
           Map<String, String> map = System.getenv();  
           // System.out.println(map.size());  
           Collection<String> allValues = map.values();  
           Set<String> key = map.keySet();  
           Iterator<String> keyIterator = key.iterator();  
           while (keyIterator.hasNext()) {  
                 Iterator<String> valueIterator = allValues.iterator();  
                 while (valueIterator.hasNext()) {  
                      System.out.print(keyIterator.next()+": ");  
                 System.out.println(valueIterator.next());  
                 }  
           }  
      }  
      public void getEnvVariables() {  
           String getEnv = System.getenv("SHELL");  
           // System.out.println(getEnv);  
      }  
 }  

Java file folder operation



//Apache Common IO
//Finding list of files as per file extension . Recusrsive files and directories

package FileSystem;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.io.FileUtils;

public class FileFilterApacheCommonIO {

public static void main(String[] args) {

FileFilter F = new FileFilter();
F.filter();

}

}

class FileFilter {
public void filter() {
String path = "C:/Test";
File f = new File(path);
String fileExtensions[] = {"txt","java"};
Collection<File> filterList = FileUtils.listFiles(f, fileExtensions,
true);
Iterator<File> fListIterator = filterList.iterator();
while (fListIterator.hasNext()) {
System.out.println(fListIterator.next().getAbsoluteFile());
}

}

}

//********************************************************************************
// List of all files and folders. Recusrsive files and directories

package FileSystem;

import java.io.File;

public class RecursiveFileDirectory {

public static void main(String[] args) {
// TODO Auto-generated method stub
Recursive R = new Recursive();
R.readRecursive("C:/Test");
}
}
class Recursive {
String path;
public void readRecursive(String path) {
File f = new File(path);
File[] fileList = f.listFiles();
if (fileList == null)
return;
// check the fileList
for (int i = 0; i < fileList.length; i++) {
/*if fileList objec is directory
recurse through directories until the fileList
object returns null*/
if (fileList[i].isDirectory()) {
readRecursive(fileList[i].getAbsolutePath());
System.out.println(fileList[i].getAbsoluteFile().getPath());
}

else if (fileList[i].isFile()) {
System.out.println(fileList[i].getAbsoluteFile().getPath());
}
}
}
}

//********************************************************************************
// find files in directories and subdirectories based on file name/ folder name using filter

package FileSystem;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;

public class FileList {

public static void main(String[] args) {
// TODO Auto-generated method stub
new FindFileName().filter();

}

}

class FindFileName {
public void filter() {
File f = new File("C:/Test");
String fName = "Helloworld";
String fileName = fName.toLowerCase();
IOFileFilter fileFilter = FileFilterUtils.nameFileFilter(fileName);
Collection<File> listOfFiles = FileUtils.listFiles(f, fileFilter, null);

Iterator<File> fileIterator = listOfFiles.iterator();
while (fileIterator.hasNext()) {
System.out.println(fileIterator.next().getName());

}
}
}



Thursday, September 10, 2015

Java pass by value

 package examples;  
 public class PrimativeDataToMethod {  
      public static void main(String[] args) {  
           // primitive data to method  
           int num1 = 10;  
           int num2 = 20;  
           PriCheck pri = new PriCheck();  
           pri.swap(num1, num2);  
           System.out.println("Outside method dont swap" + num1 + '\t' + num2);  
 System.out.println("");  
           // Object to method  
           Employee E1 = new Employee(100);  
           Employee E2 = new Employee(200);  
           System.out.println("BEFORE "+"E1 " + E1.empId + '\t' + "E2 " + E2.empId);  
           // call the swap method  
           SwpEmpID swap = new SwpEmpID();  
           swap.swap(E1, E2);  
           System.out  
                     .println("AFTER " + "E1 " + E1.empId + '\t' + "E2 " + E2.empId);  
      }  
 }  
 // passing primitive data to method  
 class PriCheck {  
      // swap num1 and num2 within method  
      public void swap(int num1, int num2) {  
           int tmp;  
           tmp = num1;  
           num1 = num2;  
           num2 = tmp;  
           System.out.println("within method swap " + num1 + '\t' + num2);  
      }  
 }  
 // create a employee class  
 class Employee {  
      int empId;  
      public Employee(int empId) {  
           this.empId = empId;  
      }  
 }  
 // passing object to method  
 class SwpEmpID {  
      public void swap(Employee E1, Employee E2) // passing Employee object to  
                                                             // method to swap object  
      {  
           Employee tmp;  
           tmp = E1;  
           E1 = E2;  
           E2 = tmp;  
           // access instance variable of Object E1 and E2 within method  
           System.out.println("instance variable of Object E1 and E2 WITHIN method "  
                     + E1.empId+'\t'+E2.empId);  
      }  
 }  

Tuesday, September 8, 2015

Java IO

JAVA STREAM CLASS REPRESENTATION



Input -- Reading content
Output -- writing the content

Java stream class are of two type

1. Byte Stream - for I/O on bytes
2. Character Stream - for I/O operation on character


Character Stream Class Byte Stream Class
Reader Input stream
Buffered Reader Buffered input stream
Buffered Writer Buffered output stream
File reader File input stream
File writer  File output stream

What is Stream?

Input stream/ output stream is the way of reading and writing raw data respectively. In stream, data are read byte by byte. For example if you want to read an image file or a binary file use Byte Stream Class
Where character stream is used for reading all text. It takes care of character decoding to give Unicode character.

What is Buffer and Un-buffered ?
Unbuffered I/O - For unbuffered access read and write operation is handled by Operating System level. Unbuffered way of reading and writing files involves direct disk access. Which is inefficient in terms of performance.
Buffered I/O - To overcome the inefficiency the way read and write operation occurs for unbuffered  way buffered stream is used. In buffered stream read operation is performed on memory. The memory is nothing but what we call buffer. native API is called when buffer is empty. Write operation is also performed on memory i.e. buffer, when the buffer is full native API is called
Unbuffered stream can be converted to buffer stream in following ways
For character class
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));

//Read File Using Buffered input stream

package example1; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class FileReader { public static void main(String[] args) { reader r = new reader(); r.fileReader(); } } class reader { public void fileReader() { // this constructor accept a input stream try { BufferedInputStream bis = new BufferedInputStream( new FileInputStream("C:/Test/sudas.txt")); while (bis.available() > 0) { int read = bis.read(); System.out.print((char) read); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

// Write File Using BufferedOutputStream

Class BufferOutput { public void bufferout() { try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:/Test/File1.txt")); String sample="This is a sample text"; byte[] inbyte = sample.getBytes(); bos.write(inbyte); bos.flush(); bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

//Read File Using Buffered Reader using READLINE method

package example1; import java.io.BufferedReader; import java.io.IOException; public class FileReader { public static void main(String[] args) { reader r = new reader(); r.fileReader(); } } class reader { // "C:/Test/sudas.txt" public void fileReader() { try { BufferedReader reader = new BufferedReader(new java.io.FileReader( "C:/Test/sudas.txt")); while (reader.readLine() != null) { String read = reader.readLine(); System.out.println(read); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

// Use of Buffer Reader using READ method

      public static void readCookies(String filePath) throws IOException {  
           BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));  
           int line;  
           while((line=br.read())!=-1)  
           {  
           System.out.println((char)line);       
           }  
      }  

//Write file using BufferedWriter

public void writer() { String path = "C:/Test/CreateFile.txt"; // create a file File file = new File(path); try { if (file.exists()) { file.deleteOnExit(); System.out.println("file exists deleting file"); } else { file.createNewFile(); } BufferedWriter writer = new BufferedWriter(new FileWriter(path)); writer.write("This is for Test Purpose"); writer.flush(); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

// EXAMPLE TO CREATE FILE, IF EXISTS DELETE FILE

public void writer() { String path = "C:/Test/CreateFile.txt"; // create a file File file = new File(path); try { if (file.exists()) { file.deleteOnExit(); System.out.println("file exists deleting file"); } else { file.createNewFile(); } // BufferedWriter writer = new BufferedWriter(new FileWriter(path)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

// Utility to copy the content of one file to the other

class CopyContent { public void copy() { String sourceFile = "C:/Test/AdobeARM.log"; String destinationFile = "C:/Test/CreateFile.txt"; try { // create a file File file = new File(destinationFile); if (file.exists()) { file.deleteOnExit(); System.out.println("file exists deleting file"); } else { file.createNewFile(); System.out.println("File created"); } // Read the source file content BufferedReader breader = new BufferedReader(new java.io.FileReader( new File(sourceFile))); BufferedWriter writer = new BufferedWriter(new FileWriter( destinationFile)); while (breader.readLine() != null) { char[] readLine = breader.readLine().toCharArray(); // write writer.write(readLine); writer.write('\n'); } writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

This is an example to get String from Fileinputstream using StringBuilder


 class LogScanner {  
      public void scan() {  
           // fileinputstream to string  
           StringBuilder sb = new StringBuilder();  
           try {  
                FileInputStream fis = new FileInputStream(new File("/Users/S_Das/Documents/Java/sudas.log"));  
                int input;  
                while((input = fis.read())!=-1){  
                sb.append((char)input);  
                }  
                System.out.println(sb.toString());  
                fis.close();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  

Monday, September 7, 2015

Java random string generator (not unique)

This code generates random Array elements. The Array elements are first taken into ArrayList and then Collection.Shuffle method is used to shuffle the elements. This produce a unique random elements.

1:  package example1;  
2:  import java.util.ArrayList;  
3:  import java.util.Collections;  
4:  public class RandomStringFromArrayList {  
5:       public static void main(String[] args) {  
6:            // create a 1D Array  
7:            String companyName[] = { "Apple", "HTC", "Samsung", "Microsoft" };  
8:            ArrayList<String> list = new ArrayList<String>();  
9:            for (int i = 0; i < companyName.length; i++) {  
10:                 list.add(i, companyName[i]);  
11:            }  
12:            for (int j = 1; j <= 10; j++) {  
13:                 Collections.shuffle(list);  
14:                 String CompanyName = list.get(0);  
15:                 System.out.println(CompanyName);  
16:            }  
17:       }  
18:  }  

Java write excel file

 package com.bmc.artestdata.qa;  
 import java.io.File;  
 import java.io.IOException;  
 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.Random;  
 import jxl.Workbook;  
 import jxl.read.biff.BiffException;  
 import jxl.write.Label;  
 import jxl.write.WritableCell;  
 import jxl.write.WritableSheet;  
 import jxl.write.WritableWorkbook;  
 import jxl.write.WriteException;  
 public class CreateCompaniesInXL {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           CreateCompanies create = new CreateCompanies();  
           create.create();  
      }  
 }  
 class CreateCompanies {  
      int totalCompanies = 200;  
      public void create() {  
           try {  
                // create a workbook  
                WritableWorkbook workbook = Workbook.createWorkbook(new File(  
                          "C:/Java_Source_Code/Company.xls"));  
                // create a worksheet  
                WritableSheet sheet = workbook.createSheet("Company", 0);  
                int i;  
                ArrayList<Integer> list;  
                Integer random;  
                for (i = 0; i <= totalCompanies; i++)  
                {  
                     list = new ArrayList<Integer>();  
                     list.add(i);  
                     Collections.shuffle(list);  
                     for (int j = 0; j < list.size(); j++) {  
                          random = list.get(j);  
                          // write cell within sheet  
                          sheet.addCell(new Label(0, i, "Automation.Company_" + 0  
                                    + random));  
                     }  
                }  
                workbook.write();  
                workbook.close();  
                // in.close();  
           } catch (IOException | WriteException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  

Java abstract class, interface Inheritance and polymorphism

 package example1;  
 public class AbstructClass {  
      public static void main(String[] args) {  
           /*  
            * SUPER CLASS SUB CLASS create a subclass object and access all the  
            * superclass instance variable and methods  
            */  
           Child child = new Child();  
           child.name = "---By createing a child class object---";  
           child.name();  
           /*  
            * SUPER CLASS SUB CLASS POLYMORPHISM and DYNAMIC METHOD DISPATCH even i  
            * can do polymorphism superclass variable = new SubclassObject  
            */  
           Parent p = new Child();  
           p.name = "---Dynamic method dispatch decides on runtime whic method to call---";  
           /*  
            * If you don't initialize the variable you will get null depending on  
            * the object the method would be called (DYNAMIC METHOD DISPATCH) in  
            * this case the Child() object is created so methods related to child  
            * object would be called.  
            */  
           p.name();  
           /*  
            * a static method available within class is notinherited has to call by  
            * class name  
            */  
           Parent.scientificName();  
           // scientificName() is a static method in parent class  
           /*  
            * ABSTRACT CLASS creating object of abstract class is not possible if  
            * you do you will create a anonymous inner class  
            */  
           abstractA abstract1 = new abstractA() {  
                @Override  
                public int intabstractMethod() {  
                     // TODO Auto-generated method stub  
                     return 0;  
                }  
                @Override  
                public void abstractMethod() {  
                     // TODO Auto-generated method stub  
                }  
           };  
           // accessing a static method within abstract class  
           abstractA abstract2 = abstractA.staticMethod();  
           // abstract2.intabstractMethod(); // this gives you a null pointer  
           // exception  
           // creating object of extended abstract class  
           extendedAbstractClass extended = new extendedAbstractClass();  
           extended.abstractMethod();  
           extended.intabstractMethod();  
           /*  
            * INTERFACE  
            */  
           interfaceClass my0 = new interfaceClass();  
           my0.abstractMethod();  
           my0.InterfaceDefaultMethod();  
           MyInterface my = new interfaceClass();  
           my.abstractMethod();  
           my.InterfaceDefaultMethod();  
           /*  
            * class NewimplementInterface extends abstractA implements  
            * MynewInterface  
            */  
           /*  
            * creating an object of interface creates anonymous inner class like  
            * creating object of abstract class  
            */  
           MynewInterface my1 = new NewimplementInterface();  
      }  
 }  
 // this is a super class  
 class Parent {  
      // super class instance variable  
      String name;  
      int age;  
      // super class class variable  
      static String scientificName = "Homo";  
      // super class instance method  
      public void name() {  
           System.out.println("Super class instance method " + name);  
      }  
      // super class instance method with a return type  
      public String getName() {  
           System.out.println("Super class instance method with return type "  
                     + name);  
           return name;  
      }  
      // super class static/class method  
      public static void scientificName() {  
           System.out.println("Super class static method " + scientificName);  
      }  
 }  
 /*  
  * this is a subclass of parent. Subclass extends superclass through a subclass  
  * object you can access the instance variable and methods of superclass. The  
  * reverse is not possible.  
  */  
 class Child extends Parent {  
      String gender;  
      // subclass instance method  
      public void gender() {  
           System.out.println("Subclass instance method " + gender);  
      }  
      // subclass static method  
      public static void play() {  
           System.out.println("Subclass ststic method ");  
      }  
      // methods from parent class can be overridden into subclass  
      // overridden methods are nothing but a copy of superclass method but just a  
      // new version and  
      // functionality. You can always call super class methods to subclass but  
      // only within the overridden method  
      // this is a overridden method. This method in parent class does not have a  
      // return type.  
      @Override  
      public void name() {  
           System.out.println("Subclass Child instance method " + name);  
           // super.name();  
      }  
      // this is a overridden method. This method in parent class has String  
      // return.  
      @Override  
      public String getName() {  
           // not sure why some one would do that  
           super.name = "Test";  
           return super.getName();  
      }  
 }  
 class Siblings extends Child {  
      // this class can inherit all methods from Child (which is superclass) of  
      // Siblings and it can inherit methods from Parent which is superclass for  
      // Child  
      // overridden method of Superclass Parent  
      @Override  
      public void name() {  
           super.name();  
      }  
      // overridden method of Superclass Patent  
      @Override  
      public String getName() {  
           return super.getName(); // the superclass Child method getName has  
                                         // return type  
      }  
      // overridden method of Superclass Child  
      @Override  
      public void gender() {  
           // TODO Auto-generated method stub  
           super.gender();  
      }  
 }  
 abstract class abstractA {  
      // a normal method within abstract class  
      public void normalMethod() {  
           System.out.println("I am a normal method within class abstractA");  
      }  
      // a static method within abstract class  
      public static abstractA staticMethod() {  
           System.out.println("I am a static method within class abstractA");  
           return null;  
      }  
      /*  
       * you can declare a class a abstract even if you don't have a abstract  
       * method with the abstract class. But remember you cannot make a abject /  
       * instantiate an abstract class. If you create object of abstract class it  
       * creates anonymous inner classes do not make methods private. Private  
       * modifiers are against inheritance  
       */  
      // it is responsibility of the extended class to implement the method body  
      // abstract method within abstract class  
      public abstract void abstractMethod();  
      // you can even have a return type to the abstract class  
      public abstract int intabstractMethod();  
 }  
 // A class can extends a abstract class. When you extend the class with abstract  
 // class  
 // you have to implement all the overridden method from abstract class  
 class extendedAbstractClass extends abstractA {  
      @Override  
      public void abstractMethod() {  
           System.out  
                     .println("This is from extended abstract class from abstractMethod");  
      }  
      @Override  
      public int intabstractMethod() {  
           System.out  
                     .println("This is from extended abstract class from intabstractMethod");  
           // ******************************************************************************************************  
           // calling a normal method from Abstract class within abstract method  
           // inherited from abstract class  
           // ******************************************************************************************************  
           super.normalMethod();  
           return 0;  
      }  
 }  
 interface MyInterface {  
      /*  
       * interface method can be either be static, abstract or default method.  
       * Default method add new functionality to the interface.  
       *   
       * For example you want to add a new functionality i.e. a new method into  
       * the interface at later stage. Now class which has already implemented the  
       * old interface will break unless the new method is overridden. This  
       * problem can be solved by default methods * Default METHODS ARE ALLOWED  
       * ONLY IN INTERFACE. So when you implement the interface to a class where  
       * all the methods within a interface are abstract you need to implement(add  
       * body) to the class where you have implemented the interface You cannot  
       * have a static method without body  
       */  
      // default method  
      default void InterfaceDefaultMethod() {  
           System.out.println("I am a default method in MyInterface ");  
      }  
      // abstract method  
      void abstractMethod();  
      // static method  
      static void ststicMethod() {  
           System.out.println("I am a ststic method in MyInterface ");  
      }  
 }  
 /*  
  * as an alternative instead of adding a default method a interface can also be  
  * extended. For example I will create a new interface MynewInterface which will  
  * extends the MyInterface so when some one implements the MynewInterface all  
  * methods would be accessible. No programmers have a choice whether to upgrade  
  * the interface or stay with the old one  
  */  
 interface MynewInterface extends MyInterface {  
      /*  
       * here you will not implement the unimplemented methods from MyInterface it  
       * is the the class which implements MyInterface OR MynewInterface will  
       * implement the incomplete methods new abstract method  
       */  
      public void InterfaceAbstractMethod();  
 }  
 /*  
  * this is a class which implements the interface My interface you can implement  
  * multiple interface (i.e interface support multiple inheritance where as you  
  * can only extend one class when you implement interface on a class all  
  * abstract methods are overridden within the class  
  */  
 class ImplementInterface implements MyInterface {  
      /*  
       * here you have a choice which interface to implement. if you implement the  
       * MynewInterface you will get MyInterface methods as well as MynewInterface  
       * methods.  
       */  
      // abstract method overridden from interface  
      @Override  
      public void abstractMethod() {  
           // TODO Auto-generated method stub  
      }  
 }  
 /*  
  * a class can implement a interface , in fact can implement multiple interface  
  * also the same class can extend a class. You can extend Superclass/ parent  
  * class/ normal class. When you extend a super class, naturally you have to  
  * implement all the methods belonging to abstract class. Abstract class does  
  * not support multiple inheritance. When you use extends and implements both  
  * use extends first  
  */  
 class NewimplementInterface extends abstractA implements MynewInterface {  
      // this is a overridden method from Abstract class  
      @Override  
      public void abstractMethod() {  
           // TODO Auto-generated method stub  
           /*  
            * Don't even think that you can access the other methods using the  
            * super. This is a implemented interface not an extended class :-)  
            */  
      }  
      // this is a overridden method from  
      @Override  
      public void InterfaceAbstractMethod() {  
           // TODO Auto-generated method stub  
      }  
      @Override  
      public int intabstractMethod() {  
           // TODO Auto-generated method stub  
           return 0;  
      }  
 }  
 class interfaceClass implements MyInterface {  
      @Override  
      public void abstractMethod() {  
           // TODO Auto-generated method stub  
      }  
 }  

Saturday, September 5, 2015

Java random number generator

JAVA NUMBER GENERATOR


 package sudas.study.example.one;  
 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.Random;  
 public class UniqueRandomNumber {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           // new Random1().random();  
           // new Random2().random();  
           new Random3().random();  
      }  
 }  
 // this will create numbers not random from 1 to 10 but not unique  
 class Random1 {  
      public void random() {  
           // with arraylist  
           ArrayList<Integer> arraylist = new ArrayList<Integer>();  
           for (int i = 1; i <= 10; i++) {  
                arraylist.add(i);  
           }  
           for (int i = 1; i <= 10; i++) {  
                Integer randomNumbers = arraylist.get(i);  
                System.out.println("From ArrayList :" + randomNumbers.intValue());  
           }  
      }  
 }  
 // Random numbers are getting generated but numbers are not unique  
 class Random2 {  
      public void random() {  
           for (int i = 1; i <= 10; i++) {  
                Random random = new Random();  
                Object nextNo = random.nextInt(i);  
                System.out.println(nextNo);  
           }  
      }  
 }  
 // This is unique random number generator  
 class Random3 {  
      public void random() {  
           ArrayList<Integer> arraylist = new ArrayList<Integer>();  
           for (int i = 0; i <= 10; i++) {  
                arraylist.add(i);  
           }  
           Collections.shuffle(arraylist);  
           for (int i = 0; i < 10; i++) {  
                Integer randomNumbers = arraylist.get(i);  
                System.out.println("Unique Random Numbers :" + randomNumbers.intValue());  
           }  
      }  
 }  

Friday, September 4, 2015

Java Read excel file

  • //Read excel file

public void ReadFromXL()
{
File f = new File("C:/Java_Source_Code/ARSystem.data.xls");
try {
Workbook workbook = Workbook.getWorkbook(f);
String[] sheetName = workbook.getSheetNames();
for (int i=0;i<sheetName.length;i++)
{
System.out.println(sheetName[i]);
}


} catch (IOException | BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

  • //get all the worksheet name

Workbook workbook = Workbook.getWorkbook(f);
Sheet sheetName = workbook.getSheet(0);
String sName = sheetName.getName();
System.out.println(sName);

  • //get all cell contents for a particular column

Cell[] columns = sheet.getColumn(0);
for (int i=0;i<columns.length;i++)
{
System.out.println(columns[i].getContents());
}
  • //get content for a particular cell

Cell cell = sheet.getCell(0, 0);
String cellContent = cell.getContents();        
System.out.println(cellContent);

  • //get all cell contents for a particular row

sheet.getRow(0);

Thursday, September 3, 2015

Feeling excited during release


Java File read write operation in Java

 package example1;  
 import java.io.BufferedOutputStream;  
 import java.io.BufferedReader;  
 import java.io.BufferedWriter;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.io.FileOutputStream;  
 import java.io.FileReader;  
 import java.io.FileWriter;  
 import java.io.IOException;  
 import java.io.OutputStream;  
 import java.io.OutputStreamWriter;  
 import java.io.Reader;  
 public class ReadWriteFile {  
      public static void main(String[] args) {  
           ReadFile r = new ReadFile();  
           r.read("c:/Test/toi.txt");  
           r.read1("c:/Test/toi.txt");  
      }  
 }  
 // read file using file input stream  
 class ReadFile1 {  
      String path;  
      public void read(String path) {  
           this.path = path;  
           File f = new File(path);  
           try {  
                FileInputStream input = new FileInputStream(f);  
                int content;  
                while ((content = input.read()) != -1) {  
                     System.out.print((char) content); // type casting int to  
                                                                  // character  
                }  
                input.close();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  
 // read file using Buffered input stream  
 class ReadFile {  
      String contents;  
      public String read(String path) {  
           File f = new File(path);  
           try {  
                BufferedReader reader = new BufferedReader(new FileReader(f));  
                BufferedWriter writer = null;  
                writer = new BufferedWriter(new FileWriter("c:/Test/sudas.txt"));  
                while ((contents = reader.readLine()) != null) {  
                     writer.write(contents);  
                     writer.write('\n');  
                     // System.out.println(contents);  
                }  
                reader.close();  
                writer.close();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
           return contents;  
      }  
      public String read1(String path) {  
           File f = new File(path);  
           try {  
                BufferedReader reader = new BufferedReader(new FileReader(f));  
                BufferedOutputStream out = new BufferedOutputStream(  
                          new FileOutputStream("c:/Test/Output.txt"));  
                while ((contents = reader.readLine()) != null) {  
                     out.write(contents.getBytes());  
                     out.write("\n".getBytes());  
                     System.out.println(contents);  
                }  
                reader.close();  
                out.close();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
           return contents;  
      }  
 }  
 class CreateFiles {  
      public void create(String path) {  
           File f = new File(path);  
           try {  
                f.createNewFile();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }