Saturday, December 10, 2016

How to check if a String and Integre List is sorted in ascending and descending using Java?

protected static boolean isStringListSorted(List data, boolean ascending) {

        if (ascending) {
            for (int i = 0; i < data.size() - 1; i++) {
                if (data.get(i).compareTo(data.get(i + 1)) > 0) {
                    System.out.println(data.get(i) + " AND " + data.get(i + 1) + " Not in ascending order");
                    return false;
                }
            }
        } else {

            for (int i = 0; i < data.size() - 1; i++) {
                if (data.get(i).compareTo(data.get(i + 1)) < 0) {
                    System.out.println(data.get(i) + " AND " + data.get(i + 1) + " Not in descending order");
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean isIntegerListSorted(int[] data, boolean ascending) {
        if (ascending) {
            for (int i = 0; i < data.length; i++) {
                if (data[i] < data[i+1]) {
                    System.out.println(data[i] + " AND " + data[i+1] + " Not in ascending order");
                    return false;
                }
            }
        } else {
            for (int i = 0; i < data.length; i++) {
                if (data[i] > data[i+1]) {
                    System.out.println(data[i] + " AND " + data[i+1] + " Not in descending order");
                    return false;
                }
            }
        }

        return true;
    }

Saturday, November 5, 2016

Create a folder with Time Stamp


/**

* Create a folder with Time Stamp
* @return Path of the folder Created


*/
public static String CreateFolderWithTimeStamp()

{
Date today = Calendar.getInstance().getTime();

// (2) create our date "formatter" (the date format we want)
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss");

// (3) create a new String using the date format we want
String folderName = formatter.format(today);
folderName = "D://" + folderName;

//String filename = String.Format("archive_{0:yyyyMMdd}", DateTime.Today);
File dir = new File(folderName);

// Tests whether the directory denoted by this abstract pathname exists.
boolean exists = dir.exists();
System.out.println("Directory " + dir.getPath() + " exists: " + exists);
if (exists) {
System.out.println("Main Folder Exist");
}
else{
System.out.println("Main Folder Doesnt Exist");
File directory = new File(folderName);
directory.mkdir();
}
return folderName ;
}

Thursday, September 15, 2016

Get Data From Webpage PDF File

public String getPDFpageData(Webdriver driver) throws Exception {

URL nav = new URL(driver.getCurrentUrl());
BufferedInputStream page = new BufferedInputStream(nav.openStream());
PDDocument pdfdoc = null;
try{
pdfdoc = PDDocument.load(page);
String result = new PDFTextStripper().getText(pdfdoc);
System.out.println(result);
}finally{
if( pdfdoc != null)
{
pdfdoc.close();
}//end of if
if( page != null)
{
page.close();
}//end of if
}//finally
return result;
}//main

Tuesday, August 23, 2016

Find Broken / Invalid Links and Images on a Page



/**
* Validate invalid images on the webpage
*/

public void validateInvalidImages() {

try {

int invalidImageCount = 0;

List "<"imagesList">" = driver.findElements(By.tagName("img"));
System.out.println("Total no.of images are :: " + imagesList.size());
for (WebElement imgElement : imagesList) {
if (imgElement != null) {
invalidImageCount = verifyimageActive(imgElement);
}
}
System.out.println("Total no.of invalid images are :: " + invalidImageCount);

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

}

public static void verifyimageActive(WebElement imgElement) {
int invalidImageCount =0;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(imgElement.getAttribute("src"));
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != 200){
invalidImageCount++;
}
} catch (Exception e) {
e.printStackTrace();
}
return invalidImageCount;
}


/**
* Validate brokenLinks on the webpage
*/

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class VerifyLinks {
 public static void main(String[] args)
 {
  WebDriver driver=new FirefoxDriver(); 
  driver.manage().window().maximize(); 
  driver.get("http://www.google.co.in/");
 
  List links=driver.findElements(By.tagName("a"));
  System.out.println("Total links are "+links.size());
 
  for(int i=0;i<
links.size(); i++){
   WebElement ele= links.get(i);
   String url=ele.getAttribute("href");
   verifyLinkActive(url);
  }
 }

 public static void verifyLinkActive(String linkUrl)
 {
        try
        {
           URL url = new URL(linkUrl);
           HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
           httpURLConnect.setConnectTimeout(3000);
           httpURLConnect.connect();
 
           if(httpURLConnect.getResponseCode()==200)
           {
               System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage());
            }
          if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND) 
           {
               System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage() + " - "+ HttpURLConnection.HTTP_NOT_FOUND);
            }
        } catch (Exception e) {
           e.printStackTrace();
        }
    }
 
}

Tuesday, August 9, 2016

How to check data with arthematic Operators in Java?


public static void compareTo() {

String s1 = "Say";

String s2 = "Tell";



if (s1.compareTo(s2) > 0) {

System.out.println("s1 is Greater s2");

} else if (s1.compareTo(s2) < 0) {

System.out.println("s1 is Lesser s2");

} else if (s1.compareTo(s2) == 0) {

System.out.println("s1 is equal to s2");

} else if (s1.compareTo(s2) != 0) {

System.out.println("s1 is Not equal to s2");

} else if (s1.compareTo(s2) >= 0) {

System.out.println("s1 is GreaterThan to s2");

} else if (s1.compareTo(s2) <= 0) {

System.out.println("s1 is LessThan to s2");

}

}

Tuesday, August 2, 2016

How to Resolve the Certificate Error with Selenium Webdriver?

IE :

driver.get("yourwebsite url that had certificate error");
driver.navigate().to("javascript:document.getElementById('overridelink').click()");
Thread.sleep(5000);

FIREFOX:

DesiredCapabilities capabilities = new DesiredCapabilities(); 
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); 
driver= new FirefoxDriver(capabilities);
driver.get("yourwebsite url that had certificate error");

Chrome:

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
 capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); 
 System.setProperty("webdriver.chrome.driver", "path to file chromedriver.exe");
 WebDriver driver = new ChromeDriver(capabilities);
 driver.get("yourwebsite url that had certificate error");
 
 

 

Wednesday, July 27, 2016

Getting the name of the current executing method

String methodName = new Object(){}.getClass().getEnclosingMethod().getName();
(OR)
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
 

 
 
 
 
 

Monday, July 25, 2016

Currency and Phone Number Format Check?


public String currencyFormatCheck(String location, int currencyValue) {
if (location.equalsIgnoreCase("US")) {
Locale currentLocale = Locale.US;
Double currencyAmount = new Double(currencyValue);
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
return currencyFormatter.format(currencyAmount);
} else if (location.equalsIgnoreCase("UK")) {
Locale currentLocale = Locale.UK;
Double currencyAmount = new Double(currencyValue);
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
return currencyFormatter.format(currencyAmount);
}
return null;
}
 
private static boolean phoneNumberFormatCheck(String phoneNo) {
// validate phone numbers of format "1234567890"
if (phoneNo.matches("\\d{10}"))
return true;
// validating phone number with -, . or spaces
else if (phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}"))
return true;
// validating phone number with extension length from 3 to 5
else if (phoneNo.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}"))
return true;
// validating phone number where area code is in braces ()
else if (phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}"))
return true;
// return false if nothing matches the input
else
return false;
}

//Example '(866) 825-3227' then you can use below regular expression

public static boolean validatePhone(String phone) {
 String phonePattern = "\\([0-9]{3}) [0-9]{3}\\-[0-9]{4}";
 // e.g. (866) 825-3227
 Pattern pattern = Pattern.compile(phonePattern);
 Matcher matcher = pattern.matcher(phone);
 return matcher.matches();
}

Tuesday, July 5, 2016

Resizing a web element using movebyoffset

public void resize(WebElement elementToResize, int xOffset, int yOffset) {
        try {
        if (elementToResize.isDisplayed()) {
        Actions action = new Actions(driver);
        action.clickAndHold(elementToResize).moveByOffset(xOffset, yOffset).release().build().perform();
        } else {
        System.out.println("Element was not displayed to drag");
        }
        } catch (StaleElementReferenceException e) {
        System.out.println("Element with " + elementToResize + "is not attached to the page document "  + e.getStackTrace());
        } catch (NoSuchElementException e) {
        System.out.println("Element " + elementToResize + " was not found in DOM " + e.getStackTrace());
        } catch (Exception e) {
        System.out.println("Unable to resize" + elementToResize + " - " + e.getStackTrace());
        }
        }

(OR)

moveToElement(WebElement toElement, int xOffset, int yOffset)
Moves the mouse to an offset from the top-left corner of the element.
 
Actions builder = new Actions(driver);   
builder.moveToElement(knownElement, 10, 25).click().build().perform();

Monday, June 20, 2016

TestNG Annotation

TestNG Annotation

Annotation
Description
@BeforeSuite
The annotated method will be run only once before all tests in this suite have run.
@AfterSuite
The annotated method will be run only once after all tests in this suite have run.
@BeforeClass
The annotated method will be run only once before the first test method in the current class is invoked.
@AfterClass
The annotated method will be run only once after all the test methods in the current class have been run.
@BeforeTest
The annotated method will be run before any test method belong ing to the classes inside the tag is run.
@AfterTest
The annotated method will be run after all the test methods belong ing to the classes inside the tag have run.
@BeforeGroups
The list of g roups that this config uration method will run before. T his method is g uaranteed to run shortly before the first test method that belong s to any of these g roups is invoked.
@AfterGroups
The list of g roups that this config uration method will run after. T his method is g uaranteed to run shortly after the last test method that belong s to any of these g roups is invoked.
@BeforeMethod
The annotated method will be run before each test method.
@AfterMethod
The annotated method will be run after each test method.
@DataProvider
Marks a method as supplying data for a test method. The annotated method must return an Object[][] where each Object[] can be assig ned the parameter list of the test method. T he @T est method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.
@Factory
Marks a method as a factory that returns objects that will be used by T estNG as Test classes. T he method must return Object[].
@Listeners
Defines listeners on a test class.
@Parameters
Describes how to pass parameters to a @T est method.
@Test
Marks a class or a method as part of the test.
 
 Note: alwaysRun, If set to true, this test method will always be run even if it depends on a method that failed.
 
 public class AnnotationsTest {

    @BeforeSuite(alwaysRun = true)
    public static void beforeSuite() {
        System.out.println("@BeforeSuite");
    }

    @BeforeTest(alwaysRun = true)
    public static void beforeTest() {
        System.out.println("@BeforeTest");
    }
  
    @BeforeClass(alwaysRun = true)
    public static void beforeClass() {
        System.out.println("@BeforeClass");
    } 

    @BeforeMethod(alwaysRun = true)
    public static void beforeMethod() {
        System.out.println("@BeforeMethod");
    }

      @Test
    public void test() {
        System.out.println("Test");
    }

    @Test
    public void test2() {
        System.out.println("Test2");
    }

    @AfterMethod(alwaysRun = true)
    public static void afterMethod() {
        System.out.println("@AfterMethod");
    }

     @AfterClass(alwaysRun = true)
    public static void afterClass() {
        System.out.println("@AfterClass");
    }

     @AfterTest(alwaysRun = true)
    public static void afterTest() {
        System.out.println("@AfterTest");
    }  

    @AfterSuite(alwaysRun = true)
    public static void afterSuite() {
        System.out.println("@AfterSuite");
    }
    
}

Output:
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
Test  
@AfterMethod
@BeforeMethod
Test2  
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite

Friday, May 20, 2016

Read Emails From Inbox Using Java?


Outlook Settings:

The following settings are the official POP, IMAP and SMTP settings provided by Microsoft for Office 365. You can find these settings in the following locations:

1. In the Outlook Web App, go to Settings.

2. In the Search box at the top, type "POP and IMAP"

3. Click the Sync Email tab on the left-hand menu to edit the POP and IMAP settings.

Gmail Settings:

Check that IMAP is turned on

  1. On your computer, open Gmail.
  2. In the top right, click Settings See all  settings.
  3. Click the Forwarding and POP/IMAP tab.
  4. In the "IMAP access" section, select Enable IMAP.
  5. Click Save Changes.

POP settings

Server name: outlook.office365.com
Port: 995
Encryption method: SSL

Server name: pop.gmail.com
Port: 995
Encryption method: SSL

IMAP settings

Server name: outlook.office365.com
Port: 993
Encryption method: SSL

Server name: imap.gmail.com
Port: 993
Encryption method: SSL

SMTP settings

Server name: smtp.office365.com
Port: 587
Encryption method: TLS or STARTTLS

Server name: smtp.gmail.com
Port SSL: 465
Port for TLS/STARTTLS: 587

 

import java.io.IOException;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage.RecipientType;

public class GmailMailVerification {

private static String user = xyz@gmail.com;
private static String password = "abcd";
final static int MAX_MESSAGES = 10;

public static void main(String argv[]) {
//Read username and password from argments
for (int optind = 0; optind < argv.length; optind++) {
if (argv[optind].equals("-U")) {
user = argv[++optind];
} else if (argv[optind].equals("-P")) {
password = argv[++optind];
}
}

Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");

try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", user, password);
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);

System.out.println("Total messages = " + inbox.getMessageCount());
System.out.println("New messages = " + inbox.getNewMessageCount());
System.out.println("Unread messages = " + inbox.getUnreadMessageCount());
System.out.println("Deleted messages = " + inbox.getDeletedMessageCount());

// Get the last 10 messages
int end = inbox.getMessageCount();
int start = end - MAX_MESSAGES + 1;
Message messages[] = inbox.getMessages(start, end);

// Reverse the ordering so that the latest comes out first
Message messageReverse[] = reverseMessageOrder(messages);

// Print the messages out
System.out.println("message size = " + messages.length);
int i = 0;
for (Message message : messageReverse) {
i++;
dumpMessage(i, message);
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}

/*
* reverse the order of the messages
*/
private static Message[] reverseMessageOrder(Message[] messages) {
Message revMessages[] = new Message[messages.length];
int i = messages.length - 1;
for (int j = 0; j < messages.length; j++, i--) {
revMessages[i] = messages[j];
}
return revMessages;
}

private static void dumpMessage(int i, Message message) throws MessagingException {
System.out.println(i + " Message envelope");
System.out.println("------------------");

// FROM
for (Address address : message.getFrom()) {
System.out.println("FROM: " + address.toString());
}

// TO
for (Address address : message.getRecipients(RecipientType.TO)) {
System.out.println("To: " + address.toString());
}

// SUBJECT
System.out.println("Subject: " + message.getSubject());

// BODY MESSAGE
try {
String content = message.getContent().toString();
System.out.println("Body Message: " + content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
---------------------------- OR ----------------------

String host = "pop.gmail.com";
String port = "995";
String userName = "xxxx@gmail.com";
String password = "xxxx";
boolean isconnected = false;
Store store = null;
Folder inbox;
Message[] messages;

/**
* Connect to mail client
* @param host
* @param port
* @param userName
* @param password
* @return
*/
public boolean getConnection(String host, String port, String userName, String password) {
Properties properties = new Properties();

// ---------- Server Setting---------------
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", port);
properties.put("mail.smtp.ssl.enable", "true");

// ---------- SSL setting------------------
properties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.pop3.socketFactory.fallback", "false");
properties.setProperty("mail.pop3.socketFactory.port", String.valueOf(port));
Session session = Session.getDefaultInstance(properties);
if (!isconnected) {
try {
// Get the POP3 store provider and connect to the store.
store = session.getStore("pop3");
store.connect(userName, password);
isconnected = true;
// opens the inbox folder
System.out.println("Getting INBOX..");
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
System.out.println("Connected to mail client: " + isconnected);
System.out.println("Connected to mail via " + host);
} catch (Exception e) {
e.printStackTrace();
}
}
return isconnected;

}

public String getSubject() {
String subject = "";
try {
if (!isconnected) {
getConnection(host, port, userName, password);
}

// fetches new messages from server
messages = inbox.getMessages();
System.out.println("You have " + messages.length + " mails in your INBOX");

int i = messages.length - 1;
Message message = messages[i];
subject = message.getSubject();
System.out.println("Mail Subject: " + subject);
} catch (Exception e) {
e.printStackTrace();
}
return subject;
}

public String getBodyContent() {
String messageContent = "";
try {
if (!isconnected) {
getConnection(host, port, userName, password);
}
messages = inbox.getMessages();

int i = messages.length - 1;
Message message = messages[i];

String contentType = message.getContentType();

if (contentType.contains("multipart")) {
// content may contain attachments
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
messageContent = getText(message);
} else {
// this part for the message content
messageContent = part.getContent().toString();
}
}
} else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}

} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Mail Body Message: " + messageContent);
return messageContent;
}

public String getAttachmentFileName() {
String fileName = "";
try {
if (!isconnected) {
getConnection(host, port, userName, password);
}
messages = inbox.getMessages();
int i = messages.length - 1;
Message message = messages[i];

String contentType = message.getContentType();

if (contentType.contains("multipart")) {
// content may contain attachments
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
fileName = part.getFileName();
}

}
}

} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Attachment File Name: " + fileName);
return fileName;
}

public static String getText(Part p) {
try {

if (p.isMimeType("text/*")) {
String s = (String) p.getContent();
return s;
}

if (p.isMimeType("multipart/alternative")) {
// prefer html text over plain text
Multipart mp = (Multipart) p.getContent();
String text = null;
for (int i = 0; i < mp.getCount(); i++) {
Part bp = mp.getBodyPart(i);
if (bp.isMimeType("text/plain")) {
if (text == null)
text = getText(bp);
continue;
} else if (bp.isMimeType("text/html")) {
String s = getText(bp);
if (s != null)
return s;
} else {
return getText(bp);
}
}
return text;
} else if (p.isMimeType("multipart/*")) {
Multipart mp = (Multipart) p.getContent();
for (int i = 0; i < mp.getCount(); i++) {
String s = getText(mp.getBodyPart(i));
if (s != null)
return s;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public void deleteEmails() throws Exception {
try {
if (!isconnected) {
getConnection(host, port, userName, password);
}
messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
message.setFlag(Flags.Flag.DELETED, true);
}
inbox.close(true);
store.close();
System.out.println("deleted mail");
} catch (Exception e) {
e.printStackTrace();
}
}

public void closeMailConnections() throws MessagingException {
if (null != inbox && null != store) {
try {
inbox.close(false);
store.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}