Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, September 17, 2019

Bazel : Debugging / JVM debugging using JDB for Scala - Bazel


Debugging / JVM debugging using JDB


Follow steps to perform debugging in Bazel / Any JVMs :

Steps :
1.cd path
2. Open new Terminal Window
3. bazel run build_name --java_debug
4. Open another Terminal Window
5. jdb -attach localhost:5005 -sourcepath ~/dev/remote/src/main/java/

Note :Breakpoint can only be set in Dev Code not on scalatest .

Eg:
#stop in Dev code
stop in dev_package.class_name.method

#stop at Dev Code
stop at dev_package.class_name:130

#Clear BreakPoint
clear dev_package.class_name:line_number
clear dev_package.class_name.method

Commands :
run
cont
step over
next
locals
print resultdf.show()


Ref : http://pages.cs.wisc.edu/~horwitz/jdb/jdb.html

Friday, May 12, 2017

Java : CSV

how to work with CSV Files

use opencsv library file
( https://mvnrepository.com/artifact/com.opencsv/opencsv)

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;

public class csv_file {
String sPath=".\\src\\test.csv";

public static void main(String[] args) throws IOException{
csv_file c=new csv_file();
ArrayList<String[]> data=new ArrayList<String[]>(); // Arraylist which stores string array type
String[] a_data={"hi","one"};
String[] a_data2={"this","is","50"};
data.add(a_data);
data.add(a_data2);
c.opencsv_writeAll(data);
System.out.println(c.opencsv_read());
}

public ArrayList<String[]> opencsv_readAll() throws IOException{
CSVReader csv = new CSVReader (new FileReader(sPath));
ArrayList<String[]> data=(ArrayList<String[]>) csv.readAll();
csv.close();
return data;
}
public ArrayList<String[]> opencsv_read() throws IOException{
CSVReader csv= new CSVReader (new FileReader(sPath));
ArrayList<String[]> data=new ArrayList<String[]>();

for(Iterator<String[]> i=csv.iterator();i.hasNext();)
data.add(i.next());
csv.close();
return data;
}

public void opencsv_writeAll(ArrayList<String[]> data) throws IOException{
CSVWriter csv= new CSVWriter (new FileWriter(sPath,true));
csv.writeAll(data);
csv.close();
}
public void opencsv_write(String[] data) throws IOException{
CSVWriter csv= new CSVWriter (new FileWriter(sPath,true));
csv.writeNext(data);
csv.close();
}

}

Java : Array List of Array ( ArrayList )


Array List of Array ( ArrayList<String[]> )


Example:

// Variable can be ArrayList<String[]> as well

List<String[]> AList= new ArrayList<String[]>();
String[] addressesArr = new String[3]; addressesArr[0] = "zero"; addressesArr[1] = "one"; addressesArr[2] = "two";

String[] addressesArr2 = {"hi", "there"};
AList.add(addressesArr);
AList.add(addressesArr2);

Monday, May 8, 2017

Java : (Swing) JTable

Java : (Swing) JTable

JTable : Used when more than 1 column is required

Pre -Req :

  1. Make sure Window Builder addon is installed into eclipse
  2. Create a New Swing Designer >app Window > Save
  3. In Design Mode > add a JList Component 
Method 1:
DefaultTableModel model = new DefaultTableModel();
model.addColumn("A");
model.addColumn("B");

table = new JTable(model);
frame.getContentPane().add(table, BorderLayout.CENTER);
model.addRow(new Object[]{"1", "Deeapk"});


Method 2:

String[] Cols={"A" , "B"};
Object[][] data={
{"1","deepak"},
{"2","Alex"},
};

table = new JTable(data,Cols);
frame.getContentPane().add(table, BorderLayout.CENTER);


Code with Scroll bar :
frame = new JFrame();
DefaultTableModel model = new DefaultTableModel();
table = new JTable(model);
scrollPane = new JScrollPane(table);
scrollBar = new JScrollBar();

frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

scrollPane.add(scrollBar);

model.addColumn("A");
model.addColumn("B");

for(int i=1;i<50;i++){
model.addRow(new Object[]{i, "Deeapk"});
}


 

Java : ( Swing ) Jlist

(Swing) JList

JTable : Used when only 1 column is required

Pre -Req :
  1. Make sure Window Builder addon is installed into eclipse
  2. Create a New Swing Designer >app Window > Save
  3. In Design Mode > add a JList Component


DefaultListModel<String> listModel = new DefaultListModel<>();
            listModel.addElement("USA");
            listModel.addElement("India");
            listModel.addElement("Vietnam");


JList list = new JList(listModel);
 frame.getContentPane().add(list, "cell 0 1 7 4,grow");


Wednesday, April 26, 2017

Java : Accept Input Java

Java : Accept Input Java



 String test1= JOptionPane.showInputDialog("Please input mark for test 1: ");

Tuesday, July 19, 2016

Java : Create html table using JSP

Create html table using JSP

Libraries required :
  1.  commons-dbutils
  2. my-sqlconnector
Added to project path and WebContent/lib folder

Below method retreieves data from the DB into List of Maps
public List SelectQuery(String sURL,String sUsn,String sPassword,String sQuery){
        ResultSet rs=null;
        MapListHandler rstoList=new MapListHandler();
        Map<String,Object> MapQuery=new HashMap<String,Object>();
        List resList=null;
      
        try {
            Class.forName("com.mysql.jdbc.Driver");  
            Connection connection = DriverManager.getConnection(sURL,sUsn, sPassword);          
            Statement st=(Statement) connection.createStatement();
             rs=st.executeQuery(sQuery);
             resList= rstoList.handle(rs);
             rs.close();
             st.close();
             connection.close();          
              
      }catch(Exception e){
          System.out.println("Failed to make connection!");
          e.printStackTrace();
      }      
        return resList;
    }


 Output : [{iditem=1, item_name=ketchup, price_kg=100}, {iditem=2, item_name=Beverages, price_kg=140}]

Below method converts the input List of Maps to html
    public <E> String List_MaptoHtml_TableRows(ArrayList l){   
        StringBuffer sb=new StringBuffer() ;
        //String s=null;
        String[] stemp;
       
        int flag=0;
       
        for(Iterator<E> i=l.iterator();i.hasNext();){
            Map<String,Object> m=(Map<String, Object>) i.next();
            if(flag==0)
            {
                stemp=m.keySet().toString().split(" ");
                sb.append("\n<tr>");
                for(int i2=0;i2<stemp.length;i2++)
                    sb.append("\n    <td><strong>"+stemp[i2].replaceAll("[^a-zA-Z0-9]", "")+"</strong></td>");
                sb.append("\n</tr>\n");
                flag=1;
            }
           
            stemp=m.values().toString().split(" ");
            sb.append("\n<tr>");
            for(int i2=0;i2<stemp.length;i2++)
                sb.append("\n    <td>"+stemp[i2].replaceAll("[^a-zA-Z0-9]", "")+"</td>");
            sb.append("\n</tr>\n");

        }               
            return sb.toString();
        }
       


Create a new Servelet and add below code to Doget method
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DBHelper DBHelp=new DBHelper();
        PrintWriter out=response.getWriter();
        ArrayList<Object> oList;


        if(LRes.isEmpty()==false){
            oList=(ArrayList<Object>) DBHelp.SelectQuery(sURL,sUsername,sPassword,"SELECT * FROM mydb.item;"); 
             Helper helper=new Helper();
             out.println("<html>");
                out.println("<head><title>Page name</title></head>");
                out.println("<body>");
                out.println(oList);
                out.println("<center><h1> List of Items </h1>");
                out.println("<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" style=\"width:500px\">");
                out.println("<tbody>");
                out.println(helper.List_MaptoHtml_TableRows(oList));
                out.println("</tbody></table><p>&nbsp;</p>");
             out.println("</center>");
                out.println("</body>");
                out.println("</html>");
        }
        HttpSession session=request.getSession(); 
            session.setAttribute("name",username); 
}

Java : Print Query data from table directly into html file in Servelet itself

Print Query data from table directly into html file in Servelet itself

Libraries required :
  1.  commons-dbutils
  2. my-sqlconnector
Added to project path and WebContent/lib folder

Below method retreieves data from the DB into List of Maps
public List SelectQuery(String sURL,String sUsn,String sPassword,String sQuery){
        ResultSet rs=null;
        MapListHandler rstoList=new MapListHandler();
        Map<String,Object> MapQuery=new HashMap<String,Object>();
        List resList=null;
      
        try {
            Class.forName("com.mysql.jdbc.Driver");  
            Connection connection = DriverManager.getConnection(sURL,sUsn, sPassword);          
            Statement st=(Statement) connection.createStatement();
             rs=st.executeQuery(sQuery);
             resList= rstoList.handle(rs);
             rs.close();
             st.close();
             connection.close();          
              
      }catch(Exception e){
          System.out.println("Failed to make connection!");
          e.printStackTrace();
      }      
        return resList;
    }


 Output : [{iditem=1, item_name=ketchup, price_kg=100}, {iditem=2, item_name=Beverages, price_kg=140}]

Below method converts the input List of Maps to html
    public <E> String List_MaptoHtml_TableRows(ArrayList l){   
        StringBuffer sb=new StringBuffer() ;
        //String s=null;
        String[] stemp;
       
        int flag=0;
       
        for(Iterator<E> i=l.iterator();i.hasNext();){
            Map<String,Object> m=(Map<String, Object>) i.next();
            if(flag==0)
            {
                stemp=m.keySet().toString().split(" ");
                sb.append("\n<tr>");
                for(int i2=0;i2<stemp.length;i2++)
                    sb.append("\n    <td><strong>"+stemp[i2].replaceAll("[^a-zA-Z0-9]", "")+"</strong></td>");
                sb.append("\n</tr>\n");
                flag=1;
            }
           
            stemp=m.values().toString().split(" ");
            sb.append("\n<tr>");
            for(int i2=0;i2<stemp.length;i2++)
                sb.append("\n    <td>"+stemp[i2].replaceAll("[^a-zA-Z0-9]", "")+"</td>");
            sb.append("\n</tr>\n");

        }               
            return sb.toString();
        }
       


Create a new Servelet and add below code to Doget method
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DBHelper DBHelp=new DBHelper();
        PrintWriter out=response.getWriter();
        ArrayList<Object> oList;


        if(LRes.isEmpty()==false){
            oList=(ArrayList<Object>) DBHelp.SelectQuery(sURL,sUsername,sPassword,"SELECT * FROM mydb.item;"); 
             Helper helper=new Helper();
             out.println("<html>");
                out.println("<head><title>Page name</title></head>");
                out.println("<body>");
                out.println(oList);
                out.println("<center><h1> List of Items </h1>");
                out.println("<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" style=\"width:500px\">");
                out.println("<tbody>");
                out.println(helper.List_MaptoHtml_TableRows(oList));
                out.println("</tbody></table><p>&nbsp;</p>");
             out.println("</center>");
                out.println("</body>");
                out.println("</html>");
        }
        HttpSession session=request.getSession(); 
            session.setAttribute("name",username); 
}

Java : Sending and Retreiving data from JSP to Serverlet and visversa

Sending and Retreiving data from JSP to Serverlet and visversa

Note :
  1. UI to Servlet -  html or jsp
  2. Servelet to UI - jsp only


UI to Servlet 

Login.html

<html>
<body>
<form action="MyServerlet1" method="get">
    <p>Username <input name="Usn" type="text" />&nbsp;</p>
    <p>Password <input name="Password" type="text" /></p>
    <p><input name="Submit" type="submit" value="Submit" /></p>
</form>
</body>
</html>


MyServerlet1.java
  1. Project>Javarespurces>src>package>rt ck >new servelet>
  2. Name "MyServerlet1" >Next,next>check doGet and doPost>Finish
  3.  Add below code to retreieve the data from "Usn" and "Password" fields.
@WebServlet("/Login")
public class MyServerlet1 extends HttpServlet {
   
    public MyServerlet1() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        String username = request.getParameter("Usn");
        String password = request.getParameter("Password");
        out.println(username+"  "+password);
    }
}

Servlet to UI (jsp file only)

itemlist.jsp (Create new jsp file in Project>WebContent>itemslist.jsp)
<html>
  <body>
    Servlet communicated message to JSP: ${jItem_list}
  </body>
</html>

Serverlet.java
request.setAttribute("jItem_list", json);
            rd = request.getRequestDispatcher("/itemslist.jsp");
            rd.forward(request, response);

 

Tuesday, July 12, 2016

Java : Object to Xml and vis versa

Object to Xml and vis versa


JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file. In this tutorial, we show you how to use JAXB to do following stuffs :
  1. Marshalling – Convert a Java object into a XML file.
  2. Unmarshalling – Convert XML content into a Java Object.

Required library : https://jaxb.java.net/latest/download.html

Marshalling

@XmlRootElement
public class Customer {
 String name;
 int age;
 int id;
 public String getName() {
  return name;
 }
 @XmlElement
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 @XmlElement
 public void setAge(int age) {
  this.age = age;
 }
}


public class JAXBExample {
 public static void main(String[] args) {

   Customer customer = new Customer();
   customer.setName("John");
   customer.setAge(18);

   try {

  File file = new File("C:\\file.xml");
  JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
  Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

  // output pretty printed
  jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

  jaxbMarshaller.marshal(customer, file);
  jaxbMarshaller.marshal(customer, System.out);

       } catch (JAXBException e) {
  e.printStackTrace();
       }

 }
}
 Output:
<customer age="18">
    <name>John</name>
</customer> 

Unmarshalling

public class JAXBExample {
 public static void main(String[] args) {

  try {

  File file = new File("C:\\file.xml");
  JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
  System.out.println(customer);

   } catch (JAXBException e) {
  e.printStackTrace();
   }

 }
} 
Customer [name=John, age=18] 

Monday, June 27, 2016

Java : doGet vs doPost


doGet vs doPost



In doget() method
  1. There is a security problems are arrival because when the user or client submit the form the associated user name or password has been display on the address bar.
  2.  client can send limited amount of data.
  3.  when the users tries to request for any Read Only data.
doPost() method
  1. when the user submit the form the associated user name or password are not display on the addressbar.
  2. client can send more then data.
  3.   used for Insertion /updation / deletion of data ,

Monday, May 16, 2016

Java : Inner Class , Nested Class , Static Class and Interfaces

Inner Class , Nested Class , Static Class and Interfaces



interface A {//All implementation in Interface = Static
    static class X{}            //To Avoid : if(X instance of A) ,can be accessed as A.X
    static abstract class Y{}    //Not valid - Cannot instantiate abstract class (static)
    static interface Z{}        //Not valid - Cannot instantiate Interface (static)
}

abstract class B {
    class X{}            //X=private by default
    abstract class Y{}    //
    interface Z{}        //
}

class C {
    void m(){class c{}}//Local inner class(visible only inside this method    )
    static class W{}    //Accessed as C.W
    class X{}            //Nested Class
    abstract class Y{}    // Implementing class needs
    interface Z{}
}


Nested Class:
1. Private by Default
2. Can access all the private members of super class
3.     C face=new C();
    C.X ear1=face.new X(); //logical grouping, readable and maintainable code
    C.X ear2=face.new X();
4. Same operation can also be done using external classes

Friday, May 6, 2016

Java : Important API

Java : Important API


  1. Fileutils : Folder and File Related Operations (also does read ,write,append to text file)
  2. StringUtils: For String Related Operations (contains,indexof,mid,leftpad,join,split,rightpad,leftpad,replace,trim etc.,)
  3. Guava: Additional util operations
  4. WorkBookFactory : Excel Operations (Apache POI)


Alternatives
  1. File>FileReader>BufferedReader : To read text
  2. File>FileWriter >BufferedWriter: To write text

Sunday, March 20, 2016

Java : Program to draw an eqilateral triangle using input string

Program to draw an eqilateral triangle using input string

Logic :

      D        1 -character
    Dee       3 - charracters
  Deepa      5
Deepaks     7

1. Increament by 2
2.
    StringUtils.leftPad("bat", 5," ")  = "  bat"
    StringUtils.leftPad("bat", 4," ")  = " bat"
    StringUtils.leftPad("bat", 3," ")  = "bat"


Program :

import org.apache.commons.lang3.StringUtils;

    public static void main(String [] args){
        String str="Deepak";
        String sTemp=null;
        StringBuffer sBuff=new StringBuffer();
       
        if(str.length/2() !=0)
            str=str+"s";       

        for(int i=1;i<=str.length();i=i+2){
             sTemp=StringUtils.mid(str, 0, i);
             sTemp=StringUtils.leftPad(sTemp, str.length()," "); // StringUtils.leftPad("bat", 5)  = "  bat"
             sBuff.append(sTemp+"\n");
            }

        JOptionPane.showMessageDialog(null,sBuff.toString());

    }


Output :

      D
    Dee
  Deepa
Deepaks





Wednesday, March 16, 2016

Java : Introduction to Guava Core Libaray

Java : Introduction to Guava Core Library

download Jar :http://mvnrepository.com/artifact/com.google.guava/guava

http://docs.guava-libraries.googlecode.com/git/javadoc/overview-summary.html
(Visit the above JavaDoc for more information  and usage . click on Frames to view complete classes)




 What Is Guava ?


-    Open Source libraries provided by Google
-    provides utility methods

Most Frequently Used Classes

1. Optional - facilitate the code to handle values as available or not available instead of checking null values.
2. Preconditions - provide static methods to check that a method or a constructor is invoked with proper parameters.
3. Ordering - multiple utility methods, multi-type sorting capability, etc
4. Objects - provides helper functions applicable to all objects such as equals, hashCode, etc.
5. Range - represents an interval or a sequence. It is used to get a set of numbers/ strings lying in a particular range.
6. Throwables - Static class provides utility methods related to Throwable interface.
7. Collections Utilities - Provides utility api for handling ArrayLists,Lists,Maps,Sets etc .,
8. String Utilities - Provides utility api for Strings.(Splitter ,Joiner, CaseFormats etc., are one of them)
9. Math Utilities - For performing Mathoperations

Tuesday, March 15, 2016

Java : Exceptions (try catch)


Java : Exceptions (try catch)



1. Creating and Catching an Exception
    public void crossFingers()
    (
        try{
            Object.takeRisk();
        ) catch (BadException ex) // "ex" can be any variable
            System. out.println ("Aaarqh! ") ;
            ex .printStackTrace () ;
        }
    }

    public void takeRisk () throws BadException {
        if (abandonAllHope) {
            throw new BadException();
        }
    }

---------------------
2. A finally block - runs regardless of an exception or even if the catch has a return statement
   
    try (
        turnOvenOn();
        x.bake () ;
    }catch (BakingException ex)
        ex.printStackTrace();
    }finally { //
runs regardless of an exception or even if the catch has a return statement        
turnOvenOff();
    }

   
3. Multiple try catch

    try {
        throw new IOException();
        }catch (FileNotFoundException f){
           
        }catch (IOException  e){
            System.out.println(e);     //output :     java.lang.NullPointerException
            e.printStackTrace;        //output :    java.io.IOException at package.Test.main(Test.java:74)
                                   
        }catch (Exception e){        //Catches all sorts of Exception should be placed LAST
                                    //If passed 1st any catch block belowing will be skipped
        }finally{
        }

       
4. Multiple catch Using OR (|)
        try {
        do something ;
        }catch (FileNotFoundException | IOException e){ //Catch executes when either of the 2 exception occur
       
        }

       
5. What you can do inside catch block ?
    -    e.printStackTrace()
    -    e.getmessage();
    -     log.error("Ops!", e); //Using logging framework like logback or log4j
    -     "USER CAN DO ANY OPERATIONS"
   
6. What is Throwable t ?
    -    In normal cases we should always catch sub-classes of Exception.
   
    Example :
        try {
        do something ;
        catch(throwable t){ //"throwable" is super class of exception
           
        }

   
   

Saturday, March 12, 2016

Java : Looping (Iterator)

Looping (Iterator)

 

Iterator :

Collections = Lists(arraylist) , Set(HashSet -remove duplicates) , Map(similar to dictionary)
  1. Java iterator is an interface.
  2. belongs to collection framework
  3. allow us to traverse the the data element without bothering implementation. Ex : User may use array ,list etc.,
  4. Basically List and set collection provides the iterator ( ArrayList, LinkedList, and TreeSet etc)
  5. Map implementation such as HashMap doesn’t provide Iterator directly


Using Iterator

  1. Create an  iterator
  2. Have the loop iterate as long as hasNext( ) returns true.
  3. Within the loop, obtain each element by calling next( ).


Array List
ArrayList<Student> s= new ArrayList<Student>();   
s.add(new Student(Adam,98));    
s.add(new Student(Bob,65));           

for(int i=0;i<=s.size();i++)                //Noraml Loop
    System.out.println(s.get(i).name); 

for(Student s_loop:s)                          //Enhanced Loop                           
    System.out.println(s_loop.name);  

for (Iterator i=s.iterator();s.hasnext()){    //Iterator
    Student s_loop=(Student)i.next();
    System.out.println(s_loop.name);
    }

   
Array
Student[] s =new Student[2];
Student Adam=new Student("Adam",98);
Student Bob=new Student("Bob",67);

s[0]=Adam;
s[1]=Bob;

for(int i=0;i<=s.length-1;i++)
    Syste
m.out.println(s[i].name);


   
You can use Iterator Patten when you want similar implementation in both List and Array
1. ArrayList already comes ready with iterator so need to worry about that
2. We need to implement for Array or Class which uses array without changing the code.
(326pg -Design Patterns,Head First)
Or
1. Use Guava
Iterator<String> it = Iterators.forArray(array);
 

Examples :

1.  HashMap

//Use Java 1.8
HashMap m=new HashMap();
m.put(1, "01");
m.put(2, "02");

m.forEach( (k,v) -> System.out.println("Key: " + k + ": Value: " + v));


or 
Iterator entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
  Entry thisEntry = (Entry) entries.next();
  Object key = thisEntry.getKey();
  Object value = thisEntry.getValue();
  // ...
}


 2. Array List
ArrayList a=new ArrayList();   
a.add(1);
a.add("hi");

Iterator it=a.iterator();
while(it.hasNext()){
System.out.println(it.next());
}


3.HashSet
HashSet s=new HashSet();
s.add("hi");
s.add("hi");
s.add("abc");
s.add("bye");

Iterator i=s.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}


Example 2


public class CrunchifyIterateThroughList {
public static void main(String[] argv) {

List<String> crunchifyList = new ArrayList<String>();

crunchifyList.add("eBay");
crunchifyList.add("Paypal");
crunchifyList.add("Google");
crunchifyList.add("Yahoo");
// iterate via "for loop"
for (int i = 0; i < crunchifyList.size(); i++) {
System.out.println(crunchifyList.get(i));
}
// iterate via "New way to loop"
for (String temp : crunchifyList) {
System.out.println(temp);
}
// iterate via "iterator loop"
Iterator<String> crunchifyIterator = crunchifyList.iterator();
while (crunchifyIterator.hasNext()) {
System.out.println(crunchifyIterator.next());
}
// iterate via "while loop"
int i = 0;
while (i < crunchifyList.size()) {
System.out.println(crunchifyList.get(i));
i++;
}
// collection stream() util: Returns a sequential Stream with this collection as its source
crunchifyList.forEach((temp) -> {
System.out.println(temp);
});
}
}

Wednesday, March 9, 2016

TestNg : Loop testcases logic (Reflection and ITestContext)

Loop testcases logic (Reflection and ITestContext)


Code Below :

public class BeforeMethodParametersExample {
    private Method method;
    private ITestContext context;
    private static final Object[][] DATA1 = { new Object[] { "first" },new Object[] { "second" }, };
    private int i;
   
    @DataProvider
    public Object[][] data1() {
        i=i+1;
        System.out.println("data provider "+1); //executes 1st
        return DATA1;//first , second
    }   
   
    //Method java.lang.reflect.Method;   ITestContext
//executes 2nd   
@BeforeMethod
    public void before(Method m, ITestContext ctx) {
        method = m;
        context = ctx;
        i=i+1;
        System.out.println("Name of test is " + method.getName()+" "+i); // execute 1st
    }
   
    @BeforeMethod  // -3rd
    public void beforeWithData(Object[] data) {
        for (Object o : data) {
            i=i+1;
            System.out.println("Data " + o+" "+i);// execute 2nd
        }
    }

    @Test(dataProvider="data1")  //4th
    public void someTest(String data) {
        i=i+1;
        System.out.println("Name of test is " + method.getName()+" "+i);
        System.out.println("Suite name is " + context.getSuite().getName()+" "+i);
    }
   
}