I am having single column in excel sheet which I want to replicate in Jython scripting and place it in adjacent column.The Content of the Column is as in the Pic below

from jxl import *
from jxl.write import *
from java.io import File
workbook = Workbook.getWorkbook(File("$(TargetFolder)\Book2.xls"))
targetWorkbook = Workbook.createWorkbook(File("$(TargetFolder)\Book2.xls"),
workbook)
sheet = targetWorkbook.getSheet(0)
columnIndex = 0

rowCount = sheet.getRows()

for i in range(rowCount):
 row = sheet.getRow(i)
 content = row[columnIndex].getContents()
 rc.logMessage("Content -> " + content)    
 wc = sheet.getWritableCell(1,i)
 newLabel = Label(1,i, content)
 sheet.addCell(newLabel)
 
targetWorkbook.write() 
targetWorkbook.close()
workbook.close()

Before running Script
null

After running Script
null

How to get Total Columns Returned by Query

 ResultSet rs = stmt.executeQuery(strSQL);
 ResultSetMetaData rsmd = rs.getMetaData();
 int columnsNumber = rsmd.getColumnCount();

How to get Column Name from Query

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 ResultSetMetaData rsmd = rs.getMetaData();
 String name = rsmd.getColumnName(1);

How to get Column Count from Query and Loop Through That

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();

// The column count starts from 1
for (int i = 1; i < columnCount + 1; i++ ) {
  String name = rsmd.getColumnName(i);
  // Do stuff with name
}

To Find a Column with particular Name

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 rs.getString(rs.findColumn("fullname"));

How to get List of Column Names from Query and Store it in a Array

 ResultSetMetaData meta = resultset.getMetaData();  
 Integer columncount = meta.getColumnCount();
 int count = 1 ; 
 String[] columnNames = null;

 while(columncount <=count)
  columnNames [i] = meta.getColumnName(i);

 System.out.println (columnNames.size());

The Servlet which loads the Singleton class should be loaded during the server startup

ConfigServlet.java

public class ConfigServlet extends HttpServlet
{	
	@Override
	public void init() throws ServletException
	{
	  super.init();
	  SingletonDBConnection.getInstance();
	}
}

web.xml

<servlet>
   <servlet-name>StartUpServlet</servlet-name>
   <servlet-class>com.mugil.tutor.ConfigServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

DBConnection.java

public class DBConnection
{
	public Connection getDBConnection()
	{
		Connection connection = null;

		try
		{
			connection = DriverManager.getConnection(
					"HOST_NAME", "USER_NAME", "PASSWORD");

		}
		catch (SQLException e)
		{
			e.getLocalizedMessage();	
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
			return null;
		}
		return connection;
	}
}

SingletonDBConnection.java

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class SingletonDBConnection
{
	private static SingletonDBConnection singleInstance;
	private static DataSource dataSource;
	private static Connection dbConnect;
	
	private SingletonDBConnection()
	{
		try
		{
			Context initContext = new InitialContext();
			Context envContext  = (Context) initContext.lookup("java:/comp/env");
			dataSource		   = (DataSource) envContext.lookup("jdbc/testdb");
			
			try
			{
				dbConnect  = dataSource.getConnection();
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			} 	
		}
		catch (NamingException e)
		{
			e.printStackTrace();
		}
	}
	
	public static SingletonDBConnection getInstance()
	{
		if(singleInstance == null)
		{
			synchronized (SingletonDBConnection.class)
			{
				if(singleInstance == null)
				{
					singleInstance = new SingletonDBConnection();
				}
			}
		}

		return singleInstance;
	}
	
	public static Connection getConnInst()
	{
		try
		{
			dbConnect = dataSource.getConnection();
		}
		catch (SQLException e1)
		{
			e1.printStackTrace();
		}
		
		if(dbConnect == null)
		{
			try
			{
				Context initContext = new InitialContext();
				Context envContext  = (Context) initContext.lookup("java:/comp/env");
				dataSource		    = (DataSource) envContext.lookup("jdbc/testdb");
				
				try
				{
					dbConnect  = dataSource.getConnection();
				}
				catch (SQLException e)
				{
					e.printStackTrace();
				} 	
			}
			catch (NamingException e)
			{
				e.printStackTrace();
			}
		}
		
		return dbConnect;		 
	}
}

ListUsers.java

public List<User> getUsersList()
	{
		Connection conn;
		Statement  stmt = null;
		ResultSet  rs;
		List<User> arrUsersList = new ArrayList<User>();
		conn = SingletonDBConnection.getInstance().getConnInst();
		
		String strSQL = "SELECT UserId, UserName, Gender, UserLocation " +
						"  FROM tblusers";
		
		try
		{
			stmt = conn.createStatement();			
			rs = stmt.executeQuery(strSQL);
			
			while(rs.next())
			{
				User objUser = new User();
				objUser.setUserId(rs.getString("UserId"));
				objUser.setUserName(rs.getString("UserName"));
				objUser.setUserGender(rs.getString("Gender"));
				objUser.setUserLocation(rs.getString("UserLocation"));
				arrUsersList.add(objUser);
			}
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if(conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }
		}
		
		
		return arrUsersList;
	}

How to Avoid unnessecary HTML Code while generating HTML for Mail or HTML File

Method1

DataOutputStream dosReport = new DataOutputStream(new FileOutputStream(fileName));

dosReport.wrtiteBytes("<table><thead>");

dosReport.writeBytes("<th>Column1</th>");
dosReport.writeBytes("<th>Column2</th>");
dosReport.writeBytes("<th>Column3</th>");
dosReport.writeBytes("<th>Column4</th>");
dosReport.writeBytes("<th>Column5</th>");
dosReport.writeBytes("<th>Column6</th>");
dosReport.writeBytes("<th>Column7</th>");
dosReport.writeBytes("<th>Column8</th>");
dosReport.writeBytes("<th>Column9</th>");

dosReport.wrtiteBytes("</thead>");

Method2
Replace with Below


DataOutputStream dosReport = new DataOutputStream(new FileOutputStream(fileName));
dosReport.wrtiteBytes("<table><thead>");

String[] columns = {"Column1", "Column2", "Column3", 
                    "Column4", "Column5", "Column6", 
                    "Column7", "Column8", "Column9"};

for(int i = 0; i < columns.length; i++)
 dosReport.writeBytes("<th>" + columns[i] +"</th>");

dosReport.wrtiteBytes("</thead>");

Disadvantage:
In the Method1 you have fine control over individual cell(tds) so you can add properties like align, individual stylings can be applied.

The below code reads a Sample.txt file and places the content in a newly created Html file Sample.html.

The file from which the content should be read is placed in a project directory which is printed in the console using the below java code.

System.out.println("Working Directory = " + System.getProperty("user.dir"));

The above code prints the current project directory in console.

package com.mugil.servlets;

import java.awt.Desktop;
import java.io.*;

class GenerateHTML 
{
    public static void main(String[] args) throws Exception 
    {    	
    	System.out.println("Working Directory = " +
                System.getProperty("user.dir"));
        BufferedReader br = new BufferedReader(new FileReader("Sample.txt"));
        File f = new File("source.htm");
        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        bw.write("<html>");
        bw.write("<body>");
        bw.write("<h1>ShowGeneratedHtml source</h1>");

        String line;
        while ((line=br.readLine())!=null) {
            bw.write(line);
            bw.newLine();
        }        
        bw.write("</body>");
        bw.write("</html>");

        br.close();
        bw.close();

        Desktop.getDesktop().browse(f.toURI());
    }
}

executeupdate vs executequery vs execute

ResultSet executeQuery() – Used for reading the content of the database.
output will be in form of ResultSet.
eg – SELECT statement.

int executeUpdate() – Used for DML(altering the database).
output will be in int.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.

boolean execute() – Executing SQL statements.
output will be in boolean. TRUE indicates the result is a ResultSet and FALSE indicates it has the int value which denotes number of rows affected by the query.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.

Element Locators using XPath

Expressions

 xpath=xpathExpression
   xpath=//img[@alt='The image alt text']
   xpath=//table[@id='table1']//tr[4]/td[2]
   xpath=//a[contains(@href,'#id1')]
   xpath=//a[contains(@href,'#id1')]/@class
   xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
   xpath=//input[@name='name2' and @value='yes']
   xpath=//*[text()="right"]

DOM – Javascript

 xpath=xpathExpression
 dom=document.forms['myForm'].myDropdown
 dom=document.images[56]
 dom=function foo() { return document.links[1]; }; foo();

How to find particular text in web driver method

WebDriver driver = new FirefoxDriver();
driver.get("https://localhost:8080/Login");

//Finds the xpath of element which contains UserName
WebElement strElemnt1 = driver.findElement(By.xpath("html/body/div[1]/div[2]/div[2]/div[2]/p[1]/b"));

How to get Last Row in Table

//How to get Last Row in Table 
String cssLast="table[class='dataTable']>tr:first-child>td:last-child"
String cssFirst="table[class='dataTable']>tr:last-child>td:last-child"

driver.findElement(By.cssSelector(cssLast)).getText();
driver.findElement(By.cssSelector(cssFirst)).getText();

By Using XPath

//By Using XPath
WebElement lastCellInFirstRow = driver.findElement(By.xpath("table[@class='dataTable']//tr[1]//td[last()]"));
WebElement lastCellInLastRow = driver.findElement(By.xpath("table[@class='dataTable']//tr[last()]//td[last()]"));

How to detect custom attribute

//How to detect custom attribute 
assertTrue(selenium.isElementPresent("//*[@btn-tag-title='Sign In']"));
selenium.click("//*[@btn-tag-title='Sign In']");

assertTrue(selenium.isElementPresent("css=*[btn-tag-title='Sign In']"));
selenium.click("css=*[btn-tag-title='Sign In']");

Finding custom attribute of span where attr=”data-automation-id” and val=”SEL_ERR”

//HTML Code
<span data-automation-id="SEL_ERR">
  Error Description
</span>

//Selenium Code
driver.findElement(By.cssSelector("span[data-automation-id='SEL-ERR']"));

If Selenium cannot find it, it’ll throw an exception. Exceptions are costly. You can use .findElements instead (mentioned in 1)), which will simply return an empty list if it cannot find the element you are looking for

driver.findElements(By.cssSelector("span[data-automation-id='SEL-ERR']")).size() != 0;

For setting the Bean value in struts-config.xml we should use the form-beans tag.The form-beans tag might contain any number of bean property defined within form-bean as below.

Defining a Simple Bean Property

<form-beans>
 <form-bean name="userBean" type="org.apache.struts.action.DynaActionForm">
   <form-property name="userName" initial="This is Bean Value" type="java.lang.String" />	
 </form-bean>
</form-beans>

In the above code I am creating a userBean and setting its value is initialized to This is Bean Value.

Now in the action mapping part of the struts-config.xml I am going to map the above created bean to path as said below

<action-mappings>
 <action path="/showBeanValue" type="org.apache.struts.actions.ForwardAction" parameter="/showBeanValue.jsp"/>				
 <action name="userBean" path="/Login" />		
</action-mappings>

In the first line I am defining action path as showBeanValue and it is going to forward to page showBeanValue.jsp when some one access the showBeanValue.do in url.

In the second statement I am creating a dummy form since the the html form action should not be empty.

 
  <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
  <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>     
  <html:form action="/Login">
    <bean:write name="userBean" property="userName"></bean:write>
    <bean:write name="userBean" property="userAge"></bean:write>
  </html:form>