Monday 24 October 2016

java code for repeating character

In this core java programming tutorial we will write a program to Find first non repeated character in string in java.



Write a program to find out first non-repeating character in string in java.
Example in java>
Given string =this is it
first non-repeating character in string= h

Must read: Reverse words in sentence in java.

Full Program/SourceCode/ Example to Find first non repeated character in string in java>
import java.util.LinkedHashMap;
import java.util.Map;
/** Copyright (c), AnkitMittal www.JavaMadeSoEasy.com */
public class FirstNonRepeatedCharacterInStringExample {
  
   public static void main(String[] args){
      
      String inputString="this is it";
       System.out.println("The first non repeated character in inputString("+inputString+") is :  " + firstNonRepeatedCharacter(inputString));
   }
  
   /**
    * Method returns first non-repeating character in inputString.
    * Returns null if there is no non-repeating character in inputString
    */
   public static Character firstNonRepeatedCharacter(String inputString){
       Map<Character,Integer>  map= new LinkedHashMap<Character ,Integer>(); //LinkedHashMap used so that we could maintain insertion order.
       char ar[]=inputString.toCharArray();
       char ch ;
      
       for (int i=0; i<ar.length; i++){
        ch=ar[i];
       
        if(map.containsKey(ch))   //if map already contains this character as key, get value corresponding to key and increment it.
            map.put(ch, map.get(ch)+1 );
        else        //put character in map with value as 1 (showing first occurrence of key in string)
            map.put(ch, 1) ;
       
       }   
       /*
     * Till this point of program, we have stored all unique characters in map as key & corresponding value representing count of character.
     */  
      
       for (int i=0; i<ar.length; i++ ){
        ch= ar[i];
        if( map.get(ch)  == 1 )   //we have found our first non-repeating character in string.
         return ch;
       }
       return null ;
   }
}
/*OUTPUT
The first non repeated character in inputString(this is it) is :  h
*/

Friday 16 September 2016

logic for reverse number in java

    int reverse = 0;
        int remainder = 0;
        do{
            remainder = number%10;
            reverse = reverse*10 + remainder;
            number = number/10;
         
        }while(number > 0);
     
        return reverse;
    }




  • Step 1: Take the remainder after dividing the number by 10. In this way, we can get last digit of the number.
  • Step 2: Store last digit in a temporary variable ‘revNum’. If there is some value in ‘revNum’, multiply that with 10 so that the earlier digits will be moved left, and then add the remainder (new last digit).
  • Step 3: Divide the original number with 10, and if the number does not become zero then repeat the above steps so that we can get each digit from last one by one.

ADb command for installation and unstallation apk

install

adb install "apk path"

uninstall

adb uninstall "packagename"  

Monday 29 August 2016

Constructor in Java

Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.
  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:
  1. Default constructor (no-arg constructor)
  2. Parameterized constructor


Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
  1. class Bike1{  
  2. Bike1(){System.out.println("Bike is created");}  
  3. public static void main(String args[]){  
  4. Bike1 b=new Bike1();  
  5. }  
  6. }  
Test it Now Output:
Bike is created 
 
 
 
 





Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
  1. class Student4{  
  2.     int id;  
  3.     String name;  
  4.       
  5.     Student4(int i,String n){  
  6.     id = i;  
  7.     name = n;  
  8.     }  
  9.     void display(){System.out.println(id+" "+name);}  
  10.    
  11.     public static void main(String args[]){  
  12.     Student4 s1 = new Student4(111,"Karan");  
  13.     Student4 s2 = new Student4(222,"Aryan");  
  14.     s1.display();  
  15.     s2.display();  
  16.    }  
  17. }  
Test it Now Output:
111 Karan
222 Aryan

Static blocks in Java


If a class has static members that require complex initialization, a static block is the tool to use.


Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initializations of a class. This code inside static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class). For example, check output of following Java program.
// filename: Main.java
class Test {
    static int i;
    int j;
     
    // start of static block
    static {
        i = 10;
        System.out.println("static block called ");
    }
    // end of static block
}
class Main {
    public static void main(String args[]) {
        // Although we don't have an object of Test, static block is
        // called because i is being accessed in following statement.
//static block code execute 1st , even before constructor and main method
        System.out.println(Test.i);
    }
}
Output:
static block called
10

Friday 26 August 2016

Static and final keyword in java

The static keyword can be used in 4 scenarios

  • static variables
  • static methods
  • static blocks of code.
  • static nested class
Lets look at static variables and static methods first.

static variable

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object
  • Syntax : Class.variable

static method

  • It is a method which belongs to the class and not to the object(instance)
  • A static method can access only static data. It can not access non-static data (instance variables) unless it has/creates an instance of the class.
  • A static method can call only other static methods and can not call a non-static method from it unless it has/creates an instance of the class.
  • A static method can be accessed directly by the class name and doesn’t need any object
  • Syntax : Class.methodName()
  • A static method cannot refer to this or super keywords in anyway

static class

Java also has "static nested classes",A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There's no such thing as a top-level static class in Java.

Side Note:

main method is static since it must be be accessible for an application to run before any instantiation takes place.

final keyword is used in several different contexts to define an entity which cannot later be changed.

  • A final class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are final, for example java.lang.System and java.lang.String. All methods in a final class are implicitly final.
  • A final method can't be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
  • A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a blank final variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.

Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.

When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.

"A static method can access only static data. It can not access non-static data (instance variables)" - UNLESS it has/creates an instance of the class. "A static method can call only other static methods and can not call a non-static method from it." - UNLESS it has/creates an instance of the class.

Thursday 25 August 2016

Assert in webdriver code

driver.get("http://google.co.in");
WebElement element = driver.findElement(By.xpath("//span[text()='Google Search']"));
String strng = element.getText();
System.out.println(strng);
Assert.assertEquals("Google Search", strng);


assertEquals check for string to match with "Google Search"

Tuesday 14 June 2016

simple way to read data from excel

If you added jars of poi properly then below code is simpler way you can use to read excel



private static XSSFCell Cell;

    private static XSSFRow Row;
      public static final String Path = System.getProperty("user.dir")+"\\src\\testData\\TestData.xlsx";
      public static final String SheetName = "Sheet1";

FileInputStream ExcelFile = new FileInputStream(Path);

            // Access the required test data sheet

            ExcelWBook = new XSSFWorkbook(ExcelFile);

            ExcelWSheet = ExcelWBook.getSheet(SheetName);
            Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
            System.out.println(Cell); //data from specific row

Sunday 12 June 2016

ANT setup for xslt report using testNg in selenium

for xslt reprt user should have ANT with machine 

so 1st ANT installation we will see,

Step 1- Navigate to below mention url
step 2- Extract zip file
Step 3- Once we extract the zip file then we need to set environment variable
Step 4- ANT_HOME should get added in path
Step 5- Now verify that Ant is installed properly- Open CMD 
ant -version
Note- if it is install properly then in output console we will get build.xml not found-build failed
Step 5- add below build.xml to your project, from below url




<project name="TestAutomation" basedir=".">
    <property name="LIB" value="${basedir}/lib" />
    <property name="BIN" value="${basedir}/bin" />
    <path id="master-classpath">
        <pathelement location="${BIN}" />
        <fileset dir="${LIB}" includes="*.jar"/>
    </path>
    
    <target name="Report">
        <delete dir="${basedir}/testng-xslt">
        </delete>
        <mkdir dir="${basedir}/testng-xslt">
        </mkdir>
        <xslt in="${basedir}/test-output/testng-results.xml" style="${basedir}/testng-results.xsl" out="${basedir}/testng-xslt/index.html">
            <param expression="${basedir}/testng-xslt/" name="testNgXslt.outputDir" />
            <param expression="true" name="testNgXslt.sortTestCaseLinks" />
            <param expression="FAIL,SKIP,PASS,CONF,BY_CLASS" name="testNgXslt.testDetailsFilter" />
            <param expression="true" name="testNgXslt.showRuntimeTotals" />
            <classpath refid="master-classpath">
            </classpath>
        </xslt>
    </target>

</project>











Step 6- now again check Ant version, successful message will come
Step 7-Add saxon 2 jars for your reports to your project
Step 8- as per your build.xml, run command from cmd after coming to your project directory, ant Report(from build.xml)
Step 9- this will create xslt reoprt folder under YOUR PROJECT
STEP 10-For reports check index.html
Step 7- after this run your code, and get xslt reports with pass fail diagrams, for this TestNg should have install with you in eclipse


Monday 6 June 2016

Maven setup for selenium



1)Set JAVA_HOME from environment variable(My computer -advanced setting)

2) add to path which added as JAVA_HOME till bin folder

3) Download ANT from Apache maven website, go for "bin" version for maven

4) unzip folder

5) set MAVEN_HOME and M2_HOME from advance setting

6) add to path which added as MAVEN_HOME till bin folder

7) go to cmd check mvn -version (verify maven install it proper or not)

8) If 7th step failed, then you are wrong with enviorment setting or java version

9) go to eclipse, add new software->http://download.eclipse.org/technology/m2e/releases as maven

10) go to project , right click and configure as maven

11) now go to project-pom.xml add dependancy as per your need, eg below dependancy for latest selenium jars

<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.0</version>
    </dependency> 

So this is how you can add maven to your selenium project

Sunday 5 June 2016

iphone and android crash log

Getting Crash Logs Directly From a Device Without Xcode
Your users can retrieve crash reports from their device and send them to you via email by following these instructions.
(It is not possible to get device console logs directly from a device)
1) Open Settings app
2) Go to Privacy, then Diagnostics & Usage
3) Select Diagnostics & Usage Data
4) Locate the log for the crashed app. The logs will be named in the format:
5) Select the desired log. Then, using the text selection UI select the entire text of the log. Once the text is selected, tap Copy
6) Paste the copied text to Mail and send to an email address as desired Getting Crash Logs and Console Output From a Device Using Xcode
Even though you won't be able to run the app in Xcode's debugger, Xcode can still give you all the information you need to debug the problem. Using Xcode 6
1) Plug in the device and open Xcode
2) Choose Window -> Devices from the menu bar
3) Under the DEVICES section in the left column, choose the device
4) To see the device console, click the up-triangle at the bottom left of the right hand panel
5) Click the down arrow on the bottom right to save the console as a file
6) To see crash logs, select the View Device Logs button under the Device Information section on the right hand panel
7) Find your app in the Process column and select the Crash log to see the contents.
8) To save a crash log, right click the entry on the left column and choose "Export Log"
9) Xcode 6 will also list low memory logs here. These will be shown with a Process name "Unknown" and Type "Unknown". You should examine the contents of these logs to determine whether any of these are caused by your app. For more information about low memory logs, see Understanding and Analyzing iOS Application Crash Reports. Using Xcode 5
1) Plug in the device and open Xcode
2) Open the Organizer window and select the Devices tab
3) Under the DEVICES section in the left column, expand the listing for the device
4) Select Device Logs to see crash logs or select Console to see Console output Back to Top Enabling App Store Diagnostic Reporting
Crash logs are automatically collected from customers who have opted in to sending diagnostic and usage information to Apple.
Beginning with Xcode 6.3, crash logs from App Store customers running at least iOS 8.3 and TestFlight beta testers can be found in the Xcode Organizer. To obtain these crash logs:
1) Open the Organizer window in Xcode 6.3 and above
2) Select "Crashes" at the top. The available crash logs can then be found within this window.
The App Distribution Guide contains further information about the Crash Reporting service.
Crash reports from customers running older iOS versions may be found in iTunes Connect.
If someone is reporting a crash, and you do not see a corresponding report in iTunes Connect, you should direct them to the following knowledge base articles for Mac or for Windows so they can opt-in to sending you crash reports.

for android -user can use monitor file from sdk folder else using adb logcat he can check logs in command prompt

appium swipe by text and appium jars

swipe by text- scorllToExact is function 1 can use for swipe- driver.scrollToExact("text")


Appium jars-http://mvnrepository.com/artifact/io.appium/java-client/2.1.0

only 1 jar needed for appium named -java-client

Thursday 2 June 2016

compile error come when user import project in eclipse

for this situation , user should add libraries from properties, same like adding jars

network connection using appium-interruptive testing

The Selenium Mobile JSON Wire Protocol Specification supports an API for getting and setting the network connection for a device. The API works through a bitmask, assigning an integer to each possible state:
Value (Alias) Data Wifi Airplane Mode
0 (None) 0 0 0
1 (Airplane Mode) 0 0 1
2 (Wifi only) 0 1 0
4 (Data only) 1 0 0
6 (All network on) 1 1 0

iOS

Unfortunately, at the moment Appium does not support the Selenium network connection API for iOS.

Android

Choose the setting you would like to use, and then send the correct bitmask from the table above.
// javascript
// set airplane mode
driver.setNetworkConnection(1)

// set wifi only
driver.setNetworkConnection(2)

// set data only
driver.setNetworkConnection(4)

// set wifi and data
driver.setNetworkConnection(6)

Sunday 22 May 2016

differencce between mobile and web app testing

What the difference between web testing and mobile
application testing
Question Submitted By :: Mobile Testing
I also faced this Question!! Answer Posted By
Answers were Sorted based on User's Feedback
Answer
# 1 Jotted some of the test coverage we need to focus on mobile testing which differed from web testing.

1. Interrupts : How app responds when it has interrupted by calls,SMS,alerts or Wi-fi change when the app is running.App should regain it's state after the interruption.

2.Mobile apps execute on the limited hardware resources and make sure that there is no hangups or performance issues.

3.Cross platform and cross devices :
App should be tested on different OS and Different devices for same issue(Android: MOTO G,Nuxes etc)

4.UI components loading,component locations while device is in different orientations.

5. Push notifications : Mobile apps works on push notifications whereas pc web applications doesn't have such concept.

6. Crash scenarios also need to be taken care when app is running.

Thursday 19 May 2016

string function

String userInput = "Hello, World! ssss1££$$%%##";
    //    String onlyAlphaNumeric = userInput.replaceAll("[^a-zA-
Z0-9]", "");
       
        //only num
    //String onlyAlphaNumeric = userInput.replaceAll("[^0-9]", "");
        //num and alpabets
                String onlyAlphaNumeric = userInput.replaceAll("[^a-zA-Z0-9]", "");           
        System.out.println(onlyAlphaNumeric);

Saturday 14 May 2016

desire capabilities appium

Capability Description Values
automationName Which automation engine to use Appium (default) or Selendroid
platformName Which mobile OS platform to use iOS, Android, or FirefoxOS
platformVersion Mobile OS version e.g., 7.1, 4.4
deviceName The kind of mobile device or emulator to use iPhone Simulator, iPad Simulator, iPhone Retina 4-inch, Android Emulator, Galaxy S4, etc…
app The absolute local path or remote http URL to an .ipa or .apk file, or a .zip containing one of these. Appium will attempt to install this app binary on the appropriate device first. Note that this capability is not required for Android if you specify appPackage and appActivity capabilities (see below). Incompatible with browserName. /abs/path/to/my.apk or http://myapp.com/app.ipa
browserName Name of mobile web browser to automate. Should be an empty string if automating an app instead. ‘Safari’ for iOS and ‘Chrome’, ‘Chromium’, or ‘Browser’ for Android
newCommandTimeout How long (in seconds) Appium will wait for a new command from the client before assuming the client quit and ending the session e.g. 60
autoLaunch Whether to have Appium install and launch the app automatically. Default true true, false
language (Sim/Emu-only) Language to set for the iOS Simulator e.g. fr
locale (Sim/Emu-only) Locale to set for the iOS Simulator e.g. fr_CA
udid Unique device identifier of the connected physical device e.g. 1ae203187fc012g
orientation (Sim/Emu-only) start in a certain orientation LANDSCAPE or PORTRAIT

appium code for rotation

  • //Launch the application
  • driver.rotate(landscape);
  • //Perform some desired actions and again switch to portrait mode
  • driver.rotate(portrait);
  • //Continue the test
  • //Launch the application
  • driver.rotate(landscape);
  • //Perform some desired actions and again switch to portrait mode
  • driver.rotate(portrait);
  • //Continue the test
  • - See more at: http://findnerd.com/list/view/How-to-perform-the-screen-rotation-in-Appium-/12414/#sthash.9vr05rZG.dpuf
  • //Launch the application
  • driver.rotate(landscape);
  • //Perform some desired actions and again switch to portrait mode
  • driver.rotate(portrait);
  • //Continue the test
  • - See more at: http://findnerd.com/list/view/How-to-perform-the-screen-rotation-in-Appium-/12414/#sthash.9vr05rZG.dpuf
  • //Launch the application
  • driver.rotate(landscape);
  • //Perform some desired actions and again switch to portrait mode
  • driver.rotate(portrait);
  • //Continue the test
  • - See more at: http://findnerd.com/list/view/How-to-perform-the-screen-rotation-in-Appium-/12414/#sthash.151w8far.dpuf
  • //Launch the application
  • driver.rotate(landscape);
  • //Perform some desired actions and again switch to portrait mode
  • driver.rotate(portrait);
  • //Continue the test
  • - See more at: http://findnerd.com/list/view/How-to-perform-the-screen-rotation-in-Appium-/12414/#sthash.151w8far.dpuf

    Tuesday 16 February 2016

    Table value selection from objetcs

    Below is HTML

    <tbody>
    </table>
    </td>
    </tr>
    <tr>
    <td>
    <div id="divListView" style="width: 100%; height: 300px; overflow: auto; display: block;">
    <table id="tblListView" class="adminlist" cellspacing="1" cellpadding="0" style="table-layout: fixed; width: 100%;">
      <tbody data-bind="template: { name: 'ActiveGradeTemplate', foreach: ActiveGrade }">
        <tr class="row0">
          <td data-bind="text:$index()+1" style="width: 5%;">1</td>
          <td data-bind="text: GradeName" style="width: 20%;">Vantage Point</td>
          <td align="right" data-bind="text: DisplayCreatedDate" style="width: 10%;">27 Mar 2013</td>
          <td align="right" data-bind="text: CreatedByUser" style="width: 10%;">Name</td>
          <td align="right" data-bind="text: DisplayModifiedDate" style="width: 10%;">27 Mar 2013</td>
          <td align="right" data-bind="text: ModifiedByUser" style="width: 10%;">Name</td>
          <td align="center" data-bind="text: Status" style="width: 5%;">Active</td>
          <td align="center" style="width: 10%;">
            <a id="lnkEdit_7" data-bind="click: $root.lnkEdit, attr:{'id':'lnkEdit_' + GradeID}" href="#">Edit</a>
            <span id="spanEdit_7" data-bind="attr:{'id':'spanEdit_' + GradeID}"></span>
          </td>
       </tr>
       <tr class="row0">
         <td data-bind="text:$index()+1" style="width: 5%;">2</td>
         <td data-bind="text: GradeName" style="width: 20%;">test grade</td>
         <td align="right" data-bind="text: DisplayCreatedDate" style="width: 10%;">Yesterday</td>
         <td align="right" data-bind="text: CreatedByUser" style="width: 10%;">Name</td>
         <td align="right" data-bind="text: DisplayModifiedDate" style="width: 10%;">Yesterday</td>
         <td align="right" data-bind="text: ModifiedByUser" style="width: 10%;">Name</td>
         <td align="center" data-bind="text: Status" style="width: 5%;">Active</td>
         <td align="center" style="width: 10%;">
           <a id="lnkEdit_11" data-bind="click: $root.lnkEdit, attr:{'id':'lnkEdit_' + GradeID}" href="#">Edit</a>
          <span id="spanEdit_11" data-bind="attr:{'id':'spanEdit_' + GradeID}"></span>
        </td>
      </tr>






    Below is code to retrieve data from tables

    // Grab the table 
    WebElement table = driver.findElement(By.id("divListView")); 
    
    // Now get all the TR elements from the table 
    List<WebElement> allRows = table.findElements(By.tagName("tr")); 
    
    // And iterate over them, getting the cells 
    for (WebElement row : allRows) { 
        List<WebElement> cells = row.findElements(By.tagName("td")); 
    
        // Print the contents of each cell
        for (WebElement cell : cells) { 
            System.out.println(cell.getText());
        }
    }