Wednesday, March 19, 2014

Selenium : (Parallel) To retreive all the Thread Ids of active Threads

(Parallel) To retreive all the Thread Ids of active Threads



Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
 
 
 Reference 
http://stackoverflow.com/questions/1323408/get-a-list-of-all-threads-currently-running-in-java 

Selenium : Handling Images , pictures and flash elements

Handling Images , pictures and flash elements



This problem can be tackled by using Sikuli .

1. Download and install Sikuli IDE or Sikuli X  (Sikuli-X)  
   You can go to this website : http://www.sikuli.org/downloadrc3.html to find setup file compatible with your OS.
  • Download the following zip file: Sikuli X r930. This contains important bug fixes
  • Unzip the above file
  • Copy all the contents of the unzipped files and replace it in the installation folder.
  • )
2. Once installed you should have Sikuli IDE available in your  Start Options for Windows .

3. Configuring Eclipse
  1. You must use a 32bit JRE version (I use jre-7u4-windows-i586.exe)
  2. Download Sikuli IDE for Windows (I use "Sikuli X r930", portable version)
  3. copy all the installation files into a new folder inside your project (ex:"sikuli-ide"), ref screenshot http://i.stack.imgur.com/LSiQV.png)
  4. Add sikuli-script.jar to the Referenced Libraries (Project > Properties > Java Build Path > Libraries, ref screenshot http://i.stack.imgur.com/N2SJ8.png)
  5. Set PATH and SIKULI_HOME environment vars (Run > Run Configurations > Environment, ref screenshot http://i.stack.imgur.com/HboXk.png)
  6. You're ready to go.

Running sample Code :

The below code will open YouTube page with a video and does the following operations:

1. Click on Pause button on the player.
2.Click on Large Player Button.
3.Click on Small Player Button.

Note :
1. Take precaution there should be no advertisement.
2. Make separate files for a)pause.png b) size_increase.png  c)size_decerease.png

 (You can take a screenshot of the player and crop these objects and place it your drive .)


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
import org.sikuli.script.SikuliException;


public class Sikuali_test {

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

        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.get("http://www.youtube.com/watch?v=b-NeudACWzc");
       
        Screen screen = new Screen();
        Pattern image = new Pattern("D:\\pause.png");
        screen.wait(image, 10);
        screen.click(image);

        Pattern image2 = new Pattern("D:\\size_increase.png");
        screen.wait(image2, 10);
        screen.click(image2);
               
        Pattern image3 = new Pattern("D:\\size_decerease.png");
        screen.wait(image3, 10);
        screen.click(image3);

    }

}












Sunday, March 16, 2014

Jmeter :To extract the response of an HTTP Sampler into a variable for later use

To extract the response of an HTTP Sampler into a variable for later use


To add regular expression extractor element to a test plan in JMeter:

1.   Right click the sampler element (request to the server from which the value needs to be extracted)

2. Select Add option à Post Processors à Regular expression extractor

-----------------------------------------------------------------------------------------------

Extracting Single string from the response

Consider an example, where a user Date displayed in a webpage Ex: Date:xxxxxxx

In order to extract the username, below R.E can be used:    

Reference Name:                   Date

Regular Expression:               Date\:(.+?)             

Template:                                 $1$

Match No. (0 for Random):    1

Default Value:                          match not found

Note:The special characters above mean:

(  ) encloses the portion of the match string to be returned

. ->  match for any character.    +  è one or more times.

?  stop when first match is found 

Without the ?, the .+ would continue until it finds the last possible match.

----------------------------------------------------------------------------------------------------

Extracting Multiple Strings from the response

Consider a scenario where the user wants to extract Date and Time.
(Ex:Date:xxxxxx Time:xxxxxxx) To extract both the ids, the below R.E can be used

                       Reference Name:                    Date_time

                       Regular Expression:    Date\: (.+?) Time\:(.+?)

                      Template:                                $1$$2$

                      Match No. (0 for Random):    1

                      Default Value:            match not found

Since we need to extract two values from the response, two groups are created. So the template has $1$$2$. The JMeter Regex Extractor saves the values of the groups in additional variables.

The following variables would be set as:

    Date_time-> xxxxxzzzz

    Date_time _g0 ->  Date:xxxx time:zzzz

    Date_time _g1 -> xxxx

    Date_time _g2 ->  zzzz

These variables can be later referred in the JMeter test plan, as ${Date_time _g1}, ${Date_time _g2}.

-------------------------------------------------------------------------------------------------------

Extracting only numbers from the String

Consider a case where we need to only extract the numbers, for example price=100$

To extract 100, the below R.E can be used

                      Reference Name:                    price

                      Regular Expression:    price= “(.+?)$”

                      Template:                                $1$

                      Match No. (0 for Random):    1

                      Default Value:            match not found

Tuesday, March 11, 2014

Selenium : Html Template Report for Cross Browser

Html Template Report for Cross Browser




<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"><title>Report</title>

</head><body style="height: 177px;">
<br>
<br>
<br>
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;<br>
<br>
<div style="text-align: center;">&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <img style="height: 204px; width: 390px;" alt="Marlabs LOGO" src="file:///D:/pics/Logo%20Marlabs_0.JPG"><br>
</div>
<br>
<table style="text-align: left; width: 938px; height: 263px;" border="1" cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td style="text-align: center; font-weight: bold; height: 74px;"><h3>Sl No </h3></td>
<td style="text-align: center; font-weight: bold; height: 74px;"><h3>Test Cases</h3></td>
<td style="text-align: center; font-weight: bold; height: 74px;"><h3>FireFox</h3></td>
<td style="text-align: center; font-weight: bold; height: 74px;"><h3>Chrome</h3></td>
<td style="text-align: center; font-weight: bold; height: 74px;"><h3>Internet Explorer</h3></td>
</tr>


<tr>
<td style="text-align: center; height: 35px;">1</td>
<td style="height: 35px; text-align: left;">Sample </td>
<td style="color: rgb(0, 1, 0); text-align: center; height: 35px;"><span style="color: rgb(51, 204, 0);">Pass </span></td>
<td style="color: rgb(0, 1, 0); text-align: center; height: 35px;"><span style="color: rgb(51, 204, 0);">Warning </span></td>
<td style="text-align: center; height: 35px;"><a href="file:///C:/Users/deepakj/Desktop/Report2.html"><span style="color: red;">Fail</span></a></td>
</tr>

<tr>
<td style="text-align: center; height: 35px;"></td>
<td style="height: 35px;"></td>
<td style="height: 35px;"></td>
<td style="height: 35px;"></td>
<td style="height: 35px;"></td>
</tr>

</tbody>
</table>
<br>
<br>
<br>
<br>
</body></html>

Selenium : GUI for the Framework

GUI for the Framework 


1. Make sure you have added "WindowBuider Pro "
2. Click on "Source "

// Use JDialog instead of JFrame for thread to pause until an event
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.AbstractButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SpringLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JRadioButton;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.Box;
import javax.swing.JCheckBox;

import java.awt.Choice;

import javax.swing.JSpinner;
import javax.swing.JSeparator;

import java.awt.Panel;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.ButtonGroup;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;


public class GUI2 extends JFrame {
    private JTextField textField;
    private JTextField password_field;
    private JTextField email_field;
    private JTextField data_field;
    private JTextField textField_4;
    private JTextField textField_5;
    private final ButtonGroup buttonGroup = new ButtonGroup();
   
    public  String sUsername ,sPassword,sEmail,sTest_path,sRange_type="none",sPath;
    public int iFrom,iTo;
    public JFileChooser Filechoose;//=new JFileChooser();
    public boolean bResume;
    public File file;
    PrintWriter writer;
    /**
     * @wbp.nonvisual location=72,219
     */
    private final ButtonGroup buttonGroup_1 = new ButtonGroup();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
//        EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                try {
                    GUI2 frame = new GUI2();
                    frame.setVisible(true);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
    }

    /**
     * Create the frame.
     */
    public GUI2() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 517, 475);
        SpringLayout springLayout = new SpringLayout();
        getContentPane().setLayout(springLayout);
       
        JLabel lblUsername = new JLabel("Username");
        springLayout.putConstraint(SpringLayout.NORTH, lblUsername, 27, SpringLayout.NORTH, getContentPane());
        springLayout.putConstraint(SpringLayout.WEST, lblUsername, 10, SpringLayout.WEST, getContentPane());
        getContentPane().add(lblUsername);
       
        textField = new JTextField();
        textField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println(textField.getText());
            }
        });
        springLayout.putConstraint(SpringLayout.NORTH, textField, -3, SpringLayout.NORTH, lblUsername);
        springLayout.putConstraint(SpringLayout.WEST, textField, 6, SpringLayout.EAST, lblUsername);
        getContentPane().add(textField);
        textField.setColumns(10);
       
        JLabel lblPassword = new JLabel("Password");
        springLayout.putConstraint(SpringLayout.WEST, lblPassword, 0, SpringLayout.WEST, lblUsername);
        getContentPane().add(lblPassword);
       
        password_field = new JTextField();
        password_field.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println(password_field.getText());
            }
        });
        springLayout.putConstraint(SpringLayout.SOUTH, lblPassword, 0, SpringLayout.SOUTH, password_field);
        springLayout.putConstraint(SpringLayout.NORTH, password_field, 19, SpringLayout.SOUTH, textField);
        springLayout.putConstraint(SpringLayout.EAST, password_field, 0, SpringLayout.EAST, textField);
        getContentPane().add(password_field);
        password_field.setColumns(10);
       
        email_field = new JTextField();
        springLayout.putConstraint(SpringLayout.NORTH, email_field, 19, SpringLayout.SOUTH, password_field);
        email_field.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println(email_field.getText());
            }
        });
        getContentPane().add(email_field);
        email_field.setColumns(10);
       
        JLabel lblEmail = new JLabel("Email");
        springLayout.putConstraint(SpringLayout.WEST, email_field, 6, SpringLayout.EAST, lblEmail);
        springLayout.putConstraint(SpringLayout.SOUTH, lblEmail, 0, SpringLayout.SOUTH, email_field);
        springLayout.putConstraint(SpringLayout.EAST, lblEmail, 0, SpringLayout.EAST, lblUsername);
        getContentPane().add(lblEmail);
       
        data_field = new JTextField();
        springLayout.putConstraint(SpringLayout.WEST, data_field, 0, SpringLayout.WEST, textField);
        springLayout.putConstraint(SpringLayout.NORTH, data_field, 143, SpringLayout.NORTH, getContentPane());
        getContentPane().add(data_field);
        data_field.setColumns(10);
       
       
        JLabel lblDataPath = new JLabel("Data Path");
        springLayout.putConstraint(SpringLayout.NORTH, lblDataPath, 24, SpringLayout.SOUTH, lblEmail);
        springLayout.putConstraint(SpringLayout.WEST, lblDataPath, 0, SpringLayout.WEST, lblUsername);
        getContentPane().add(lblDataPath);
       
         final JRadioButton rdbtnAllTestCase = new JRadioButton("All Test Case");
         rdbtnAllTestCase.addChangeListener(new ChangeListener() {
             public void stateChanged(ChangeEvent e) {
                 if(rdbtnAllTestCase.isEnabled())
                     sRange_type="all";

             }
         });

        buttonGroup.add(rdbtnAllTestCase);
        springLayout.putConstraint(SpringLayout.WEST, rdbtnAllTestCase, 64, SpringLayout.WEST, getContentPane());
        getContentPane().add(rdbtnAllTestCase);
       
         final JRadioButton rdbtnNewRadioButton = new JRadioButton("Range");
         rdbtnNewRadioButton.addChangeListener(new ChangeListener() {
             public void stateChanged(ChangeEvent e) {
                 if (rdbtnNewRadioButton.isSelected()==true)
                {
                    textField_4.setVisible(true);
                    textField_5.setVisible(true);
                    sRange_type="range";           
               
                }else if(rdbtnNewRadioButton.isSelected()==false)
                {
                    textField_4.setVisible(false);
                    textField_5.setVisible(false);
                }
             }
         });

       
        buttonGroup.add(rdbtnNewRadioButton);

        springLayout.putConstraint(SpringLayout.NORTH, rdbtnNewRadioButton, 235, SpringLayout.NORTH, getContentPane());
        springLayout.putConstraint(SpringLayout.SOUTH, rdbtnAllTestCase, -2, SpringLayout.NORTH, rdbtnNewRadioButton);
        springLayout.putConstraint(SpringLayout.WEST, rdbtnNewRadioButton, 64, SpringLayout.WEST, getContentPane());
        getContentPane().add(rdbtnNewRadioButton);
       
        final JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("Selective");
        rdbtnNewRadioButton_1.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                if(rdbtnNewRadioButton_1.isSelected()==true)
                    sRange_type="selective";
            }
        });
        buttonGroup.add(rdbtnNewRadioButton_1);
        springLayout.putConstraint(SpringLayout.NORTH, rdbtnNewRadioButton_1, 6, SpringLayout.SOUTH, rdbtnNewRadioButton);
        springLayout.putConstraint(SpringLayout.WEST, rdbtnNewRadioButton_1, 64, SpringLayout.WEST, getContentPane());
        getContentPane().add(rdbtnNewRadioButton_1);
       
       
        rdbtnAllTestCase.setSelected(true);
        final JComboBox comboBox = new JComboBox();
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sRange_type="path";
               
            }
        });
        JButton btnNewButton = new JButton("OK");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //String sUsername ,sPassword,sEmail,sTest_path;

                sUsername=textField.getText().toString();
                sPassword=password_field.getText().toString();
                sEmail=email_field.getText().toString();
                sTest_path=data_field.getText().toString();
                //try{

                if (sRange_type.equalsIgnoreCase("range"))
                {       
                        try{
                            iFrom=Integer.parseInt(textField_4.getText());
                            iTo=Integer.parseInt(textField_5.getText());
                        }catch(Throwable t)
                        {
                            JOptionPane.showMessageDialog(null, "Please enter valid integer values");
                        }
                }else if (sRange_type.equalsIgnoreCase("path"))
                {
                    sPath=(String) comboBox.getSelectedItem();
                    System.out.println(sTest_path+"\\"+sPath);
                }
                else if (sRange_type.equalsIgnoreCase("none") )
                {
                   
                    JOptionPane.showMessageDialog(null, "Please choose a value in the radio button");
                }
               
           
            if (sUsername.isEmpty()==false && sPassword.isEmpty()==false && sEmail.matches("(.*)@(.*)\\.(.*)")==true && sTest_path.isEmpty()==false && sRange_type.equalsIgnoreCase("none")==false )
                {
                    System.out.println(sUsername+"\n"+sPassword+"\n"+sEmail+"\n"+sTest_path+"\n"+"Range="+sRange_type+"\n----Creating xml");
                     try {
                            
                             writer = new PrintWriter("D:\\1.xml", "UTF-8");
                            writer.println("<username>"+sUsername+"</username>");
                            writer.println("<password>"+sPassword+"</password>");
                            writer.println("<email>"+sEmail+"</email>");
                            writer.println("<testdatapath>"+sTest_path+"\\"+sPath+"</testdatapath>");
                            writer.println("<selection>"+sRange_type+"</selection>");
                            writer.println(" <from>"+iFrom+" </from>");
                            writer.println("<to>"+iTo+"</to>");
                            writer.println("<resume>"+bResume+"</resume>");
                            writer.close();
                            System.out.println("-------------SUCCESS-----------");
                    } catch (Throwable t){   
                        System.out.println(t.getCause()+"\n Error logging xml");
                     }
                }
            else
                JOptionPane.showMessageDialog(null, "Please provide valid data ");

            }
           
        });
        springLayout.putConstraint(SpringLayout.SOUTH, btnNewButton, -49, SpringLayout.SOUTH, getContentPane());
        springLayout.putConstraint(SpringLayout.EAST, btnNewButton, 0, SpringLayout.EAST, rdbtnNewRadioButton);
        getContentPane().add(btnNewButton);
       
        JButton btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        springLayout.putConstraint(SpringLayout.NORTH, btnCancel, 0, SpringLayout.NORTH, btnNewButton);
        springLayout.putConstraint(SpringLayout.WEST, btnCancel, 60, SpringLayout.EAST, btnNewButton);
        getContentPane().add(btnCancel);
       
        JButton btnHelp = new JButton("Help");
        btnHelp.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "---- Created by MARLABS (Reg) --------- ");
            }
        });
        springLayout.putConstraint(SpringLayout.WEST, btnHelp, 56, SpringLayout.EAST, btnCancel);
        springLayout.putConstraint(SpringLayout.SOUTH, btnHelp, 0, SpringLayout.SOUTH, btnNewButton);
        getContentPane().add(btnHelp);
       
        final JCheckBox chckbxNewCheckBox = new JCheckBox("Resume");
        chckbxNewCheckBox.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                if(chckbxNewCheckBox.isEnabled())
                    bResume=true;
                else
                    bResume=false;
            }
        });
        springLayout.putConstraint(SpringLayout.SOUTH, chckbxNewCheckBox, -27, SpringLayout.NORTH, btnNewButton);
        springLayout.putConstraint(SpringLayout.EAST, chckbxNewCheckBox, 0, SpringLayout.EAST, rdbtnNewRadioButton_1);
        getContentPane().add(chckbxNewCheckBox);
       
        textField_4 = new JTextField();
        springLayout.putConstraint(SpringLayout.NORTH, textField_4, 1, SpringLayout.NORTH, rdbtnNewRadioButton);
        springLayout.putConstraint(SpringLayout.WEST, textField_4, 79, SpringLayout.EAST, rdbtnNewRadioButton_1);
        springLayout.putConstraint(SpringLayout.EAST, textField_4, 14, SpringLayout.EAST, btnCancel);
        getContentPane().add(textField_4);
        textField_4.setColumns(10);
        textField_4.setVisible(false);
       
        textField_5 = new JTextField();
        springLayout.putConstraint(SpringLayout.NORTH, textField_5, 1, SpringLayout.NORTH, rdbtnNewRadioButton);
        springLayout.putConstraint(SpringLayout.EAST, textField_5, -120, SpringLayout.EAST, getContentPane());
        getContentPane().add(textField_5);
        textField_5.setColumns(10);
        textField_5.setVisible(false);
       
        JLabel lblNewLabel_2 = new JLabel("To");
        springLayout.putConstraint(SpringLayout.EAST, lblNewLabel_2, -173, SpringLayout.EAST, getContentPane());
        springLayout.putConstraint(SpringLayout.WEST, textField_5, 5, SpringLayout.EAST, lblNewLabel_2);
        springLayout.putConstraint(SpringLayout.NORTH, lblNewLabel_2, 4, SpringLayout.NORTH, rdbtnNewRadioButton);
        getContentPane().add(lblNewLabel_2);
       
       
        JLabel lblFrom = new JLabel("From");
        springLayout.putConstraint(SpringLayout.NORTH, lblFrom, 4, SpringLayout.NORTH, rdbtnNewRadioButton);
        springLayout.putConstraint(SpringLayout.EAST, lblFrom, -6, SpringLayout.WEST, textField_4);
        getContentPane().add(lblFrom);
       
         final JRadioButton rdbtnTestCasePath = new JRadioButton("Test Case Path");
         springLayout.putConstraint(SpringLayout.NORTH, rdbtnTestCasePath, 19, SpringLayout.SOUTH, data_field);
        JButton btnBrowse = new JButton("Browse");
        springLayout.putConstraint(SpringLayout.NORTH, btnBrowse, 142, SpringLayout.NORTH, getContentPane());
        springLayout.putConstraint(SpringLayout.EAST, data_field, -6, SpringLayout.WEST, btnBrowse);
        springLayout.putConstraint(SpringLayout.EAST, btnBrowse, 0, SpringLayout.EAST, btnCancel);
        btnBrowse.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Filechoose=new JFileChooser();
                Filechoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
               
                int retval=Filechoose.showOpenDialog(GUI2.this);
                if (retval == JFileChooser.APPROVE_OPTION) {
                    //... The user selected a file, get it, use it.
                    sRange_type="path";
                    file = Filechoose.getSelectedFile();
                    data_field.setText(file.getPath());
                    rdbtnTestCasePath.setVisible(true);
                    //System.out.println(file.getPath());
                }
            }
        });
        getContentPane().add(btnBrowse);

       
        springLayout.putConstraint(SpringLayout.NORTH, comboBox, 18, SpringLayout.SOUTH, btnBrowse);
        springLayout.putConstraint(SpringLayout.WEST, comboBox, 13, SpringLayout.WEST, btnCancel);
        springLayout.putConstraint(SpringLayout.EAST, comboBox, 124, SpringLayout.EAST, btnHelp);
        comboBox.setVisible(false);
       
       
         rdbtnTestCasePath.setVisible(false);
         springLayout.putConstraint(SpringLayout.WEST, rdbtnTestCasePath, 63, SpringLayout.WEST, getContentPane());

         rdbtnTestCasePath.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                 if(rdbtnTestCasePath.isSelected())
                 {
                     sRange_type="path";
                     comboBox.removeAllItems();
                     comboBox.setVisible(true);
                     File[] listOfFiles = file.listFiles();

                         for (int i = 0; i < listOfFiles.length; i++) {
                               if (listOfFiles[i].isDirectory()) {
                                  comboBox.addItem(listOfFiles[i].getName());//(listOfFiles[i].getName());
                           }
                         }
                 }
                     else
                     {
                     comboBox.setVisible(false);
                     comboBox.removeAllItems();
                     }
             }
         });
       
       
        buttonGroup.add(rdbtnTestCasePath);
        getContentPane().add(rdbtnTestCasePath);
        getContentPane().add(comboBox);
    }
}

Java : Text Reader and Text Writer into other file

 Text Reader and Text Writer into other file

Function to Write Data from a Text File : -

    // sData = Contains the data to be written  (String buffer type)
    //sPath = Path of the new file which is created and sData is written into

    public void Write_text(StringBuffer sData ,String sPath)
    {
        BufferedWriter writer = null;
        try {
//            String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
            File newFile = new File(sPath);
            writer = new BufferedWriter(new FileWriter(newFile));
            writer.append(sData);//write(sData);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (Exception e) {
            }
        }
       
    }

   
   

Function to Read Data from a Text File : -

    // sPath contains the path of the file to be read
    // ex : "C:\\Users\\deepakj\\Desktop\\report.txt"
   
    public StringBuffer Read_text(String sPath)
    {

StringBuffer Reporter = new StringBuffer();
         try { 
                File file = new File(sPath);//"C:\\Users\\deepakj\\Desktop\\report.txt");  // Path of the html file
                FileReader fr = new FileReader(file);  
                BufferedReader br = new BufferedReader(fr);                                                  
                String data = null;

                while((data = br.readLine()) != null)    
                {    
                    Reporter.append(data+"\n"); 
                }        
               
                System.out.print(Reporter);
            } catch(IOException e)
            { 
                System.out.println("bad !"); 
            }        
             return Reporter;
    }

Friday, March 7, 2014

Android : Fetch all running process ,memory and Process ID

Fetch all running process ,memory and Process ID


import java.util.List;
//import android.R;
import android.os.Bundle;
import android.os.Debug;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.ComponentName;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      
        TextView tv = (TextView) findViewById(R.id.textView);       
         ActivityManager activityManager = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
             
          List<RunningAppProcessInfo> procInfos = activityManager .getRunningAppProcesses();
         // List<RunningAppProcessInfo> procInfos2=activityManager.
         for (int idx = 0; idx < procInfos.size(); idx++)
         {
            tv.setText(tv.getText() + "" + (idx + 1) + "."  + procInfos.get(idx).processName +"(" +procInfos.get(idx).pid+")"+"\n");
         }

        
         ActivityManager localActivityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); // use Context.ACTIVITY_SERVICE not the literal "activity"
         List<ActivityManager.RunningAppProcessInfo> procsInfo = localActivityManager.getRunningAppProcesses();

         int[] pids = new int[procsInfo.size()];
         for (int i = 0; i < procsInfo.size(); i++) {
             ActivityManager.RunningAppProcessInfo info = procsInfo.get(i);
             pids[i] = info.pid;
         }

         Debug.MemoryInfo[] procsMemInfo = localActivityManager.getProcessMemoryInfo(pids);
         for (int idx = 0; idx < procsMemInfo.length; idx++)
         {
            tv.setText(tv.getText() + "" + (idx + 1) + "."  +procsMemInfo[idx].getTotalPss()+ "kb\n");
         }
    
}}

 activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
        android:layout_height="match_parent"
    tools:context=".MainActivity" >
   
        <TextView
            android:id="@+id/textView"
        android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        android:text="Running Apps \n" />
   
</RelativeLayout>

Android : Fetch Application CPU , Memory Usage ,Running Process

Fetch Application CPU , Memory Usage ,Running Process


Below given generic functions can be used in your program without any major mod.

Reference sites :
http://android-test-tw.blogspot.in/2012/10/dumpsys-information-android-open-source.html
http://www.m2catalyst.com/tutorial-finding-cpu-usage-for-individual-android-apps/
http://stackoverflow.com/questions/15148193/how-to-get-higher-precision-of-cpu-than-that-from-top-command
http://stackoverflow.com/questions/11201659/whats-android-adb-shell-dumpsys-tool-and-its-benefits
http://codeseekah.com/2012/10/21/android-shell-tricks-ps/   -(Android shell tricks: ps)




//Fetches the CPU usage of the given Process - Currently all process @ 0%

   private String process_name_cpu(String Process_name)
   {
          try{   
                 ArrayList<String> list2 = new ArrayList<String>();     


  //adb shell dumpsys cpuinfo
        //(adb shell ps | grep com.android.phone | awk '{ system("adb shell cat /proc/" $2 "/stat");}' | awk '{print $14+$15;}')
        //ps -eo pcpu,pid,user,args | sort -r -k1 | less
        //ps -t -x -P -p -c
        //ps -t -x -P -p -c [pid|name]
        //com.android.calculator2|2302
        //Process p2 = Runtime.getRuntime().exec("ps -t -x -P -p -c ["+2302+"]",null,null);

 
                 Process p2 = Runtime.getRuntime().exec("top -m 150  -d 1 -n 1",null,null);//top -m 150  -d 1 -n 1",null,null);
                 BufferedReader reader2 = new BufferedReader(new InputStreamReader(p2.getInputStream()));
                 int i2 = 0;
                 String line2 = reader2.readLine();
                 String a[]={""};          
                // System.out.println(line2);
                 while (line2 != null) {
                       // Log.e("Output "  + i2, line2);
                        list2.add(line2);
                        line2 = reader2.readLine();      
                        i2++ ;
                 }
                 p2.waitFor();
                 for (int i=0 ;i<=list2.size();i++)
                 {     
                        if(list2.get(i).contains(Process_name)==true)
                        {
                              a=list2.get(i).toString().split(" ");
                              break;
                        }
                 }
                
                 for(int i=0;i<=a.length;i++)
                 {
                        if(a[i].contains("%")==true){                            
                        System.out.println("cpu utilization" + a[i]);                      
                        return a[i];
                        }
                 }
                       
          }catch (Throwable t)
                 {
                 System.out.println("Unable to fetch cpu data ---\n"+t.fillInStackTrace());
                 }
         
          return null;
   }



   //---------------------------------------------------------------

   //Description: Retrieves the process name from the application

   //Arguements required : application_name  -- String Type---Input
                        //Ex: app_to_process_name("system")

                        //returns cpu usage --String Type (ex:com.android.system)

   private String app_to_process_name(String application_name)
   {
          try{
                 ArrayList<AppActivity> res = new ArrayList<AppActivity>();       
         
       List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);   
       String sApp_name,sProcess_name;
      
       for(int i=0;i<packs.size();i++)
       {
           PackageInfo p = packs.get(i);
           if ((p.versionName == null))
           {
               continue ;
           }    
          
           sApp_name = p.applicationInfo.loadLabel(getPackageManager()).toString();
           sProcess_name=p.applicationInfo.processName.toString();
          
           if(sApp_name.contentEquals(application_name))
           {
                //System.out.println("gotcha"+ sProcess_name );
               
              
               return sProcess_name;             //break;
                
                
           }      
       }
          }catch (Throwable t)
          {
                 System.out.println("Unable to fetch the process name from the app\n"+t.getMessage());
          }
       return null;
   }


   //Description: Retreives the memory consumed by the particular process

   //Arguements required : sProcess -- String Type---Input
                        //Ex: process_memory("com.android.system")

                        //returns memory usage --integer Type (ex: 22845) /// in kb

   // NOTE: Fetchs the PSS memory of the process
   private int process_memory(String sProcess)
   {
          try{
                 ActivityManager localActivityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); // use Context.ACTIVITY_SERVICE not the literal "activity"        
               List<ActivityManager.RunningAppProcessInfo> procsInfo = localActivityManager.getRunningAppProcesses();
         
               int[] pids = new int[procsInfo.size()];
               for (int i = 0; i < procsInfo.size(); i++)
               {
                   ActivityManager.RunningAppProcessInfo info = procsInfo.get(i);
                   pids[i] = info.pid;
               }
         
               Debug.MemoryInfo[] procsMemInfo = localActivityManager.getProcessMemoryInfo(pids);
               for (int idx = 0; idx < procsMemInfo.length; idx++)
               {
                  if(procsInfo.get(idx).processName.toString().equalsIgnoreCase(sProcess))
                  {
                     
                      System.out.println("memory" + procsMemInfo[idx].getTotalPss());
                         return procsMemInfo[idx].getTotalPss();               
                  }
               }
          }catch (Throwable t)
          {
                 Log.v("process missing","Unable to find the process");
                 System.out.println("Process not found---\n"+t.getMessage());
          //     return 0;
          }
          return 0;            
          }
  
  

Tuesday, March 4, 2014

Android : Implement an Image as Toggle button

 Implement an Image as Toggle button




Step 1 .


Step 2  : activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="@drawable/backg">

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="105dp"
    android:background="@drawable/off"
    android:button="@drawable/button_xml"
    android:minHeight="1dip"
    android:minWidth="2dip"
    android:textOff=" "
    android:textOn=" " />

</RelativeLayout>


Step 3 : MainActivity.java

public class MainActivity extends Activity {
public String result ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        final ToggleButton  tb = (ToggleButton) findViewById(R.id.toggleButton1);
         tb.setOnClickListener(new OnClickListener() {
             public void onClick(View v)
             {
                 String s;
                 if(tb.isChecked())
                     
                 {
                     s="ON";
                     Toast.makeText(getBaseContext(),"Button is ON",Toast.LENGTH_SHORT).show();         
                 }
                 else
                 {
                     s="OFF";
                     Toast.makeText(getBaseContext(),"Button is OFF",Toast.LENGTH_SHORT).show();
                     }
                 
                         }
         });
}
       

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}