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 ,

Java : WebServer Database Connection and retreive data

WebServer Database Connection and retrieve data


Notes:

  1. doPost(..) method is generally used for Insertion /updation / deletion of data , 
  2. doGet(..) is used when the users tries to request for any Read Only data.

Pre -Req :

  1.  Using MySQL as DB Server
  2. Download "MySQL connector J.Jar" driver file and paste it into "Project/WebContent/WEB-INF/lib" folder path.
  3. Add the same file into project build directory.
  4. Download "Apache Commons DbUtils" jar file and paste it into "Project/WebContent/WEB-INF/lib" folder path.
  5. Repeat step 3.

DBHelper method: 
The below method return the results of the query in the form of Query list.


    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;
    }


 Serverlet :
 Calling Method 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    
        DBHelper DBHelp=new DBHelper();
         PrintWriter out=response.getWriter();
        out.print(DBHelp.SelectQuery(sURL,sUsername,sPassword,"Select * from mydb.login;"));
    }

Wednesday, June 22, 2016

Creating a simple web Service

Creating a simple web Service


https://www.youtube.com/watch?v=Av6zh817QEc
http://crunchify.com/servlet-tutorial-getting-starting-with-jsp-servlet-example/

Tips:
  1. External Jars go into - Project\WebContent\WEB-INF\lib
  2. Java files (Serverlets) goes into - Project\Java Resources\src\com.package\HERE
  3. JSP files - Project\WebContent\
  4. html files -  Project\WebContent\
  5. JSP files are html files but with different extension 
  6. The 1st html file shown is index.jsp , so this shoulkd not be deleted.



Configuring TomCat WebServer to Eclipse
1. download eclise
2. Download ApacheTomcat zip file Eg:8.73
3. Unzip AcpacheTomcat into a folder
4. Open Eclipse > Window >Preference>Server > Run time Environment>Add
5. In Add Window , Select the respective Apache Server Downloaded and Ck on finish

Validation :
1. In Eclipse > Window >perspective > Open perspective> web
2. In server Tab below> Right ck > new > Server
3. Select the correct server
4. Finish
5. A server gets added into the server tab , Double click on it to open the server settings
6. In Server Locations> Select use custom location and provide new path to save ur server.
7. Also user can change the port numbers in "Ports" Tab
8. save
9. perform right ck on the new server created in server tab> Select start
10. Open browser tab in eclipse > open "http://localhost:8080"
11. User should get 404 error meaninf server is configured correctly and running

Create project

1.    In Eclipse>File> New >Dynamic web project
2. Projectname= webapp-02, Make sure Dynamic Web Module version=2.5, Target runtime =8.0 (or what ever downloaded)
3. next ,again Next
4. Make sure "Generate web.xml" is checked.
5. Finish
6. Project>Rt clk>new >jsp file
7. file name "index.jsp"
8. Next and finish

9. Double ck "Deployment Descriptor" to open web.xml file
10. project>java resources > src>Create a new package "com.pack1
11. project>java resources > src>select package "com.pack1>right ck and create new serverlet>class name as "MyServerlet" (MyServerlet is the name specified  )
12 .open index.jsp and add below lines at the end (note: they are case sensitive):
    <h1>Welcome</h1>
    <form action="MyServerlet">
    <input type="submit" value="send">
    </form>

    </body>
    </html>

13. Open MyServerlet.java > add below code in doGet method :
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        out.print("hell noi");

    }

14. save all
15. project >Right Ck>Run as "Run on Server"

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, April 10, 2016

Java :OOPS Design Rules

OOPS Design Rules

Software :
  1. Perform what it supposed to.
  2. Flexible (by adding OOPS)
  3. Maintainable and Reusable

Object
  1. Object naming should be related to its operation
  2. Each object should not perform unrelated activities
  3. There should not be any unused properties or fields.
  4. Encapsulation helps divide application into logical parts.
  5. Duplicate code should be encapsulated separately
  6. Encapsulate what varies to protect class from unnecessary chages
Delegation: Delegating the current task to  specialized object which is designed to handle that.

Textual Analysis of Use Cases : Nouns = Classes and Verbs =methods.

Interface Vs Class
Coding to Interface is better as user has option to extend open.

Extra Classes make softare inflexible and difficult to change

Monday, April 4, 2016

Find out which process is locking a file or folder in Windows

Find out which process is locking a file or folder in Windows




Have a look at Process Explorer (procexp.exe).
From its introduction:
Ever wondered which program has a particular file or directory open? Now you can find out.
To find out what process is using a specific file follow these steps:
  1. Go to Find, Find Handle or DLL.. or simply press Ctrl+F.
    Enter image description here
  2. Enter the name of the file and press Search.
    Enter image description here
  3. Process Explorer will list all processes that have a handle to the file open. Click on an entry to focus the process in the main window.
    Enter image description here
  4. Optionally, you can then even close the handle manually through the lower pane (Ctrl+L):
    Enter image description here

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





Friday, March 18, 2016

Selenium : Page Object Model (By) VS Page Factory (@FindBy)


 Page Object Model (By) VS Page Factory (@FindBy)


1) Page Object Model

- Page Object Model - Initialize all object locators separately using "By"

 Code Here :
class starttest{
     @Test
      public void LoginTest() {    
            By usernameField = By.xpath("//*[text()=login_login_username]")
            By passwordField = By.name("//*[text()=login_login_password]")
            By loginButton = By.xpath("//*[text()=login_submit]");
          
            WebDriver driver=new FireFoxDriver();
            driver.get("http://some-login-page");
          
            driver.findElement(usernameField).sendKeys("my name");
            driver.findElement(passwordField).sendKeys("my password");
            driver.findElement(loginButton).click();
      }
  }

 2) Page Factory (@FindBy and PageFactory.initElements(driver, .class))

 1) @FindBy can accept tagName, partialLinkText, name, linkText, id, css, className, xpath as attributes.

2)  @FindBy(xpath="//*[text()=login_login_username]")
    private WebElement usernameField;
 

Is  Same as 

WebElement usernameField=By.xpath("//*[text()=login_login_username]")

3)
  @FindBy(xpath="//*[@id='']")    is same as     //@FindBy(how = How.xpath, using ="//*[@id='']")
 @FindBy(name="username")        is same as     //@FindBy(how = How.NAME, using = "username")
 @FindBy(className="radio")       is same as       //@FindBy(how = How.CLASSNAME, using = "radio")

 Code Here :


class starttest{

     @Test
      public void LoginTest() {   
        WebDriver driver=new FireFoxDriver();
        driver.get("http://some-login-page");
       
        LoginPage loginPage=PageFactory.initElements(driver, LoginPage.class); //Initialize Login Page     
        loginPage.login("student1","Testing1");
      }
  }


 public class LoginPage {

    @FindBy(xpath="//*[text()=login_login_username]")
    private WebElement usernameField;   \\
By usernameField = By.xpath("//*[text()=login_login_username]")   
   

 @FindBy(xpath="//*[text()=login_login_password]")
    private WebElement passwordField;   
   
    @FindBy(xpath="//*[text()=login_submit]")
    private WebElement loginButton;        

   
    public void login(String usernametext,String passwordtext)    {
        usernameField.sendKeys(usernametext);
        passwordField.sendKeys(passwordtext);
        loginButton.click();
    }   
}

Thursday, March 17, 2016

Selenium : How to Create Xpath


Selenium : How to Create Xpath

Target URL: www.mouthshut.com
Target Web element: Signup button, Login Button
Tools used:
·         FireBug : To formulate Xpath
·         Selenium Ide : To Test the formulated Xpath
Things to remember:-
1.       Target page should be open is FireFox
2.       Selenium ide and Firebug  should be open
3.       The formulated Xpath will go into “Target” field of Selenium IDE.
4.       All Xpath which go into IDE start with “xpath=//”
5.       The page usually start with <body> , therefore the foremost parent will always be “//Body” while writing Full Path
6.       Html Page may be like :
<body id=”aaaaa”>

   <div id=”bbbbb”>

   <div id=”cccc”>

          <a id=”dddd” class=”1111”>

          <ul id=”eeee”  target=”2222” href=”5555”>

  <div id=”ffff”>
               
Syntax in IDE:
Xpath=//branch/branch [ @property=’value’ or contains ( @property, “value”) ]
In the above example :
1.   Branch or Nodebody , div , a , ul ,img
Note : Each Node value will have  many properties and many values .Therefore always start with a node value or "*" along with its relate property and value (Ex ://a[@target='_new']  or //*[@target='_new']  )
2.   Propertyid , class , target
3.   Valueaaaa , bbbb , cccc , dddd , 1111 , 2222 , eeee , ffff ,5555

Syntax in Selenium (Eclipse Java) 
   ( Note -"Syntax in Selenium IDE" is only used to create Xpath and the below syntax is the usage of Xpath created using IDE )
Syntax :
WebElement oObject_Name=Driver_Object.findElement(By.xpath("Created Xpath Goes here ,starting from '//'"));
Example : 
oDriver=new FirefoxDriver();
oDriver.get("https://URL_Here");
WebElement oObject=oDriver.findElement(By.xpath("//branch/branch [ @property=’value’ or contains ( @property, “value”) ]"));

1.     Using Full Path
 xpath=//body/form/div[7]/div/div[2]/div/div[2]/ul/li/a
(The page usually start with <body> , therefore the foremost parent will always be “//Body” while writing Full Path )
Selenium Code :
 oDriver=new FirefoxDriver();
oDriver.get("https://www.mouthshut.com");
oTitle=oDriver.findElement(By.xpath("//body/form/div[7]/div/div[2]/div/div[2]/ul/li/a"));
2.     Using Last()
xpath=//body/form/div[7]/div/div[2]/div/div[last()]/ul/li/a
3.     Using Full Path+ @ attribute
·         xpath=//body/form/div[7]/div/div[2]/div/div[last()]/ul/li/a[@class='']
·         xpath=//body/form/div[7]/div/div[2]/div/div[last()]/ul/li/a[@style='background-color: transparent;']
(For Login Button)
xpath=//body/form/div[7]/div/div[2]/div/div[last()]/ul/li[2]/a[@target='_new']
4.      Using only @ attribute      (For Login Button)
xpath=//a[@target='_new']
(Which is equivalent to
xpath=//body/form/div[7]/div/div[2]/div/div[last()]/ul/li[2]/a[@target='_new']    )
5.     Using Descendants
xpath=//div[@class='new-menu']/descendant::div[@class='fr']
6.     Using keywords
xpath=//a[contains(@href, "javascript:__doPostBack(")]
xpath=//a[contains(@id, "ctl00_ctl00_ctl00_ContentPlaceHolderHeader_ContentPlaceHolderFooter_litSignUp")]



7.     And Operation
xpath=//a[contains(@id, "ctl00") and contains(@href,"javascript:_")]


8.     using position()
xpath=//div[@class='tdltaln']/div[position()=2]/ul/li


9.     Using starts-with keyword
xpath=//a[starts-with(@href, "https://graph.facebook.com")]
10. OR (|) condition
xpath=//a[@id='ctl00_ctl00_ctl00_ContentPlaceHolderHeader_ContentPlaceHolderFooter_litSignUpLink' or contains(@href,"javascript:__doPostBack")]

 xpath=//a[contains(@id,"ctl00_ctl00_ctl00_") or contains(@href,"javascript:__doPostBack") ]


 xpath=//a[contains(@href,"javascript:__doPostBack") or contains(@id,"ctl00_ctl00_ctl00_")]

11. Going 1 step back  
     Traversing from child to parent use    "/.."
12. Going back multiple steps or reverse tracing ( ancestor:: )
Ex :If user "ancestor::div" , then all the ancestor elements are highlighted with "div" node

 Back Trace to first occurrence of div element 
 //*[text()='Biological Sciences']/ancestor::div[1]
13. Going to specfic child element from parent node:( child:: )
Simialr to just "/ut[1]"
//*[text()='Biological Sciences']/ancestor::div[1]/child::ul[1]
 
14. Wild Card “*”
xpath=//*[@id="ctl00_ctl00_ctl00_ContentPlaceHolderHeader_ContentPlaceHolderFooter_litSignUpLink"]
15. Nth element
xpath=//ul[@class='login']/*[1]


16. No child
xpath=//img[count(*)=0]  

17. Last Second or Last But one 
xpath=//div[@class='dvaligncenter']/div[last()-1]//a

Examples for Xpath
xpath=xpathExpression: Locate an element using an XPath expression.

1. xpath=//img[@alt='The image alt text']
2. xpath=//table[@id='table1']//tr[4]/td[2]
3. xpath=//a[contains(@href,'#id1')]
4. xpath=//a[contains(@href,'#id1')]/@class
5. xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
6. xpath=//input[@name='name2' and @value='yes']
7. xpath=//*[text()="right"]
8. xpath=//*[@id='view']/*[not(@selected='selected')][1]
9. xpath=//*[text()='Biological Sciences']/ancestor::div[1]
10. xpath=.//*[local-name(.)='th' or local-name(.)='td']
Xpath summary
1.Path
    1. Full
    2. Full+attribute
    3. Attribute
    4. Wild Card(*)
    5. Recent ancestor "/.. "
    6. //a[6]
    7. div[3][contains(@id,'dvheader')] -goto 3rd element and fetch if it has dvheader similar to AND
    2.Functions
    1.  position
    1. [Last()]  //[Last[]-1]
    2. [Position()= 42]
    3. count
    1. text
    1. [starts-with(@,””)] -- Used For Dynamic Elements
    2. [contains(@,””)] -- Used For Dynamic Elements
    3. [text()=””] --text
    3.Logical
    1. And
    2. or
    3. not


  1. Navigation
  2.  Descendants::div[1]



  3. ancestor::div[1]
  4. child::div[1]

                   
    Ref:
                    http://software-testing-tutorials-automation.blogspot.in/2013/06/xpath-tutorials-identifying-xpath-for.html