Saturday, January 30, 2016

File download from url

public static Logger APP_LOGS = Logger.getLogger(HttpDownloadUtility.class.getName());
private static final int BUFFER_SIZE = 4096;

/**
* Downloads a file from a URL
*
* @param fileURL
* HTTP URL of the file to be downloaded
* @param saveDir
* path of the directory to save the file
* @throws IOException
*/
public static void downloadFile(String fileURL, String saveDir) {
try {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();

// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();

if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
}

System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);

// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;

// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);

int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}

outputStream.close();
inputStream.close();

System.out.println(fileName + " File downloaded successfully");
APP_LOGS.info(fileName + " File downloaded successfully");
} else {
APP_LOGS.error("No file to download. Server replied HTTP code: " + responseCode);
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
} catch (Exception e) {
APP_LOGS.error("Could not able to download file : " + e.getMessage());
}
}

Friday, January 29, 2016

Properties file Read/Write in Java

protected static Properties prop;
/**
* Method to load Property files
*
* @param filePath
* @return Properties
* @throws Exception
*/
public static Properties loadProperties(String filePath) throws Exception {
try {
prop = new Properties();
// Read object repository file
FileInputStream fis = new FileInputStream(new File(filePath));

// load all objects
prop.load(fis);
return prop;
} catch (Exception e) {
e.printStackTrace();;
}
return prop;

}

/**
* Method to get property valueF
*
* @param p
* -Properties
* @param name
* @return propValue
*/
public static String getProperties(Properties p, String name) {
String propValue = null;
try {
propValue = p.getProperty(name);
return propValue;
} catch (Exception e) {
e.printStackTrace();
}
return propValue;
}
 
/**
     * To set value into Property file
     *
     * @param prop
     * @param key
     * @param value
     */
    public void setProperty(Properties prop, String key, String value, String filePath) throws Exception {
        try {
            prop.setProperty(key, value);
            prop.store(new FileOutputStream(filePath), null);
        } catch (Exception e) {
          e.printStackTrace();
        }
    }
 
/**
     * Loading A Property File From The Classpath
     *
     * @param fileName
     *            - only file name without complete path
     * @throws Exception
     */
    public Properties loadPropertyFileFromClasspath(String fileName) throws Exception {
        try {
            if (fileName != null && !fileName.isEmpty()) {
                InputStream ins =  this.getClass().getClassLoader().getResourceAsStream(fileName);
                prop.load(ins);
            } else {
                throw new Exception("property file '" + fileName + "' not found in the classpath");
            }
        } catch (Exception e) {
            throw new Exception("Error while loadProperties: " + e.toString());
        }
        return prop;

    }

Monday, January 25, 2016

Capturing Page JavaScript Errors Using Selenium WebDriver


public void printPageErrors() throws Exception {
    //Capture all errors and store them In array.
    List Errors = JavaScriptError.readErrors(driver);
    System.out.println("Total No Of JavaScript Errors : " + Errors.size());
    //Print Javascript Errors one by one from array.
        for (int i = 0; i < Errors.size(); i++) {
            System.out.println("Error Message : " + Errors.get(i).getErrorMessage());
            System.out.println("Error Line No : " + Errors.get(i).getLineNumber());
            System.out.println(Errors.get(i).getSourceName());
            System.out.println();
        }
 }


Note: Need to download "JSErrorCollector-0.5.jar"
need to download "JSErrorCollector-0.5.jar"

Saturday, January 23, 2016

How To Get X Y and Height Width Coordinates Of Element In Selenium WebDriver


public void getCoordinates() throws Exception {
 //Locate element for which you wants to retrieve x y coordinates.
    WebElement Image = driver.findElement(By.xpath("//img[@border='0']"));
    //Used points class to get x and y coordinates of element.
    Point point = Image.getLocation();
    int xcord = point.getX();
    System.out.println("Element's Position from left side Is "+xcord +" pixels.");
    int ycord = point.getY();
    System.out.println("Element's Position from top side Is "+ycord +" pixels.");
 }

public void getSize() throws Exception {
//Locate element for which you wants to get height and width.
    WebElement Image = driver.findElement(By.xpath("//img[@border='0']"));
    //Get width of element.
    int ImageWidth = Image.getSize().getWidth();
    System.out.println("Image width Is "+ImageWidth+" pixels");
    //Get height of element.
    int ImageHeight = Image.getSize().getHeight();
    System.out.println("Image height Is "+ImageHeight+" pixels");
 } 

How To Handle Stale Element Reference Exception in Selenium Webdriver

public boolean retryingFindClick() {
boolean result = false;
 int count = 0;
// It will try 2 times to find same element using name.
    while (count < 2) {
         try {
                //If exception generated that means It Is not able to find element
               //then catch block will handle It.
               WebElement webEle = driver.findElement(By.name("name"));
               //If exception not generated that means element found
               //and element text get cleared.
              webEle.click();
              result = true;
              break;
         } catch (StaleElementReferenceException e) {
                System.out.println("Trying to recover from a stale element :"
                                                 + e.getMessage());
         }
          count++;
    }
    return result;
}