Saturday, October 24, 2015

JUnit and Test NG for software testing

  

How To Use.


JUnit is a unit testing framework which is very handy and useful to perform unit testing of java codes.

To setup Junit on a maven project include this dependency on pom.xml
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit-dep</artifactId>
  <version>4.10</version>
  <scope>test</scope>
</dependency>         
<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-library</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>

Annotations used in Junit test
@BeforeClass -- This runs only once before all @Test
@AfterClass  -- This runs only once after all @Test
@Before -- This runs before every @Test
@After-- This runs after every @Test
@Test  -- This is the actual test
@Rule  -- To introduce a Rule like ErrorCollector rule
@Test( expected = IllegalStateException.class )
@RunWith -- for any other test runner class except the default Junit runner
@SuiteClasses -- for running all tests in suite



 package com.sudas.newJunit;  
 import static org.junit.Assert.*;  
 import java.io.PrintWriter;  
 import org.hamcrest.Matchers;  
 import org.junit.After;  
 import org.junit.AfterClass;  
 import org.junit.Before;  
 import org.junit.BeforeClass;  
 import org.junit.Test;  
 public class JunitAnnotations {  
      Calculators calc1;  
      Calculators calc2;  
      Calculators calc3;  
      @BeforeClass  
      public static void setUpBeforeClass() throws Exception {  
      }  
      @AfterClass  
      public static void tearDownAfterClass() throws Exception {  
      }  
      @Before  
      public void setUp() throws Exception {  
           calc1 = new Calculators("10", "10");  
           calc2 = new Calculators("10.1", "10.1", "10.1");  
           calc3 = new Calculators("10.1", "10.1", "10.1", "10.1");  
      }  
      @After  
      public void tearDown() throws Exception {  
      }  
      @Test  
      public void AdditionTwoNumbers() {  
 //          assertEquals(20.21, calc1.twoDigitAddition(), 0);  
           assertThat(calc1.twoDigitAddition(), new Matchers().equalTo(20.21));  
      }  
      @Test  
      public void AdditionThreeNumbers() {  
           assertEquals(60.3, calc2.threeDigitAddition(), 0);  
      }  
      @Test  
      public void AdditionFourNumbers() {  
           assertEquals(80.4, calc3.FourDigitAddition(), 0);  
      }  
 }  


@After annotation is used where we need to close db connection. close buffer stream etc.

@BeforeClass - Unlike @Before which runs before every test, @BeforeClass run only once in the test class. @BeforeClass is use to create database connection object webdriver object etc.


@Rule
 @Rule  
      public ErrorCollector collector = new ErrorCollector();  
      @Test  
      public void testSeven() {  
           int num1[] = { 10, 20, 30, 40, 50 };  
           int num2[] = { 10, 20, 0, 40, 50 };  
           // Assert.assertArrayEquals("All elements in array are equal", num1,  
           // num2);  
           // Assert.assertThat(num1, Matchers.equalTo(num2));  
           collector.checkThat("Element mismatch", num2, Matchers.equalTo(num1));  
      }  


JUnit Test Runner
      @RunWith(Suite.class)  
 //     @Suite.SuiteClasses({   
 //       calc.class,ArrayTest.class  
 //     })  
      @SuiteClasses  
      ({ArrayTest01.class,ArrayTest02.class})  
      public class JunitTestSuite {  
      }  


A broader JUnit example

 package com.sudas.junit;  
 import org.hamcrest.Matchers;  
 import org.hamcrest.*;  
 import org.junit.Assert;  
 import org.junit.Ignore;  
 import org.junit.Rule;  
 import org.junit.Test;  
 import org.junit.rules.ErrorCollector;  
 public class JunitExample {  
      public static void main(String[] args) {  
      }  
      @Test  
      public void testOne() {  
           // Test for actual and expected result  
           String actual = "Apple";  
           String expected = "apple";  
           // use of assert  
           Assert.assertEquals(expected.toLowerCase(), actual.toLowerCase());  
      }  
      // if condition is true test case fail  
      @Test  
      public void tesTwo() {  
           String actual = "Apple";  
           String expected = "apple";  
           Assert.assertFalse("This condition is Flase", actual.length() == expected.length());  
      }  
      @Test  
   // if condition is true test case pass
public void testThree() { String actual = "Apple"; String expected = "apple"; Assert.assertTrue("This condition is True", actual.length() == expected.length()); } @Test  
// Hamcrest matcher example
      public void testFour() {  
           String actual = "Apple";  
           String expected = "apple";  
           Assert.assertThat(actual, Matchers.equalToIgnoringCase(expected));  
      }  
      @Test  
      public void testFive() {  
// Hamcrest matcher ignore case example
String actual = "Apple"; String expected = "apple"; Assert.assertThat(actual, Matchers.equalToIgnoringCase(expected)); } @Test  
// Array Test
      public void testSix() {  
           int num1[] = { 10, 20, 30, 40, 50 };  
           int num2[] = { 10, 20, 0, 40, 50 };  
           Assert.assertArrayEquals("All elements in array are equal", num1, num2);  
      }  
      @Rule  
      public ErrorCollector collector = new ErrorCollector();  
      @Test  
// Use of Error collector rule
      public void testSeven() {  
           int num1[] = { 10, 20, 30, 40, 50 };  
           int num2[] = { 10, 20, 0, 40, 50 };  
           // Assert.assertArrayEquals("All elements in array are equal", num1,  
           // num2);  
           // Assert.assertThat(num1, Matchers.equalTo(num2));  
           collector.checkThat("Element mismatch", num2, Matchers.equalTo(num1));  
      }  
      @Test  
      public void testEight() {  
           String num1 = "10.1";  
           String num2 = "10.1";  
           double number1 = Double.parseDouble(num1);  
           double number2 = Double.parseDouble(num2);  
           double total = number1 + number2;  
           Assert.assertTrue(total == 20.2);  
      }  
      @Ignore("do not test")  
      @Test  
      public void testNine() {  
      }  
 }  
Test Results For Failed Tests

JunitExample
com.sudas.junit.JunitExample
tesTwo(com.sudas.junit.JunitExample)

java.lang.AssertionError: This condition is Flase
eTestRunner.main(RemoteTestRunner.java:192)

testSix(com.sudas.junit.JunitExample)
All elements in array are equal: arrays first differed at element [2]; expected:<30> but was:<0>

testSeven(com.sudas.junit.JunitExample)
java.lang.AssertionError: Element mismatch
Expected: [<10>, <20>, <30>, <40>, <50>]
     got: [<10>, <20>, <0>, <40>, <50>]



@Parameterized test using JUnit



CLASS UNDER TEST

 package sudas.junit;  
 public class Addition {  
      public int addition(int num1, int num2) {  
           int total = num1 + num2;  
           return total;  
      }  
 }  

 package sudas.junit;  
 import static org.junit.Assert.*;  
 import java.util.Arrays;  
 import java.util.Collection;  
 import java.util.Collections;  
 import java.util.List;  
 import org.junit.After;  
 import org.junit.AfterClass;  
 import org.junit.Before;  
 import org.junit.BeforeClass;  
 import org.junit.Test;  
 import org.junit.runner.RunWith;  
 import org.junit.runners.Parameterized;  
 import org.junit.runners.Parameterized.Parameters;  
 @RunWith(Parameterized.class)  
 public class JunitParameterTest {  
      static Addition addition;  
      int expected;  
      int number1;  
      int number2;  
      public JunitParameterTest(int expected, int number1, int number2) {  
           // TODO Auto-generated constructor stub  
           this.expected = expected;  
           this.number1 = number1;  
           this.number2 = number2;  
      }  
      @BeforeClass  
      public static void setUpBeforeClass() throws Exception {  
           addition = new Addition();  
      }  
      @AfterClass  
      public static void tearDownAfterClass() throws Exception {  
      }  
      @Before  
      public void setUp() throws Exception {  
      }  
      @After  
      public void tearDown() throws Exception {  
      }  
      @Parameterized.Parameters  
      public static Collection<Object[]> addedNumbers() {  
           return Arrays.asList(new Object[][] { { 3, 1, 2 }, { 5, 2, 3 }, { 7, 3, 4 }, { 9, 4, 5 }, });  
      }  
      @Test  
      public void test() {  
           int t = addition.addition(number1, number2);  
           System.out.println(number1);  
           assertEquals(expected, t);  
      }  
 }  

OUTPUT





 import static org.junit.Assert.*;  
 import org.junit.After;  
 import org.junit.AfterClass;  
 import org.junit.Before;  
 import org.junit.BeforeClass;  
 import org.junit.Test;  
 public class ExecutionOrder {  
      @BeforeClass  
      public static void setUpBeforeClass() throws Exception {  
           System.out.println("@BeforeClass");  
      }  
      @AfterClass  
      public static void tearDownAfterClass() throws Exception {  
           System.out.println();  
      }  
      @Before  
      public void setUp() throws Exception {  
           System.out.println("@AfterClass");  
      }  
      @After  
      public void tearDown() throws Exception {  
           System.out.println("@After");  
      }  
      @Test  
      public void test01() {  
           System.out.println("test01");  
      }  
      @Test  
      public void test02() {  
           System.out.println("test02");  
      }  
      @Test  
      public void test03() {  
           System.out.println("test03");  
      }  
 }  
EXECUTION ORDER 
@BeforeClass
@Before
test01
@After
@Before
test02
@After
@Before
test03
@After
@AfterClass
 

Common Test NG Annotations

@BeforeSuite - 

@AfterSuite
@BeforeTest
@AfterTest
@BeforeGroups
@AfterGroups
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod


 package TestNG;  
 import org.testng.annotations.Test;  
 import org.testng.annotations.BeforeMethod;  
 import org.testng.annotations.AfterMethod;  
 import org.testng.annotations.BeforeClass;  
 import org.testng.annotations.AfterClass;  
 import org.testng.annotations.BeforeTest;  
 import org.testng.annotations.AfterTest;  
 import org.testng.annotations.BeforeSuite;  
 import org.testng.annotations.AfterSuite;  
 public class AnnotationsOrder {  
      @Test  
      public void Test01() {  
           System.out.println("@Test 01");  
      }  
      @Test  
      public void Test02() {  
           System.out.println("@Test 02");  
      }  
      @Test  
      public void Test03() {  
           System.out.println("@Test 03");  
      }  
      @Test  
      public void Test04() {  
           System.out.println("@Test 04");  
      }  
      @Test  
      public void Test05() {  
           System.out.println("@Test 0");  
      }  
      @BeforeMethod  
      public void beforeMethod() {  
           System.out.println(" @BeforeMethod");  
      }  
      @AfterMethod  
      public void afterMethod() {  
           System.out.println(" @AfterMethod");  
      }  
      @BeforeClass  
      public void beforeClass() {  
           System.out.println("@BeforeClass");  
      }  
      @AfterClass  
      public void afterClass() {  
           System.out.println(" @AfterClass");  
      }  
      @BeforeTest  
      public void beforeTest() {  
           System.out.println(" @BeforeTest");  
      }  
      @AfterTest  
      public void afterTest() {  
           System.out.println(" @AfterTest");  
      }  
      @BeforeSuite  
      public void beforeSuite() {  
           System.out.println(" @BeforeSuite");  
      }  
      @AfterSuite  
      public void afterSuite() {  
           System.out.println("@AfterSuite");  
      }  
 }  
 EXECUTION ORDER
[TestNG] Running:  
  C:\Users\sudas\AppData\Local\Temp\testng-eclipse--451353207\testng-customsuite.xml  
  @BeforeSuite  
  @BeforeTest  
 @BeforeClass  
  @BeforeMethod  
 @Test 01  
  @AfterMethod  
  @BeforeMethod  
 @Test 02  
  @AfterMethod  
  @AfterClass  
  @AfterTest  
 PASSED: Test01  
 PASSED: Test02  
 ===============================================  
   Default test  
   Tests run: 2, Failures: 0, Skips: 0  
 ===============================================  
 @AfterSuite  
 ===============================================  
 Default suite  
 Total tests run: 2, Failures: 0, Skips: 0  
 ===============================================  
 [TestNG] Time taken by org.testng.reporters.JUnitReportReporter@3419866c: 15 ms  
 [TestNG] Time taken by org.testng.reporters.jq.Main@4f47d241: 71 ms  
 [TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 1 ms  
 [TestNG] Time taken by org.testng.reporters.EmailableReporter2@198e2867: 6 ms  
 [TestNG] Time taken by org.testng.reporters.XMLReporter@6d1e7682: 16 ms  
 [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@2f410acf: 37 ms  


< Implementation of TestNG >

This example will illustrate the use of Listener in TestNG and will illustrate use of overriding methods from TestListenerAdapter  like onTestFailure, onTestSuccess.
onTestFailure - Gets executed on Test Failure 
onTestSuccess - Gets executed on Test Success.

Use of ITestResult Interface on @AfterMethod




package com.TestNG;

import org.testng.annotations.Test;
import org.testng.annotations.Parameters;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Optional;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.AfterSuite;

public class NewTest extends TestListenerAdapter {
 // This test takes parameter from testNG XML file
 @Parameters({ "parameter_name1", "parameter_name2" })

 // Test Case One
 @Test(testName = "TestOne", groups = { "g1", "g5" }, enabled = true)
 // if no argument are supplied
 public void t1(@Optional("p1") String par1, @Optional("p2") String par2) {
  Assert.assertEquals(par1, par2);
 }

 // Test Case Two
 @Test(testName = "TestTwo", groups = { "g1" }, enabled = true)
 public void t2() {
  Assert.assertTrue(true);

 }

 // Test Case Three
 @Test(testName = "TestThree", groups = { "g1" }, enabled = false)
 public void t3() {
 }

 // Test Case Four
 @Test(testName = "TestFour", groups = { "g1", "g5" }, enabled = false)
 public void t4() {
 }

 // Test Case Five
 @Test(testName = "TestFive", groups = { "g1", "g5" }, enabled = false)
 public void t5() {
 }

 @BeforeMethod
 public void beforeMethod() {
 }

 @AfterMethod
 public void afterMethod(ITestResult result) {
  if (result.getStatus() == ITestResult.SUCCESS) {
   System.out.println("Test method Name " + result.getName());

   System.out.println("do something in after method");
  }
 }

 @BeforeClass
 public void beforeClass() {
 }

 @AfterClass
 public void afterClass() {
 }

 @BeforeTest
 public void beforeTest() {
 }

 @AfterTest
 public void afterTest() {
 }

 @BeforeSuite
 public void beforeSuite() {
 }

 @AfterSuite
 public void afterSuite() {
 }

 @Override
 public void onTestFailure(ITestResult tr) {
  // TODO Auto-generated method stub
  System.out.println("because failed");
  System.out.println(tr.getName());
  super.onTestFailure(tr);
 }

 @Override
 public void onTestSuccess(ITestResult tr) {
  // TODO Auto-generated method stub
  System.out.println("because passed");
  super.onTestSuccess(tr);
 }
}

Test NG XML to run the above tests
<?xml version="1.0" encoding="UTF-8"?>
<suite name="check for failed tests">
 <listeners>
  <listener class-name="com.TestNG.NewTest" />
 </listeners>
 <test name="TestOne">
 <classes>
  <class name="com.TestNG.NewTest" />
 </classes>
</test>
</suite>

Thursday, October 15, 2015

Java Copy directory recursive




.

 package apache.commons;  
 import java.io.File;  
 import java.io.IOException;  
 import org.apache.commons.io.FileUtils;  
 public class CopyDirectory {  
      public static void main(String[] args) {  
           new CopyDirectory().copyDirectory();  
           new CopyDirectory().checkCopy();  
      }  
      public void copyDirectory() {  
           File srcDir = new File("/Users/S_Das/Documents/Java/project.chanko");  
           File destDir = new File("/Users/S_Das/Documents/Java/new.project.chanko");  
           try {  
                FileUtils.copyDirectory(srcDir, destDir);  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
      public void checkCopy() {  
           File file = new File("/Users/S_Das/Documents/Java/new.project.chanko");  
           if (file.exists()) {  
                System.out.println("Directory copied");  
           }  
           else {  
                System.out.println("not");  
           }  
      }  
 }  

Java Copy file using NIO





 package FileSystem;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.nio.file.Files;  
 import java.nio.file.Paths;  
 import java.nio.file.StandardCopyOption;  
 public class CopyFiles {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           new CopyFiles().copyFiles();  
      }  
      public void copyFiles() {  
           String destination = "/Users/S_Das/Documents/Java/new.xml";  
           String source = "/Users/S_Das/Documents/Java/jdk-8u60-linux-i586.gz";  
           try {  
                // OPTION 01  
                Files.copy(Paths.get("/Users/S_Das/Documents/Java/pom.xml"), new FileOutputStream(new File(destination)));  
                // OPTION 02  
                Files.copy(new FileInputStream(new File(source)),  
                          Paths.get("/Users/S_Das/Documents/Java/NEW_jdk-8u60-linux-i586.gz"),  
                          StandardCopyOption.REPLACE_EXISTING);  
           } catch (FileNotFoundException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  

Java EPOCH to Date Time and vice verse converter







package DateTime;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateExample {

 public static void main(String[] args) {
  ChangeDate dateuse = new ChangeDate();
  dateuse.EpochToDateTime();
  dateuse.dateTimeToEpoch();

 }

}

class ChangeDate {

 String formatDate;

 public void EpochToDateTime() {
  DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS");
  format.setTimeZone(TimeZone.getDefault());
  formatDate = format.format(new Date().getTime());
  System.out.println(formatDate);
  System.out.println("epoch " + new Date().getTime());
  // System.out.println(System.currentTimeMillis());
 }

 public void dateTimeToEpoch() {
  // String dateTime = "20/11/2015 18:55:00";
  SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy HH:mm:ss.SSS");
  // format.setTimeZone(TimeZone.getDefault());
  try {
   Date epoch = format.parse(formatDate);
   System.out.println(epoch.getTime());

  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}


Monday, October 12, 2015

Java Log Helper using Scanner

Problem Statement: 
Sometimes it becomes very tedious to find some thing in a huge log file, most of the time we look for some string pattern in the log file, For example we look for keywords like "success", "failure", "error", "warning", "java stack trace", "error code" , etc.
Through  this utility, without opening the log file and effortlessly  we can find the string we are looking for within the log file. If there is a match the utility will return a match along with the line numbers the string you are looking for is present.
From the sample.txt file I am finding the string "com0113:



OUTPUT



 package sudas.utils;  
 import java.io.BufferedInputStream;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.io.IOException;  
 import java.util.Scanner;  
 public class LogScannerHelper {  
      public static void main(String[] args) {  
           // new Bufferedreader().inputStream();  
           new scanner().scanLines();  
      }  
 }  
 class scanner {  
      // read the content of the log file and search for a perticular string  
      public void scanLines() {  
           try {  
                Scanner scan = new Scanner(new File("C:/Test/sudas.txt"));  
                String match = "of";  
                int lineNumber = 1;  
                while (scan.hasNextLine()) {  
                     String line = scan.nextLine();  
                     // System.out.println(line+'\t'+lineNumber++);  
                     Scanner string = new Scanner(line);  
                     String completeString = string.findInLine("companies");  
                     {  
                          int lineNum = lineNumber++;  
                          if (completeString != null) {  
                               System.out.println(completeString + '\t' + "-- at line number "+lineNum);  
                          }  
                     }  
                }  
           } catch (FileNotFoundException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  

Friday, October 9, 2015

Java understanding static




Example to illustrate static in Java

In this example the variable counter is a static variable and it is a class variable not a instance variable. The number of times the counter() method is instantiated which in turn executed the println statement and incremented the static variable counter by 1. As the static variable does not belong to instance of a class instead it belongs to a class instead, so every time the counter() method is instantiated the counter gets incremented.

 package sudas.study.example.one;  
 public class ObjectCounter {  
      public static void main(String[] args) {  
           ObjCounter o1 = new ObjCounter();  
           o1.counter();  
           ObjCounter o2 = new ObjCounter();  
           o2.counter();  
           ObjCounter o3 = new ObjCounter();  
           o3.counter();  
      }  
 }  
 class ObjCounter {  
      static int counter = 0;  
      public void counter() {  
           System.out.println("Number of object created " + counter++);  
      }  
 }  

Eclipse settings to remove blank lines between codes


Wednesday, October 7, 2015

Java scanner utility to take input from console and save inputs in a file

This utility takes keyboard input what you type in console and saves all the string in a file

This is what i am inputting in the console

And this is where it is getting saved in a file



 package Scanner;  
 import java.io.BufferedOutputStream;  
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.util.ArrayList;  
 import java.util.Iterator;  
 import java.util.Scanner;  
 public class ScannerHelper {  
      String line;  
      public static void main(String[] args) throws IOException {  
           // TODO Auto-generated method stub  
           new ScannerHelper().scanner();  
      }  
      public void scanner() throws IOException {  
           Scanner scan = new Scanner(System.in);  
           File f = new File("C:/Test/createdbyscanner.txt");  
           BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));  
           if (f.exists()) {  
                f.delete();  
           }  
           boolean condition = true;  
           ArrayList<String> arraylist = new ArrayList<String>();  
           while (condition) {  
                line = scan.nextLine();  
                arraylist.add(line);  
                if (line.equals(".")) {  
                     break;  
                }  
           }  
           Iterator<String> itr = arraylist.iterator();  
           while (itr.hasNext()) {  
                String scannerLine = itr.next().toString();  
                // System.out.println(scannerLine);  
                try {  
                     System.out.println("from scanner " + scannerLine);  
                     bos.write(scannerLine.getBytes());  
                     bos.write(' ');  
                     bos.write('\n');  
                } catch (IOException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                }  
           }  
           bos.flush();  
           bos.close();  
      }  
 }  

Monday, October 5, 2015

Java reading a file and printing the line number


Example to read a file through Scanner class and print number of lines in the file

INPUT file used (line.txt)


 package sudas.utils;  
 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.util.Scanner;  
 public class LogHelper {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           new logScanner().scanIgnoreCase();  
      }  
 }  
 class logScanner {  
      String path = "C:/Test/line.txt";  
      int lineNumber;  
      public void scanIgnoreCase() {  
           try {  
                Scanner in = new Scanner(new FileInputStream(path));  
                int lineNum = 0;  
                while (in.hasNextLine()) {  
                     String nextline = in.nextLine();  
                     System.out.println(nextline);  
                     System.out.println(lineNum++);  
                }  
           } catch (FileNotFoundException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  
OUTPUT

Apple
0
Banana
1
Orange
2
Grapes
3
Rose
4
Lily
5
Dog
6
Cat
7

Example to read a file through LineNumberReader class and print number of lines in the file



 package LineReader;  
 import java.io.FileReader;  
 import java.io.IOException;  
 import java.io.LineNumberReader;  
 public class GetLineNumber {  
      public static void main(String[] args) {  
           new GetLineNumber().getLineNumber();  
      }  
      public void getLineNumber() {  
           try {  
                LineNumberReader linereader = new LineNumberReader(new FileReader("C:/Test/line.txt"));  
                int reader;  
                while ((reader = linereader.read()) != -1) {  
                     // String contents =linereader.readLine();  
                     // System.out.println(contents);  
                     char c = (char) reader;  
                     System.out.print(c);  
                     if (c == '\n') {  
                          System.out.println(linereader.getLineNumber());  
                     }  
                }  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  
OUTPUT

Apple
1
Banana
2
Orange
3
Grapes
4
Rose
5
Lily
6
Dog
7
Cat

Sunday, October 4, 2015

Have a break !!!


Speed Machine



Java Properties File

Java properties file are use to read project configuration/ utility configuration. Suppose you have a utility which queries the database, for that you may need Username, Password, Hostname which is useful when using a java properties file.
In this tutorial things covered are
1. How to create a property file
2. How to write to property file
3. How to read from property file with key
4. How to read all keys and values from property file



 package Java.property.file;  
 import java.io.BufferedInputStream;  
 import java.io.BufferedOutputStream;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.util.Enumeration;  
 import java.util.Properties;  
 public class PropertyFileExample01 {  
      public static void main(String[] args) {  
           new PropertyFileExample01().setProperties();  
           new PropertyFileExample01().getProperies();  
           new PropertyFileExample01().readAllFromProperties();  
      }  
      // write to the properties file  
      public void setProperties() {  
           /*  
            * and if you want to create the file sudas.properties file.CreateFile  
            * something to do  
            */  
           File file = new File("/Users/S_Das/git/project.chanko/sudas.properties");  
           try {  
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));  
                Properties prop = new Properties();  
                prop.setProperty("hostname", "testHostName");  
                prop.setProperty("username", "testUserName");  
                prop.setProperty("password", "testPassword");  
                /*  
                 * writes the property table to the Output stream Parameters: out an  
                 * output stream. comments a description of the property list.  
                 */  
                prop.store(bos, null);  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
      // read from the properties file  
      public void getProperies() {  
           // created a file input stream to read the properties file  
           try {  
                BufferedInputStream bis = new BufferedInputStream(  
                          new FileInputStream(new File("/Users/S_Das/git/project.chanko/sudas.properties")));  
                Properties prop = new Properties();  
                // Reads a property list (key and element pairs) from the input byte  
                // stream.  
                prop.load(bis);  
                // get the properties file  
                String hostname = prop.getProperty("hostname");  
                String usernsme = prop.getProperty("username");  
                String password = prop.getProperty("password");  
                System.out.println(hostname + '\t' + usernsme + '\t' + password);  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
      // This method is not working not able to find the file from class path  
      /*  
       * public void getPropertiesFromClassPath() {  
       *   
       * InputStream inputStream =  
       * PropertyFileExample01.class.getClassLoader().getResourceAsStream(  
       * "/sudas.properties");  
       *   
       * try { Properties prop = new Properties(); prop.load(inputStream);  
       *   
       * String hostname = prop.getProperty("hostname"); String usernsme =  
       * prop.getProperty("username"); String password =  
       * prop.getProperty("password");  
       *   
       * System.out.println(hostname + '\t' + usernsme + '\t' + password);  
       *   
       * } catch (IOException e) { // TODO Auto-generated catch block  
       * e.printStackTrace(); }  
       *   
       * }  
       */  
      // read everything from a property file  
      public void readAllFromProperties() {  
           Properties prop = new Properties();  
           BufferedInputStream bis;  
           try {  
                bis = new BufferedInputStream(  
                          new FileInputStream(new File("/Users/S_Das/git/project.chanko/sudas.properties")));  
                prop.load(bis);  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
           Enumeration<?> values = prop.propertyNames();  
           while (values.hasMoreElements()) {  
                String key = values.nextElement().toString();  
                System.out.println("Key : " + key);  
                String value = prop.getProperty(key);  
                System.out.println("Value : " + value);  
           }  
      }  
 }  

Friday, October 2, 2015

Java Sort ArrayList


Using Comparator to sort the arraylist.


 package CollectionFramework;  
 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.Comparator;  
 import java.util.Iterator;  
 import java.util.List;  
 public class ComparatorAndComparable {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           new Fruits().listOfFruits();  
      }  
 }  
 // example to show the use of comparator and comparable  
 // Use of comparator example. Sorting String Objecy  
 class Fruits {  
      public void listOfFruits() {  
           List<String> fruits = new ArrayList<String>();  
           // this is am array list which accepts String type object  
           // let us have some fruits  
           String s1 = "grapes";  
           String s2 = "Gooseberries";  
           String s3 = "Apple";  
           String s4 = "Zfruit";  
           String s5 = "zafruit";  
           // add these fruits to the arrayList  
           fruits.add(s1);  
           fruits.add(s2);  
           fruits.add(s3);  
           fruits.add(s4);  
           fruits.add(s5);  
           // Collections.sort(fruits); // this will only work if all the fruit  
           // starts with same case  
           Collections.sort(fruits, new Comparator<String>() {  
                @Override  
                public int compare(String o1, String o2) {  
                     // TODO Auto-generated method stub  
                     return o1.compareToIgnoreCase(o2);  
                }  
           });  
           Iterator<String> it = fruits.iterator();  
           while (it.hasNext()) {  
                String value = it.next();  
                System.out.println(value);  
           }  
      }  
 }  

Using Comparable to sort arraylist
 package CollectionFramework;  
 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.Iterator;  
 import java.util.List;  
 public class ComparatorAndComparable {  
      public static void main(String[] args) {  
           new fruitArrayList().fruitArray();  
      }  
 }  
 // when we are comparing any object then use comparable  
 class FruitsName implements Comparable<FruitsName> {  
      String name;  
      public void fruitName(String name) {  
      }  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
      @Override  
      public int compareTo(FruitsName o) {  
           // TODO Auto-generated method stub  
           return this.name.compareToIgnoreCase(o.getName());  
      }  
 }  
 class fruitArrayList {  
      public void fruitArray() {  
           List<FruitsName> fruitnameArray = new ArrayList<>();  
           // create a fruit Object  
           FruitsName orange = new FruitsName();  
           orange.setName("Orange");  
           FruitsName apple = new FruitsName();  
           apple.setName("apple");  
           FruitsName grapes = new FruitsName();  
           grapes.setName("Grapes");  
           fruitnameArray.add(orange);  
           fruitnameArray.add(apple);  
           fruitnameArray.add(grapes);  
           Collections.sort(fruitnameArray);  
           Iterator<FruitsName> itr = fruitnameArray.iterator();  
           while (itr.hasNext()) {  
                System.out.println(itr.next().getName());  
           }  
      }  
 }  

Thursday, October 1, 2015

Java exception handling and creating custom exception


Below example shows how to use Java lag predefined exceptions in two ways as throws in method signature and using try catch cause.
This example also shows how to create your own exception/ user defined exception



 package ExceptionHandler;  
 import java.io.File;  
 import java.io.IOException;  
 public class ExceptionTutorial {  
      public static void main(String[] args) {  
           try {  
                new ExceptionTutorial().TestFileException();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
           new ExceptionTutorial().TestFileException1();  
           new TestCustomExceptions().checkMobilePhoneName("ddd");  
      }  
      /*** Example about Java in built exception class ***/  
      /*  
       * Method "TestFileException" is throwing IOException and try catch block on  
       * main method where "TestFileException" method's object is created is  
       * catching the IO exception  
       */  
      public void TestFileException() throws IOException {  
           File file = new File("C:/does_not_exist");  
           file.createNewFile();  
      }  
      public void TestFileException1() {  
           File file = new File("C:/does_not_exist");  
           try {  
                // here I am using the createNewFile method, this method throws  
                // IOException - If an I/O error occurred.  
                // the catch block is catching the IO exception  
                file.createNewFile();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  
 /*** Example about Java custom exception / user defined exception ***/  
 /*  
  * This exercise is to built a custom exception class Use the custom exception  
  * class in your method and throw the exception  
  *   
  */  
 class UserException extends RuntimeException {  
      public UserException(String message) {  
           super(message);  
      }  
 }  
 // create a method which will throw the custom exception created  
 class TestCustomExceptions {  
      public void checkMobilePhoneName(String name) throws UserException {  
           if (name.contentEquals("apple")) {  
                System.out.println("This is a iPhone");  
           } else {  
                throw new UserException("Wrong phone");  
           }  
      }  
 }  

OUTPUT
java.io.IOException: Access is denied
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
at ExceptionHandler.ExceptionTutorial.TestFileException(ExceptionTutorial.java:31)
at ExceptionHandler.ExceptionTutorial.main(ExceptionTutorial.java:11)
java.io.IOException: Access is denied
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
at ExceptionHandler.ExceptionTutorial.TestFileException1(ExceptionTutorial.java:40)
at ExceptionHandler.ExceptionTutorial.main(ExceptionTutorial.java:17)

Exception in thread "main" ExceptionHandler.UserException: Wrong phone
at ExceptionHandler.TestCustomExceptions.checkMobilePhoneName(ExceptionTutorial.java:68)
at ExceptionHandler.ExceptionTutorial.main(ExceptionTutorial.java:18)


This is an example to show how to continue with the program execution after exception is raised. Using for loop.


 package Robo.RoboFramework;  
 public class DisplayName {  
      public static void main(String[] args) {  
           new DisplayName().tryCatch();  
           /*  
            * try { new DisplayName().tryCatch(); } catch (CustomException e) { //  
            * TODO Auto-generated catch block e.printStackTrace(); }  
            */  
      }  
      // A method throwing an exception  
      String cityName[] = { "Pune", "pune", "Delhi" };  
      public void displayCityName(String cityName) throws CustomException {  
           System.out.println("City Name : " + cityName);  
           if (!cityName.equals("Pune")) {  
                throw new CustomException("This is not Pune");  
           } else if (cityName == "Pune") {  
                System.out.println("This is Pune");  
           }  
      }  
      // using try catch to catch the exception and continue with execution  
      // using the try catch inside the for loop  
      public void tryCatch() {  
           int i;  
           for (i = 0; i < cityName.length; i++) {  
                // continue;  
                try {  
                     new DisplayName().displayCityName(cityName[i]);  
                } catch (CustomException c) {  
                     System.out.println("EXCEPTION RAISED");  
                }  
           }  
      }  
      class CustomException extends RuntimeException {  
           public CustomException(String message) {  
                super(message);  
           }  
      }  
 }  


OUTPUT
City Name : Pune
This is Pune
City Name : pune
EXCEPTION RAISED
City Name : Delhi
EXCEPTION RAISED