Wednesday 29 May 2013

create multiple sheets in excel via java code



package com.ReadAndWriteExcel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.XLSX.ExcelXLSX;

public class Main {
static XSSFWorkbook xssfWorkbook;
static XSSFSheet xssfSheet;

public static void main(String[] args) throws IOException {
int numOfSheet=3;
Vector vectorDataExcelXLSX = new Vector();
Vector<Vector> ParentVector = new Vector<Vector>();
String excelXLSXFileName = "C:\\task\\masterxls\\Config.xlsx";
Workbook wb = new XSSFWorkbook();
FileOutputStream fos = new FileOutputStream("Master.xlsx", true);
File file = new File("C:\\task\\modules");
String[] str = file.list();
String[] SheetNames ={"Test Cases","Test Steps","Test Data"};
for (int var = 0; var < numOfSheet; var++)
{
for (String st : str)
{
vectorDataExcelXLSX = ExcelXLSX.readDataExcelXLSX("C:\\task\\modules\\" + st, var);
ParentVector.add(vectorDataExcelXLSX);
ExcelXLSX.PrintInConsoleDataExcelXLSX(vectorDataExcelXLSX);
}
ExcelXLSX.writeExcelFile(ParentVector, wb, SheetNames[var]);
ParentVector.clear();
}
System.out.println("Excel file has been generated!");
wb.write(fos);
fos.close();
}
}

Read And write Excel:------>

 public static Vector readDataExcelXLSX(String fileName,int SheetNumber) {
    Vector vectorData = new Vector();
        try {
            FileInputStream fileInputStream = new FileInputStream(fileName);
            XSSFWorkbook xssfWorkBook = new XSSFWorkbook(fileInputStream);  
            // Read data at sheet 0
            XSSFSheet xssfSheet = xssfWorkBook.getSheetAt(SheetNumber);    
            Iterator rowIteration = xssfSheet.rowIterator();  
            // Looping every row at sheet 0
            while (rowIteration.hasNext()) {     
                XSSFRow xssfRow = (XSSFRow) rowIteration.next();  
                Iterator cellIteration = xssfRow.cellIterator();  
                Vector vectorCellEachRowData = new Vector();    
                // Looping every cell in each row at sheet 0
                while (cellIteration.hasNext())
                {
                XSSFCell xssfCell = (XSSFCell) cellIteration.next();
                    vectorCellEachRowData.addElement(xssfCell);
                }              
                vectorData.addElement(vectorCellEachRowData);
            }        
        } catch (Exception ex) {    
        ex.printStackTrace();
        }
        return vectorData;
    }


public static void writeExcelFile(Vector<Vector> vectorData, Workbook wb,String sheetName) throws IOException {
Row row;
Cell cell;
String[] cellvalue = null;
        int t=0;
       Sheet sh=wb.createSheet(sheetName); 
for (int i = 0; i < vectorData.size(); i++) {
Vector vectorCellEachRowData = (Vector) vectorData.get(i);
for (int j = 0; j < vectorCellEachRowData.size(); j++) {
String str1=vectorCellEachRowData.get(j).toString().replace("[","");
cellvalue =str1.split(",");
row = sh.createRow((short) t);
                                t++;
for (int k = 0; k < cellvalue.length; k++) {
cell = row.createCell((short) k);
cell.setCellValue(cellvalue[k].replace("]",""));
}
}
System.out.println();
}
}

IMP NOTE---->
Dont Forget to attach POI Jars for XSSf(5 Jars)

Thursday 23 May 2013

ant build for testng


Ant build file for TestNG:->



Sample Ant build.xml file to run TestNG


<?xml version="1.0" encoding="UTF-8"?>
<!--
  Filename: build.xml
  Note: You have to change the followings according to your environment:
          -<pathelement location="lib/testng/testng-5.14.7.jar"/>
          -<pathelement location="bin"/>
-->
<project basedir="." default="testng_nice_report" name="Sample of Ant file for TestNG">

<!-- Define <testng> task -->
<taskdef name="testng" classname="org.testng.TestNGAntTask">
<classpath>
<pathelement location="C:/Selenuim_Automation/Jars and Properties File/jars/testng.jar" />

</classpath>
</taskdef>

<!-- Directory name where the TestNG report will be saved. -->
<property name="testng.output.dir" value="testng_output" />

<!-- Directory path of compiled classes(i.e *.class) -->
<path id="classes">
<pathelement location="C:/Selenuim_Automation/MyAnt/bin" />
<pathelement location="C:/Selenuim_Automation/Jars and Properties File/jars/selenium-server-standalone-2.32.0.jar"/>
<pathelement location="C:/Selenuim_Automation/Jars and Properties File/jars/log4j-1.2.14.jar"/>
</path>

<!--
  Target to run TestNG. It will run according to what are defined in testng.xml.
  The report will be saved at .../testng_output/index.html.
  -->
<target name="runTestNG">

<mkdir dir="${testng.output.dir}" />

<!-- Create the output directory. -->
<testng outputdir="${testng.output.dir}" classpathref="classes">
<xmlfileset dir="." includes="testng.xml" />
</testng>

</target>

<!--
 Example for TestNG-XSLT
   Run this target only after TestNG had generated the xml resutl file(i.e. testng_output/testng-results.xml).
   Change TestNG-XSLT stylesheet path accordingly(i.e. lib/testng-xslt-0.6.2/src/main/resources/testng-results.xsl).
-->
<target name="testng_nice_report"  depends="runTestNG"  >
<mkdir dir="testng_nice_report" />
<xslt in="testng_output/testng-results.xml" style="C:/Selenuim_Automation/MyAnt/src/com/xsl/testng-results.xsl" out="testng_nice_report/index.html">
<param name="testNgXslt.outputDir" expression="C:/Selenuim_Automation/MyAnt/testng_nice_report" />
<param name="testNgXslt.showRuntimeTotals" expression="true" />
</xslt>
</target>


</project>


 Ant testng.xml:


<?xml version="1.0" encoding="UTF-8"?>
<!--
  Filename: testng.xml
  Note: You have to change the following according to your environment:
          -<class name="com.packageName.MyTestClassName" />
-->
<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My Test Suite" >

  <test name="My Test1"  >
    <!--  Add all classes you would like TestNG to run. -->
    <classes>
      <class name="com.LoginViaTestNG.LoginTestt" />  
    </classes>
  </test>

</suite>


Monday 20 May 2013

tower of hanoi android code

<<----------------------"TOWER OF HANOI"---------------------->>


Android Source code:--->Emulator with GPU enables ,Target=above 4.0.1 only


1) Download AndEngine from:---->
https://github.com/nicolasgramlich/AndEngine


2)  TowerOfHanoiActivity.java:------->


import java.io.IOException;
import java.io.InputStream;
import java.util.Stack;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.bitmap.BitmapTexture;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.adt.io.in.IInputStreamOpener;
import org.andengine.util.debug.Debug;

import com.tutorial.towerofhanoi.gameelements.Ring;

public class TowerOfHanoiActivity extends SimpleBaseGameActivity {

private static int CAMERA_WIDTH = 800;
private static int CAMERA_HEIGHT = 480;

private ITextureRegion mBackgroundTextureRegion, mTowerTextureRegion, mRing1, mRing2, mRing3;
private Stack<Ring> mStack1, mStack2, mStack3;
private Sprite mTower1, mTower2, mTower3;

public EngineOptions onCreateEngineOptions() {
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
}

@Override
protected void onCreateResources() {
try {
ITexture backgroundTexture = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
@Override
public InputStream open() throws IOException {
return getAssets().open("gfx/background.png");
}
});

ITexture towerTexture = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {

@Override
public InputStream open() throws IOException {
return getAssets().open("gfx/tower.png");
}
});

ITexture ring1 = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {

@Override
public InputStream open() throws IOException {
return getAssets().open("gfx/ring1.png");
}
});

ITexture ring2 = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {

@Override
public InputStream open() throws IOException {
return getAssets().open("gfx/ring2.png");
}
});
ITexture ring3 = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {

@Override
public InputStream open() throws IOException {
return getAssets().open("gfx/ring3.png");
}
});
backgroundTexture.load();
towerTexture.load();
ring1.load();
ring2.load();
ring3.load();

this.mBackgroundTextureRegion = TextureRegionFactory.extractFromTexture(backgroundTexture);
this.mTowerTextureRegion = TextureRegionFactory.extractFromTexture(towerTexture);
this.mRing1 = TextureRegionFactory.extractFromTexture(ring1);
this.mRing2 = TextureRegionFactory.extractFromTexture(ring2);
this.mRing3 = TextureRegionFactory.extractFromTexture(ring3);

this.mStack1 = new Stack<Ring>();
this.mStack2 = new Stack<Ring>();
this.mStack3 = new Stack<Ring>();
} catch (IOException e) {
Debug.e(e);
}
}

@Override
protected Scene onCreateScene() {
final Scene scene = new Scene();
Sprite backgroundSprite = new Sprite(0, 0, this.mBackgroundTextureRegion, getVertexBufferObjectManager());

mTower1 = new Sprite(0.241f * CAMERA_WIDTH, 0.133f * CAMERA_HEIGHT, this.mTowerTextureRegion, getVertexBufferObjectManager());
mTower2 = new Sprite(0.5f * CAMERA_WIDTH, 0.133f * CAMERA_HEIGHT, this.mTowerTextureRegion, getVertexBufferObjectManager());
mTower3 = new Sprite(0.756f * CAMERA_WIDTH, 0.133f * CAMERA_HEIGHT, this.mTowerTextureRegion, getVertexBufferObjectManager());

Ring ring1 = new Ring(1, 139, 174, this.mRing1, getVertexBufferObjectManager()) {

@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if(this.getmStack().peek().getmWeight() != this.getmWeight())
return false;
this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
if(pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
checkForCollisionsWithTowers(this);
}
return true;
}
};
Ring ring2 = new Ring(2, 118, 212, this.mRing2, getVertexBufferObjectManager()) {

@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if(this.getmStack().peek().getmWeight() != this.getmWeight())
return false;
this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
if(pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
checkForCollisionsWithTowers(this);
}
return true;
}
};
Ring ring3 = new Ring(3, 97, 255, this.mRing3, getVertexBufferObjectManager()) {

@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if(this.getmStack().peek().getmWeight() != this.getmWeight())
return false;
this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
if(pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
checkForCollisionsWithTowers(this);
}
return true;
}
};

this.mStack1.add(ring3);
this.mStack1.add(ring2);
this.mStack1.add(ring1);

ring1.setmStack(mStack1);
ring2.setmStack(mStack1);
ring3.setmStack(mStack1);
ring1.setmTower(mTower1);
ring2.setmTower(mTower1);
ring3.setmTower(mTower1);

scene.attachChild(backgroundSprite);
scene.attachChild(mTower1);
scene.attachChild(mTower2);
scene.attachChild(mTower3);
scene.attachChild(ring1);
scene.attachChild(ring2);
scene.attachChild(ring3);
scene.registerTouchArea(ring1);
scene.registerTouchArea(ring2);
scene.registerTouchArea(ring3);
scene.setTouchAreaBindingOnActionDownEnabled(true);
return scene;
}

private void checkForCollisionsWithTowers(Ring ring) {
Stack<Ring> stack = null;
Sprite tower = null;

if(ring.collidesWith(mTower1) && (mStack1.size() == 0 || ring.getmWeight() < mStack1.peek().getmWeight())) {
stack = mStack1;
tower = mTower1;
} else if(ring.collidesWith(mTower2) && (mStack2.size() == 0 || ring.getmWeight() < mStack2.peek().getmWeight())) {
stack = mStack2;
tower = mTower2;
} else if(ring.collidesWith(mTower3) && (mStack3.size() == 0 || ring.getmWeight() < mStack3.peek().getmWeight())) {
stack = mStack3;
tower = mTower3;
} else {
stack = ring.getmStack();
tower = ring.getmTower();
}
ring.getmStack().remove(ring);
if(stack != null && tower !=null && stack.size() == 0) {
ring.setPosition(tower.getX() + tower.getWidth()/2 - ring.getWidth()/2, tower.getY() + tower.getHeight() - ring.getHeight());
} else if(stack != null && tower !=null && stack.size() > 0) {
ring.setPosition(tower.getX() + tower.getWidth()/2 - ring.getWidth()/2, stack.peek().getY() - ring.getHeight());
}
stack.add(ring);
ring.setmStack(stack);
ring.setmTower(tower);
}
}




3)  Ring.java:---->


import java.util.Stack;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

public class Ring extends Sprite {

private int mWeight;
private Stack<Ring> mStack; //this represents the stack that this ring belongs to
private Sprite mTower;

public Ring(int weight, float pX, float pY, ITextureRegion pTextureRegion, VertexBufferObjectManager pVertexBufferObjectManager) {
super(pX, pY, pTextureRegion, pVertexBufferObjectManager);
this.mWeight = weight;
}

public int getmWeight() {
return mWeight;
}

public Stack<Ring> getmStack() {
return mStack;
}

public void setmStack(Stack<Ring> mStack) {
this.mStack = mStack;
}

public Sprite getmTower() {
return mTower;
}

public void setmTower(Sprite mTower) {
this.mTower = mTower;
}
}


Thursday 16 May 2013

selenium webdriver example



Automation of Login Details:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class LoginTest {

   
    public static void main(String[] args) {
        //WebDriver driver=new FirefoxDriver();
      
 System.setProperty("webdriver.chrome.driver", "C:\\Selenuim_Automation\\ChromeDriver\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();

        //Step 1- Opening Ellamoss site
        driver.get("http://www.ellamos.com/");

        //Step-2 Clicking on My account
        driver.findElement(By.xpath("html/body/form/div[6]/div[1]/div/ul/li[1]/a")).click();

        //Step-3 Entering Email address in the textbox
        driver.findElement(By.xpath("//*[@id='ContentPlaceHolder1_email']")).sendKeys("abc@gmail.com");

        //Step-4 Entering Password in the textbox
        driver.findElement(By.xpath("//*[@id='ContentPlaceHolder1_password']")).sendKeys("pass_123");

        //Step-5 Clicking on Signin button
        driver.findElement(By.xpath("//*[@id='login']")).click();
       
        //Verifications
        //Getting the text from application

        String actText=driver.findElement(By.xpath("html/body/form/div[6]/div[3]/table/tbody/tr[2]/td/span[1]/span")).getText();

        //Expected text
        String expText="abc@gmail.com";
        //actText, exptext Comparison
        if(actText.equals(expText)){
            System.out.println("Strings are equal");
        }else{
            System.out.println("Strings are not equal");
        }

        driver.close();
       
    }

}

Wednesday 8 May 2013

send mail in java


Jar Required:-
1 activation.jar  (Java Application Framework )
2 mail.jar         (Javax.mail.jar)



import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;




public class SendGMail {
String d_email = "from@gmail.com",
d_password = "hellohi",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "to@gmail.com",
m_subject = "hello swami",
m_text = "this is just a test mail";

public SendGMail() {
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");


try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);

MimeMessage msg = new MimeMessage(session);
msg.setText(m_text);
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new
InternetAddress(m_to));
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(d_email, d_password);
}
}

public static void main(String[] args){
     new SendGMail();
}
}



To send mail in webmail just rmeove port number and add your host name.

Monday 6 May 2013

XSSFWorkBook


Five jars are needed to run this:-
1. xmlbeans-2.3.0
2.poi-ooxml-3.5-FINAL
3.poi-3.5-FINAL
4.ooxml-schemas-1.0
5.dom4j-1.6.1(1)

XSSF  is used to read .xlsx  File,while HSSF for .xls

package com.readindExcelusingXSSF;

import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Vector;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;



public class ExcelXLSX {

/* @HELP
@class:    ExcelXLSX
@Singleton Class(if any): nil
@ constructor(if any): given the name of xlsx file and display method is called, ExcelXLSX()
@methods: Main method,Vector readDataExcelXLSX(String fileName),displayDataExcelXLSX(Vector vectorData)
@parameter: respective methods have their own parameters
@notes: reading excel file ie .xlsx using xssf with added five jars of it
@returns: All respective methods have their return types
@END
*/

   
    private Vector vectorDataExcelXLSX = new Vector();
   
    public ExcelXLSX() {
   
    String excelXLSXFileName = "D:/Test_Config.xlsx";
       
    vectorDataExcelXLSX = readDataExcelXLSX(excelXLSXFileName);
       
    displayDataExcelXLSX(vectorDataExcelXLSX);
    }
   
    public static Vector readDataExcelXLSX(String fileName) {
   
    /* @HELP
@class: ExcelXLSX
@method: readDataExcelXLSX()
@parameter:String fileName
@notes: reading xlsx and retriving in a vector
@returns: vector
@END
*/
   
        Vector vectorData = new Vector();
       
        try {
            FileInputStream fileInputStream = new FileInputStream(fileName);
           
            XSSFWorkbook xssfWorkBook = new XSSFWorkbook(fileInputStream);
           
            // Read data at sheet 0
            XSSFSheet xssfSheet = xssfWorkBook.getSheetAt(0);  
           
            Iterator rowIteration = xssfSheet.rowIterator();
           
            // Looping every row at sheet 0
            while (rowIteration.hasNext()) {
           
                XSSFRow xssfRow = (XSSFRow) rowIteration.next();
               
                Iterator cellIteration = xssfRow.cellIterator();
               
                Vector vectorCellEachRowData = new Vector();
               
                // Looping every cell in each row at sheet 0
                while (cellIteration.hasNext())
                {
             
                XSSFCell xssfCell = (XSSFCell) cellIteration.next();
                   
                    vectorCellEachRowData.addElement(xssfCell);
                }
               
                vectorData.addElement(vectorCellEachRowData);
            }
           
        } catch (Exception ex) {
         
        ex.printStackTrace();
        }
       
        return vectorData;
    }
   
    public static void displayDataExcelXLSX(Vector vectorData) {
   
    /* @HELP
@class: ExcelXLSX
@method: displayDataExcelXLSX()
@parameter:Vector vectorData
@notes: display the vector to console
@returns: nil
@END
*/
       
    // Looping every row data in vector
        for(int i=1; i<vectorData.size(); i++) {
       
        Vector vectorCellEachRowData = (Vector) vectorData.get(i);
           
        // looping every cell in each row
            for(int j=0; j<vectorCellEachRowData.size(); j++) {
           
            System.out.print(vectorCellEachRowData.get(j).toString()+"\t\t ");
               
            }
            System.out.println("");
        }
    }
 
   
    public static void main(String[] argas)
    {
   
    /* @HELP
@class: ExcelXLSX
@method: main()
@parameter:String Array
@notes:object creation to call constructor
@returns: nil
@END
*/
   
           new ExcelXLSX();
 
    }
   
}