Wednesday, November 28, 2012

Shell script: format numbers


Shell script to format date in yyyy.mm.dd format
#!/bin/bash

year=2012

for (( c=1; c<=12; c++ ))
do
   month=$(printf "%02d" $c)

  for (( d=1; d<=15; d++ ))
  do
     day=$(printf "%02d" $d)
     echo $year.$month.$day
  done
done

Java : Send Email


Following is the code to send email using java. Download mail.jar and activation.jar to run the program.
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailProcessor {
 
 private String mailHost;
 private String from;
 private String to;
 private String subject;
 private String text;
 
  public static void main(String[] args)
 {
  EmailProcessor emp = new EmailProcessor("mailhost", "from@test.com", "to1@test.com,to2@test.com", "Subject", "Email Text");
  emp.send();
 }
 
 public EmailProcessor(String mailhost, String from, String to, String subject, String text){
  this.from = from;
  this.to = to;
  this.subject = subject;
  this.text = text;
  this.mailHost = mailhost;
 }
 
 public void send(){
 
  Properties props = new Properties();
  
  props.put("mail.smtp.host", mailHost);
 
  Session mailSession = Session.getDefaultInstance(props);
  Message simpleMessage = new MimeMessage(mailSession);
 
  InternetAddress fromAddress = null;
  InternetAddress[] toAddress = null;
  try {
   fromAddress = new InternetAddress(from);
   
   String[] toEmails = to.split(",");
            toAddress = new InternetAddress[toEmails.length];
            for (int i = 0; i < toEmails.length; i++)
            {
             toAddress[i] = new InternetAddress(toEmails[i].trim());
            }
  } catch (AddressException e) {
   Utility.logError(e.getMessage());
   e.printStackTrace();
  }
 
  try {
   simpleMessage.setFrom(fromAddress);
            simpleMessage.setRecipients(RecipientType.TO, toAddress);
   simpleMessage.setSubject(subject);
   simpleMessage.setText(text);
 
   Transport.send(simpleMessage);
  } catch (MessagingException e) {
   Utility.logError(e.getMessage());
   e.printStackTrace();
  }
 }
}

Friday, June 8, 2012

Selenium: Testing auto complete fields

Selenium's "type" command does not trigger auto complete feature to give suggestion. We can use "typeKeys" method to simulate auto complete. Here is the sample code for this:
public static void inputTextInAutocompleteField(String testField, String testValue) 
{
        try {
                selenium.type(testField, testValue);
                selenium.typeKeys(testField," \b") ;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
Here we are first entering value in the text field, then using selenium's 'typeKeys' method to press 'space' character and then 'backspace' (\b) character.

Selenium: How to accept SSL certificates

When you run your selenium tests on any HTTPS url, things go wrong. We get certificate exception and test doesn't proceed. In firefox, the workaround for this problem is to create your own Firefox profile, with the specific certificate added on it manually and then start Selenium server with that firefox profile, but for Internet Explorer there is no such workaround.

However, we can resolve this issue by installing CyberVillains Certificate on Windows. We need to follow below steps to work Selenium with SSL.

1. Start selenium server with "-trustAllSSLCertificates" command
2. Use "*firefoxproxy" instead of "firefox" OR "*iexploreproxy" instead of "iexplore"
3. Install CyberVillains Certificate (selenium bundles a special certification authority (CA) certificate that is used to trust all the other SSL certificates.)

Installing CyberVillains Certificate
---------------------------------------
1. Extract selenium jar into a folder
2. Goto sslSupport diretory
3. Double click on cybervillainsCA.cer




Tuesday, June 5, 2012

Bash: read csv file

Here is the script to read csv file in shell script.
#!/bin/bash
FILENAME=test.csv
OLDSEP=$IFS
IFS=,

[ ! -f $FILENAME ] && { echo "File not found : $FILENAME"; exit 99; }

while read field1 field2 field3 field4
do
    echo "$field1 : $field2 : $field3 : $field4"
done < $FILENAME

IFS=$OLDSEP

Cannot remove directory: File exists

I was trying to remove a directory and got error: "cannot remove directory 'logs/': File exists"
$chmod -R 777 logs/
$rm -rf logs/
$rm: cannot remove directory 'logs/': File exists
Checked the logs folder content and found out that there was .nfs*** file in this, when I manually deleted this file, it was recreated immediately and the timestamp of the file was not current, it was same of which I just deleted.
$ls -lrta
total 20K
drwxrwxrwx 3 test vishnu 4.0K May  3 03:27 ..
-rwxrwxr-x 1 test vishnu  11K May  3 03:27 .nfs29682
drwxrwxr-x 2 test vishnu 4.0K Jun  4 23:17 .
To solve this issue, we need to find out which process is using this file and delete that process.
$/usr/sbin/fuser -u logs/.*
logs/.:    
logs/..:    
logs/.nfs29682:     23142m(test)
23142 is the process which is using this directory, we need to kill it.
kill -9 23142
now delete the directory, it will be deleted successfully.
$rm -rf logs/
$

Thursday, April 19, 2012

Selenium: Check if Selenium Server is running

If you want to check whether selenium server is running or not, hit the url "http://host:port/selenium-server/driver/?cmd=testComplete", If response is returned that means, server is running on the given host:port. Here is the Java code for this:


import java.net.HttpURLConnection;
import java.net.URL;

public static boolean isSeleniumServerRunning(String host, int port) 
  {
   try {
    String baseUrl = "http://" + host + ":" + port;
    System.out.println("Checking selenium server status [" + baseUrl + "]");
    URL url = new URL(baseUrl + "/selenium-server/driver/?cmd=testComplete");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    
    if(connection.getResponseCode() == HttpURLConnection.HTTP_OK)
     return true;
  } catch (Exception e) {
   System.err.println("Could not check selenium server status: " + e.getMessage());
   e.printStackTrace();
  }   
  return false;
  }

Java: Copy Directory structure

Here is the code for copying a directory structure
 public static void copyFolder(String srcFile, String destFile) throws IOException
 {
  File src = new File(srcFile);
  File dest = new File(destFile);
  
  if(!src.exists())
  {
   System.out.println("Source folder do not exists [" + srcFile + "]");
   return;
  }
  
  if(src.isDirectory())
  {
    //if directory not exists, create it
    if(!dest.exists())
    {
       dest.mkdir();
    }

    //list all the directory contents
    String files[] = src.list();

    for (String file : files) 
    {
     
     //construct the src and dest file structure
     String sourceFile = src.getAbsolutePath() + File.separator + file;
     String destinationFile = dest.getAbsolutePath() + File.separator + file;
     
     //recursive copy
     copyFolder(sourceFile, destinationFile);    }
  }
  else
  {
    //if file, then copy it
    //Use bytes stream to support all file types
    InputStream in = new FileInputStream(src);
          OutputStream out = new FileOutputStream(dest); 

          byte[] buffer = new byte[1024];

          int length;
          //copy the file content in bytes 
          while ((length = in.read(buffer)) > 0){
          out.write(buffer, 0, length);
          }

          in.close();
          out.close();
  }
 }

Java: Comparing Arrays

Want to compare arrays of which item may not be in same order. Here is the solution:

public static boolean compareArrays(String[] actual, String[] expected)
    {
        if(actual == null || expected == null)
            return false;
       
        Arrays.sort(actual);
        Arrays.sort(expected);
       
        if(Arrays.equals(actual, expected))
            return true;
        else
            return false;
    }