June 15, 2015

Jmeter CookieManager Code


If you need to update your Cookies, like in my case I need to add double quotes to one variable.
Following code was helpful:


import org.apache.jmeter.protocol.http.control.Cookie;
import org.apache.jmeter.protocol.http.control.CookieManager;

CookieManager manager = ctx.getCurrentSampler().getProperty("HTTPSampler.cookie_manager").getObjectValue();
value = ${authorizationcode};
Cookie cookie = new Cookie("Authorization", ('"' + value + '"')  , sampler.getDomain(), sampler.getPath(), false, System.currentTimeMillis());
manager.add(cookie);
sampler.setCookieManager(manager);

April 13, 2015

Selenium Webdriver Coding Tips

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;


public class webdriverClass  {

public static void main(String[] args) throws InterruptedException, ParseException, IOException{

/* ProfilesIni profile= new ProfilesIni();
FirefoxProfile fp = profile.getProfile("second");
FirefoxDriver driver = new FirefoxDriver(fp);
               driver.get("http://google.com"); */

WebDriver driver = new FirefoxDriver();
driver.get("http://www.abc.com");
driver.manage().window().maximize(); // Maximize the browser windows
// Input web element, like text box
String x = driver.findElement(By.xpath("//*[@id='blq-search-q']")).getAttribute("name"); // Reading from webpage
System.out.println(x);
driver.findElement(By.xpath("//*[@id='blq-search-q']")).sendKeys("myname");  // Writting to web page

driver.findElement(By.xpath("//*[@id='blq-search-q']")).clear();  // Clear value on text box

driver.findElement(By.xpath("//*[@id='blq-search-q']")).click();  // Click on Button

driver.findElement(By.xpath("//ul[@id='blq-search-q']/li[1]/a")).click();  // Click on Link using Xpath
driver.findElement(By.xpath("//ul[@id='blq-search-q'] li:nth-child(1) a")).click();  // Click on Link using cssSelector
     
//Drop Down and select
WebElement dropSelect= driver.findElement(By.xpath("//*[@id='blq-search-q']")); // To Choose option from drop down list
List <WebElement> dropdown = dropSelect.findElements(By.tagName("option"));
for (int i=0; i <dropdown.size();i++)
System.out.println(dropdown.get(i).getText()+ dropdown.get(i).getAttribute("Selected"));

// Radio Buttons/Check boxes
List <WebElement> radioButtons= driver.findElements(By.xpath("//input[@name='groupName']"));
for (int i=0; i <radioButtons.size();i++)
  System.out.println(radioButtons.get(i).getText()  + radioButtons.get(i).getAttribute("checked"));

// Hidden components/links isDisplayed

List <WebElement> links= driver.findElements(By.tagName("a"));
for (int i=0; i <links.size();i++)
  System.out.println(links.get(i).getText()  + links.get(i).isDisplayed());

// Screen Shots of Webpages

File src =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(src, new File("C:\\google.jpg"));  /// change the name each time you run the code
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//Implicit wait, Global
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); // Maximum Wait 30secs
//Once written, it applicable on all driver based Action, its global

// Explict Wait, local to Action, FluentWait and WebdriverWait
//WebdriverWait
WebDriverWait webwait = new WebDriverWait(driver,20); // Creating a refrence and using it mutiple times
driver.get("http://www.bbc.com");
driver.findElement(By.xpath("//*[@id='blq-search-q']")).click();
//Waiting for element to appear
webwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='blq-page-class']")));

//FluentWait with Polling and Ignoring the exception
new FluentWait<WebDriver>(driver)  //
      .withTimeout(30, TimeUnit.SECONDS)
      .pollingEvery(5, TimeUnit.SECONDS)
      .ignoring(NoSuchElementException.class).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='blq-page-class']")));

// Page loading time out
driver.manage().timeouts().pageLoadTimeout(30,TimeUnit.SECONDS);

// Thread Sleep
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  // sleep for 5 sec

// Handling pop-up or multiple windows

Set set = new HashSet();  // No index like error, duplicate elements not allowed
set.add("Cars");
set.add("Truck");
set.add("Bus");
set.add("Bike");

Iterator itr = set.iterator();
while(itr.hasNext())
System.out.println(itr.next());

// Actual Usage for windows handle for popups
Set<String> winIds = driver.getWindowHandles();
Iterator<String> itrwin = winIds.iterator();
System.out.println(winIds.size());
String mainWindow = itrwin.next();
String popup =  itrwin.next();
driver.switchTo().window(popup);
driver.close();
driver.switchTo().window(mainWindow);

// Handling alerts

Alert alert = driver.switchTo().alert();
alert.accept();
driver.switchTo().defaultContent();

      // Handling SSL certificate popups
Set<String> httpsWin  = driver.getWindowHandles();
Iterator<String> itrhttps = httpsWin.iterator();
System.out.println(httpsWin.size());
String mainWin = itrhttps.next();
String httpswin =  itrhttps.next();
driver.switchTo().window(httpswin);

 // For Firefox
FirefoxProfile fp = new FirefoxProfile();
fp.setAcceptUntrustedCertificates(true);  // This will handle trust in most cases
fp.setAssumeUntrustedCertificateIssuer(false); // if not then use this command also
 // For Chrome
System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
// For IE
driver.navigate().to("javascript:document.getElementByID(''overridelink).click()");
} 

// Mouse movements
Actions action = new Actions(driver);
WebElement menu = driver.findElement(By
.xpath("//*[@id='blq-page-class']"));
action.moveToElement(menu).build().perform();
// if its not working then we can use
// FirefoxProfile = profile = new FirefoxProfile();
// profile.setEnableNativeEvents(true);
//WebDriver driver = new FirefoxDriver(profile);
// for Chrome
// System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
// WebDriver driver = new ChromeDriver();



// Random selection
Random random = new Random();
int number = random.nextInt(100);
System.out.println(number);

WebElement alllinks = driver.findElement(By
.xpath("//*[@id='blq-page-class']"));
List<WebElement> linklist = alllinks.findElements(By.tagName("a"));
int sizet = linklist.size();
Random r = new Random();
linklist.get(r.nextInt(sizet)).click(); // clicking random link on web page

// Dragging Filter range
WebElement p = driver
.findElement(By.xpath("//*[@id='blq-page-class']"));
action.dragAndDropBy(p, -100, 0).build().perform();

// Scrolling
int x1 = p.getLocation().x;
action.clickAndHold(p).dragAndDropBy(p, x1,100).build().perform(); // same can be used for drag and drop also

// The drag and Drop by element will accept two webelement, one source with destination

// Working with WebTable/ Tables - Defining xpath
// xpath - //table[@class= 'dataTable']/tbody/tr/td[2] -- complete 2
// column
// xpath - //table[@class= 'dataTable']/tbody/tr[4] -- complete 4 row


// Upload file from browse window with code
driver.findElement(By.xpath("//input[@id='browse-button-q']"))
.sendKeys("c:\\image.jpg");

// Upload using AutoIT tool if we face issues in upload
// You can create exe to perform windows actions, which can then be
// integrated with Java code


Process process = new ProcessBuilder("c:\\temp.exe",
"c:\\image.jpg", "Open").start();


/* Auto IT code for generation of exe

  $windowHandle = WinGetHandle("File Upload") WinActivate($windowHandle)
ControlSetText("File Upload", "", "[CLASS:Edit; INSTANCE:1]",
$CmdLine[1]) ControlClick("File Upload", "",
"[CLASS:Edit; INSTANCE:1]")


*/

// Click with mouse and hold the element
action.moveToElement(
driver.findElement(By.xpath("//input[@id='browse-button-q']")))
.clickAndHold(
driver.findElement(By
.xpath("//input[@id='browse-button-q']")))
.build().perform();
Thread.sleep(5000);
action.release(driver.findElement(By
.xpath("//input[@id='browse-button-q']")));

// Working with iFrames , check by right clicking section of web page
// with mouse and option "This Frame"appears
// Identify the frame in which our xpath belongs to and then use teh no.
// to switch to it

driver.switchTo().frame(0);
int s = driver.findElements(By.tagName("iFrame")).size();
for (int i = 0; i < s; i++) {
driver.switchTo().frame(i);
int t = driver.findElements(
By.xpath("//input[@id='browse-button-q']")).size();
System.out.println(t);
driver.switchTo().defaultContent();
}

// Verifying Cookies Values
Set<Cookie> cookies = driver.manage().getCookies();
Iterator<Cookie> citr = cookies.iterator();
while (itr.hasNext()) {
Cookie c = citr.next();
System.out.println(c.getDomain() + "--" + c.getName() + "--"
+ c.getValue());
}
driver.manage().deleteAllCookies();

// Pressing Enter or Escape etc key
driver.findElement(By.xpath("//*[@id='blq-search-q']")).sendKeys(Keys.ENTER);


// Verifying or Validating if element is present or not


String part1 = "//*[@id='blq-search-q']/table/tbody/tr[";
String part2 = "]td";
for (int i = 0; i < sizet; i++){
boolean xpathfound = isElementPresent(part1+i+part2);
while (xpathfound)
driver.findElement(By.xpath(part1+i+part2)).click();

Assert.assertTrue(xpathfound, "Xpath found");
}

// File upload
driver.findElement(By.xpath("//input[@id='filename']")).sendKeys("c:\\test.jpeg");

// handling Calendar
String currentdate = "24/04/2015";
String months[] = { "January", "Februray", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
Date date = dateFormat.parse(currentdate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);

int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);

String forwardClick = "//div[@class='calendar']/table/ttable/tr[2]/td[2]/div";
String myMonth = months[month] + ", " + year ;
String xpathMonthYear = "//div[@class='calendar']/table/ttable/tr[1]/td[1]/div";

while (!driver.findElement(By.xpath(xpathMonthYear)).getText().equals(myMonth))
driver.findElement(By.xpath(forwardClick)).click(); // Keep clicking on forward arrow til we get the month we want

String calPart1 ="//div[@class='calendar']/table/ttable/tr[";
String calPart2 ="]/td[";
String calPart3 ="]/div";
int convDateCal=0;
for(int num= 1; num <6; num++){
for(int num2= 2; num2 <8; num2++){
String dateCal = driver.findElement(By.xpath(calPart1 + num + calPart2 + num2 + calPart3)).getText();
if (!dateCal.equals("")){
convDateCal= Integer.parseInt(dateCal);
}
if(convDateCal == day ){
driver.findElement(By.xpath(calPart1 + num + calPart2 + num2 + calPart3)).click();
}
}
}

// Managing Windows Alerts or windows message box
Alert alert1 = driver.switchTo().alert();
alert1.accept();
alert1.dismiss();
driver.switchTo().defaultContent();

// front and back button of web page
driver.navigate().to("http://google.com"); // use navigate instead of get
driver.navigate().back();
driver.navigate().forward();

// Downloading file using profile by creating own profile
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2); // to be set by default
profile.setPreference("browser.download.dir", "c:\\data"); // directory path for download path
profile.setPreference(" browser.helperApps.neverAsk.saveToDisk", "application/msword,application/x-rar-compressed "); //MIME types

WebDriver drivernew = new FirefoxDriver(profile);
drivernew.get("http://testsite.com");
drivernew.findElement(By.xpath("//path/a[1]")).click();


// Handling Dynamic movement options which appear and disappear fast, like menu drop down
// If ui/li is present then use Actions

System.out.println(driver.findElement(By.xpath("//input[@id='browse-button-q']")).isDisplayed());

WebElement xpath_root = driver.findElement(By.xpath("//input[@id='browse-button-root']/ul/li"));
WebElement xpath_sub = driver.findElement(By.xpath("//input[@id='browse-button-q']/ul/li"));
Actions action1 = new Actions(driver);
action1.moveToElement(xpath_root).build().perform();
xpath_sub.click();

// Executing JavaScript functions present on page, if no ui/li is there but javascript is there
// calling javascript like fun('myfunc') for some dynamic action, use page source to get function name
// It can be use to select drop down, radio button , list

// Webdriver is firing Javascript in back ground
((JavascriptExecutor) driver).executeScript("fun('myfunc')"); // script name
((JavascriptExecutor) driver).executeScript("document.getElementById('radiotype').click()"); // document is of html and we are using id

//Listener Class, Mouse Movement

/*
public class listnerClass implements AbstractWebDriverEventListner
public void afterNavigateBack(WebDriver webdriver){
}

IN the main class
WebDriver webDriver = new FirefoxDriver();
EventFiringWebDriver driver = new EventFiringWebDriver(webDriver);
listnerClass listnerclass = new listnerClass();
driver.register(listnerclass);
// Listner class is used to perform any action prior or before

EventFiringMouse mouse = new EventFiringMouse(driver, listnerclass);

driver.get("http://testpage.com");

// Replication mouse movement on webpage
Locatable overItem = (Locatable) driver.findElement(By.xpath("//*[id@='bar']"));
Coordinates cor = overItem.getCoordinates();
try{
mouse.mouseMove(cor);
}catch{(Exception e1){
}

// Right clicking on a link
driver.findElement(By.xpath("//input[@id='browse-button-q']")).sendKeys(Keys.chord(Keys.SHIFT,Keys.F10));

// x and Y co=ordinates of a link
Point p = driver.findElement(By.xpath("//input[@id='browse-button-q']")).sendKeys(Keys.chord(Keys.SHIFT,Keys.F10));
System.out.println(p.x);
System.out.println(p.y);

*/


// If there is no ui/li(xpath for say) then try javascript, and if that also doesn't work then use mouse over 


}
public static boolean isElementPresent(String xpathfile) {
int size = driver.findElements(By.xpath(xpathfile)).size();
if (size > 0)
return true;
else
return false;
}

}

April 12, 2015

Quickly Configuring Jenkins

Installing jenkins with SVN
Download WAR file from
https://updates.jenkins-ci.org/download/war/

run Following command after copying jenkins.war file to bin folder of Java
java -jar jenkins.war --httpPort=9090

or on Linux  https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+on+Red+Hat+distributions

and access Jenkins... http://localhost:9090
Now update the SVN Pluggin from Manage Plugins,
(Manage Jenkins-> Configure System). In the "Maven Installations" section,
1) click the Add button,
2) give it a name such as "Maven 3.2.2" and then
3) choose the version from the drop down.

Then go to New Item --> Choose Maven Project, and create project name
Run on build first and let it create empty workspace
Now go to Home and choose your project --> Configure
Configure --> Source Code Management --> Subversion (Add Repository URL)

Build Triggers -- > Poll SCM :  for Automatic Scheduling H(0-30) 8 * * *
E-mail Notification --> to send update on build

Add,
Subversion Tagging Plugin
Zentimestamp plugin
Next Build Number Plugin

Manage Jenkins -> Configure System
Global properties --> Date pattern for the BUILD_ID (build timestamp) variable --> YYYY-MM-DD_hh-mm-ss
Jenkins Location --> System Admin e-mail address --> myemail@mail.com
E-mail Notification --> SMTP server (smtp.office365.com)
Default user e-mail suffix @company.com
Use SMTP Authentication User Name myemail@mail.com Password
SMTP Port 587

And configure Email notifications  Add from address in System Admin e-mail address under the Jenkins Location
And then add SMTP details together with from Address




April 07, 2015

Working with Selenium Webdriver

Selenium works only for browser based application not for windows based application.
There are some browser tools that you can use in order to identify web elements in the DOM easily. These are:

Firepath and Firebug for Firefox  -- Press F12. You can use Inspector to identify objects
Google Developer Tools for Chrome -- By Default Inspector is avaliable on right click or hit F12 to identify objects
Web Inspector for Safari

Open the desired web page, right-click the desired element and click on Inspect Element.

    1. By ID: in Java: driver.findElement(By.id("element id"))
    2. By CLASS: in Java: driver.findElement(By.className("element class"))
    3. By NAME: in Java: driver.findElement(By.name("element name"))
    4. By TAGNAME: in Java: driver.findElement(By.tagName("element html tag name"))
    5. By CSS Selector: in Java: driver.findElement(By.cssSelector("css selector")) -- Mostly used
    6. By Link: in Java: driver.findElement(By.link("link text"))
    7. By XPath: in Java: driver.findElement(By.xpath("xpath expression"))  -- Mostly used

Difference of Syntax between CSS and XPATH:

        driver.findelement(By.xpath("input[id='Email'] and [class='Gmail']/p");
        driver.findelement(By.cssSelector("input[id='Email'] [class='Gmail'] p");
        driver.findelement(By.cssSelector("#Email");

Performing partial match on attribute values

        ^= as in input[id^='email'] means Starting with.
        $= as in input[id$='_name'] means Ending with.
        *= as in Input[id*='userName'] means Containing.

Finding elements with XPATH

Absolute path
    WebElement userName =
           driver.findElement(By.xpath("html/body/div/form/input"));
Relative path
    WebElement email = driver.findElement(By.xpath("//input"));

Finding elements using index
    WebElement email =
           driver.findElement(By.xpath("//input[3]"));

Finding elements using attributes/custom values with XPath

WebElement logo =
           driver.findElement(By.xpath("img[@alt='logo']"));


For XPATH we can also use:
    starts-with()

        input[starts-with(@id,'input')]
        Starting with: input

    ends-with()

        input[ends-with(@id,'_field')]
        Ending with: _field

    contains()

        input[contains(@id,'field')]
        Containing: field

Locating table rows and cells:
@Test
public void testTable() {
   WebElement simpleTable = driver.findElement(By.id("items"));

   //Get all rows
   List rows = simpleTable.findElements(By.tagName("tr"));
   assertEquals(3, rows.size());

   //Print data from each row
   for (WebElement row : rows) {
      List cols = row.findElements(By.tagName("td"));
      for (WebElement col : cols) {
         System.out.print(col.getText() + "\t");
      }
   System.out.print();
   }
}

Using jQuery selectors

Locate all the Checkbox which are checked by calling jQuery find() method.
find() method returns elements in array

List elements =
        (List) js.executeScript("return jQuery.find(':checked')");





Always Use Page Factory for synchronizations:

Use PageFactory with AjaxElementLocatorFactory - PageFactory which is a support class for the Selenium 2 Page Objects pattern which we are using, and the AjaxElementLocatorFactory is the factory for the element locators. In our case the constructor will looks like:

        public GoogleResultsPage() {
             PageFactory.initElements(new AjaxElementLocatorFactory(driver, 15), this);
        }

This code will wait maximum of 15 seconds until the elements specified by annotations will appear on the page, in your case the homePageLink which will be located by xpath. You will not need to use ElementPresent class.

You can also use Pagefactory, and have something like:

      @FindBy(how = How.NAME, using = "logonName")
          private WebElement logonNameField;

     @FindBy(how = How.NAME, using = "password")
         private WebElement passwordField;

Now, as for How., you can have:

       CLASS_NAME
       CSS
       ID
       ID_OR_NAME
       LINK_TEXT
       NAME
       PARTIAL_LINK_TEXT
      TAG_NAME
      XPATH
      class
Or you can use your own DOM Search plus Xpath, that would be outside of WebDriver API , but it should work.

       driver.findElement(By.id("user_firstName")).sendkey();

instead we use

      @FindBy(id ="user_firstName")
          WebElement firstName;


Optimizing the usage of Hardware:
 Create Various Profiles in the browser which has altogether different propertiies (CMD: firefox.exe -p profilemanager)

     Profiles.ini profile= new Profiles.ini();
     FirefoxProfile fp = profile.getProfile("NewFirefoxProfile");
     FirefoxDriver driver = new FirefoxDriver(fp);

Then using DesiredCapabilities we can open different profiles browser running differnet script altogether

 DesiredCapabilities capability = DesiredCapabilities.firefox();
     capability.setBrowserName("firefox");
     capability.setPlatform(Platform.WIN8_1);
     FirefoxDriver driver = new FirefoxDriver(capability);          

Execution without browser
HTMLUnit driver Class is used if we dont want to open any browser, execution happens without browser being opened
     HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3);

April 02, 2015

Learning Java for Selenium


  • Install Java and Download Eclipse IDE EE for Java Developers editor (both are free for download).
  • Run eclipse.exe and create a folder and select it as workspace
  • Then go to File --> New --> Java Project or others then Java Project
  • Now write the Project name and click Finish
  • Now your Project will be shown in Package Explorer
  • Expand it
  • Go to src folder --> right click it --> create a New Java Class (No space in name) togther with checked Public Static Void main
  • All colored words in eclipse code are reserved. You can execute code with Run button from eclipse and see result in console below.


myclass.java

import java.io.*;
import java.util.Properties;
import java.util.logging.Logger;
import org.apache.log4j.*;
import org.apache.poi.hssf.usermodel.*;

public class myclass  { 


//Execution starts from here
public static void main(String[] args) throws IOException { // Main Function


// Data types

int i  = 32; //max 32 bits
long j = 64; //max 64 bit
double k = 2.34; // decimal and integer numbers
char l = 'a'; // single character
boolean m = true; // True or False

String string; // Its not a data type but a String Class, though often used

// Conditional operators print the result as True or False

System.out.println(22>11); 
// > < <= >= == != are other conditional operators

// Control flow operators

int x = 5;
int y = 7;

// if else
if (y>x) {  

// Concatenation of String and Number in output result

System.out.println(" Print the result  " + x); 
} else {
System.out.println(" Print the result  " + y);
}

// while loop
while (x < 10){
System.out.println(x); 
x= x+1; // x++ is also same
}

// for loop

for (int q = 0; q<10; q++){
System.out.println("for loop print " + q); 
}

// Logical/bitwise Operators,  & and | used with both integral and boolean variables, 
// while && and || used with only boolean operands

int z = 9;
if (y>x & y>z ) {  
System.out.println("Y is greatest"); 
} else if (x>y & x>z ) {
System.out.println("X is greatest");
} else if  (y>x & z>y )  {
System.out.println("Z is greatest");
}


// One Dimensional Arrays
String strg[]= new String[3]; // int i[] = new int[3]; char c[] = new char[3]; 
// Object obj[] = new Object[3]; ... we can add multiple data types
strg[0] = "abc";
strg[1] = "xyz";
strg[2] = "pqr";
System.out.println(strg[0] + strg[1]  + strg[2]);
System.out.println(strg.length);

// Two Dimensional Arrays
String str[][]= new String[3][4]; // 3 rows, 4 columns
//First Row
str[0][0] = "A01";
str[0][1] = "B02";
str[0][2] = "C03";
str[0][3] = "D03";
//Second Row
str[1][0] = "A11";
str[1][1] = "B12";
str[1][2] = "C13";
str[1][3] = "D13";
//Third Row
str[2][0] = "A21";
str[2][1] = "B22";
str[2][2] = "C23";
str[2][3] = "D23";

for(int rownum=0; rownum<str.length; rownum++){
for(int colnum=0; colnum<str[0].length; colnum++){
System.out.print(str[rownum][colnum]+ "  ");
}
System.out.println();
}
/////////////////////////////////////////////////////////////////////
// Function
myfunction(); // Call Function
myAddfunction(1,2,3); // Call Function n number of times
myAddfunction(5,6,7);
int retValue = myAddReturnfunction(8,9,10);
System.out.println(retValue);
////////////////////////////////////////////////////////////////////////
// Inheritance 
//ObjClass.java is Child Class and newClass.java is Parent Class 
objClass obj1 = new objClass();
obj1.funChild();  // Function inherited by objClass Child Class from Parent/Super newClass 
obj1.printInheritance(); // Create Object of Child Class and Inherit functions of Parnet and Child both

newClass obj2 = new newClass();
obj2.printInheritance(); // Create Object of Parent Class and use functions


newClass obj3 = new objClass(); // Create Reference which is of Parent and Object is Child class
obj3.funChild(); // Parent Class
obj3.printInheritance(); // If overridden then called from Child Class
// Using this we can only call functions of Parent Class 

// Interface
myInterface obj4 = new newClass();
//obj4.func3();  Cannot access the function defined in newclass only the myInterface
// we can only access function that are defined in myInterface and overridden in newClass
obj4.func1();

newClass obj5 = new newClass();
obj5.func3(); //We can access functins defined in newclass


// Text File reading and writing
//Creating the file 

File file = new File ("C:\\temp\\newfile.txt");
    file.createNewFile();
// Writing to the file
    FileWriter writefile = new FileWriter("C:\\temp\\newfile.txt");
    BufferedWriter out = new BufferedWriter(writefile);
    out.write("name= the new text");
    out.newLine();
    out.flush();
// Reading from the file    
    FileReader readfile = new FileReader("C:\\temp\\newfile.txt");
    BufferedReader in = new BufferedReader(readfile);
    System.out.println(in.readLine());
//Reading from  Properties File , variable - value pair
    Properties prop = new Properties();
    FileInputStream fis = new FileInputStream("C:\\temp\\newfile.txt");
    prop.load(fis);
    System.out.println(prop.getProperty("name"));
    System.out.println(System.getProperty("user.dir")); // Identifying current directory
    
// Reading from excel file, need external jar of POI API| Apache POI - the Java API for Microsoft Documents
    //http://poi.apache.org/spreadsheet/quick-guide.html
    
    HSSFWorkbook wb = new HSSFWorkbook();
    FileOutputStream fileOut = new FileOutputStream("C:\\temp\\workbook.xls");
    wb.write(fileOut);
    fileOut.close();
   
    
// Using Log4J | External jar log4j is required... need to add log4j.properties to src folder
       
   /*       log4j.rootLogger=DEBUG, stdout, file
            log4j.appender.file=org.apache.log4j.RollingFileAppender
    log4j.appender.file.File=C:\\log4j-application.log
    log4j.appender.file.MaxFileSize=5MB
    log4j.appender.file.MaxBackupIndex=10
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n  */
    
    PropertyConfigurator.configure("log4j.properties");
    Logger logger = Logger.getLogger("myclass.class");

    logger.info("Logging input here");

}

public static void myfunction() { // New Function
System.out.println(" My Function");
}

public static void myAddfunction(int a, int b, int c) { // New Function with arguments
int sum = a+b+c;
System.out.println(sum);
}

public static int myAddReturnfunction (int a, int b, int c) { // New Function with arguments, with return
int sum = a+b+c;
return sum;
}

}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
objClass.java

// package obj ; --- for package obj  and for accessing functions/variables import obj.newClass; in that class
public class objClass extends newClass  {  // extends inherits all properties functions/variable

// Access modifier
// public -- accessible from all everywhere
// default -- accessible in current package 
// protected -- accessible in current package and child classes
// private -- accessible in current class only


String name; // Non Static Global variables can be used across
int num, num1, num2, num3 ;
int number= 10;
static int grade= 5; // Now if we want values of variable/function to be "constant" across all objects then use static. 
// Static variables resides in common location, and they are not part of Objects

//contructor, it help in initializing the object
public objClass(){  // No return type for constructor
System.out.println("Constructor is called everytime object of class is created");
}
//constructor with parameters to intialize object with values
public objClass(int num2, int num3){ //example of overloading, if arguments are different
this.num2 = num2; // If we write num2 = num2 then it will not use Global variable and use local only and do comparison
   this.num3 = num3; // this will always point to current object and global variables will be avaliable
}
public static void main(String[] args) {

objClass obj = new objClass(); 
// obj is reference to the object (or point towards the object in memory) and " new object" is the memory object
// and we can access all non static functions/variable in object using this reference, since we cannot access non static things from static

obj.name = "name"; // All variables/function reside in object (memory location)
obj.num = 10;
obj.func();

objClass obj2 = new objClass(); // Another reference is created for new memory location of Object
obj2.name = "name2";
obj2.num = 102;
obj2.func();

objClass obj3 = new objClass();
obj3=obj2; // Multiple references can point to same Object


objClass.staticfunc(); // Directly with class name
obj.staticfunc(); //Static functions should not be called using object, they should either be called with class or directly
staticfunc(); //directly
//non static functions have to be called with the help of objects

System.out.println(grade);
// But System.out.println(num); will not get printed as static can access only static function/variable
// Non static variables can only be accessed via object

// Passing Object to function for Action
objClass obj4 = new objClass();
obj4.num1 = 10;
System.out.println(obj4.num1);
changeObj(obj4.num1); //New Values will not update as Object reference is still to old variable
System.out.println(obj4.num1);
changeObjVal(obj4); // Passed whole object and the new Values get updated 
System.out.println(obj4.num1);

objClass obj5 = new objClass(50,60);
System.out.println(obj5.num2);
System.out.println(obj5.num3);

// String Class String str = " This is test String"; System.out.println(str.indexOf("s")); // first occurrences of letter s in string String temp[]=str.split(" "); // Split the string on the basis of space for(int j=0;j<temp.length; j++){ System.out.println(temp[j]); } // Converting data types String i = "10"; int j = Integer.parseInt(i); String k = String.valueOf(j);

}

public void func(){ // Non Static functions can access both static and non static
System.out.println(grade);
System.out.println(number);
int i = 2; // local variable inside function 
}
public static void staticfunc(){ // Static functions can access only static functions/global variables etc
System.out.println(grade);
// System.out.println(number);.... this will not work
int j = 2; // local variable inside function 
}

public static void changeObj(int a){
a = 30;
}
public static void changeObjVal(objClass x ){
x.num1 = 30;
}

public void printInheritance(){
System.out.println("Child Inheritance");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
newClass.java


import java.util.ArrayList;
import java.util.Hashtable;


public class newClass implements myInterface {  // Its inheriting Interface and has to implement all methods of parent class

public void funChild() {

System.out.println("Parent Class");
}


public void printInheritance(){
System.out.println("Parent Inheritance");
}


@Override
public void func1() {
// TODO Auto-generated method stub

}


@Override
public void func2()    {
// TODO Auto-generated method stub

}

//public void func3() throws InterruptedException { // Either use try catch or throws exception handling
// If we need to catch the exception then use try catch else use throws to ignore it
// throw new Exception("some exception");  // throw and throws difference
public void func3()  {
try{    // Exception Handling using Try Catch
int i[]=new int[5];
i[5]= 10;

} catch (Exception e) { // Exception is the inbuild Class and e is the object reference
System.out.println("error" + e.getMessage());
e.printStackTrace();
}

try{    // Exception Handling using Try Catch
int i = 5/0;

} catch (Exception e) { // Exception is the inbuild Class and e is the object reference
System.out.println("error" + e.getMessage());
e.printStackTrace();
} finally { // final a = 10; means its value can't be changed any time; final and finally difference
System.out.println("Always this code is run despite of exception at any level");
}

try {

int i = 5/0;
}catch (Throwable e) { // its a super class of both Error and Exception and captures both

}
// Array List the inBuild Class of Dynamic 
ArrayList<String> list = new ArrayList<String>();  // Array without external boundary of String Type
//ArrayList list = new ArrayList(); // No Type defined
list.add("A");
list.add("B");
System.out.println(list.get(0));

// Hashtable the inBuild Class
Hashtable<String,String> tbl = new Hashtable<String,String>();
//Hashtable tbl = new Hashtable(); // No index in hashtable like Array, but its a Key-Value pair
tbl.put("name","MyName");
tbl.put("Address","MyAddress");
System.out.println(tbl.get("name"));

 }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
myInterface.java

// Its another type used for Inheritance 
public interface myInterface {  // Object of Interface cannot be created
// it only has method declaration & variable but no body

int a = 10;  // Final variable, values can't be changed, it is mandatory to initialize
public void func1();
public void func2();   /// No Static functions

}