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>

load-on-startup is a tag element which appear inside servlet tag in web.xml.load-on-startup tells the web container about loading of a particular servlet. if you don’t specify load-on-startup then container will load a particular servlet when it feels necessary most likely when first request for that servlet will come, this may lead to longer response time for that query if Servlet is making database connection which contribute network latency or time consuming job.

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

Points to remember

  • If load-on-startup value is same for two servlet than they will be loaded in an order on which they are declared inside web.xml file.
  • If load-on-startup is 0 or negative integer than Servlet will be loaded when Container feels to load them.
  • load-on-startup guarantees loading, initialization and call to init() method of servlet by web container.
  • If there is no load-on-startup element for any servlet than they will be loaded when web container decides to load them.

Lower the value of load-on-startup, servlet will be loaded first.

Use during Connection pool, downloading files or data from network or prepare environment ready for servicing client in terms of initializing cache, clearing pipelines and loading important data in memory

Add the JSTL Library as below

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

Populating a Text Box

  <input name="txtUserName" id="txtUserName" type="text" value='<c:out value="${User.userName}"></c:out>'>

Populating a Dropdown List
Type 1

 <select name="cboAge" id="cboAge">
  <c:forEach begin="20" end="60" var="i">
    <option value="${i}" <c:if test="${i == User.age}">Selected</c:if>>${i}</option>    			
  </c:forEach>
 </select>

Type 2

 <select name="cboLocation" id="cboLocation">
   <option value="Chennai">Chennai</option>
   <option value="Bangalore">Bangalore</option>
   <option value="Mumbai">Mumbai</option>
  </select>

Javascript Code

$('document').ready(function(){
  $('#cboLocation').val('<c:out value="${User.location}"></c:out>');
});

Populating Radio buttons

<input name="rdoGender" type="radio" id="rdoMale" value="1" <c:out value="${User.gender == 1?'checked':''}"></c:out>><label for="rdoMale">Male</label>
<input name="rdoGender" type="radio" id="rdoFemale" value="0" <c:out value="${User.gender == 0?'checked':''}"></c:out>><label for="rdoFemale">Female</label>

Populating Check boxes

 <input name="chkSkills" type="checkbox" id="chkJava" value="Java" <c:if test="${fn:contains(User.skills, 'Java')}">Checked</c:if>><label for="chkJava">Java</label>    	
Posted in JSP.

While storing the HTML code in oracle db the column type should be CLOB rather than BLOB. Incase if you have used BLOB for storing the HTML code while carrying out update you should first convert the content in to hexadecimal values as below.

  SELECT (RAWTOHEX(UTL_RAW.CAST_TO_RAW('Test'))) 
    FROM DUAL;

The above code returns Hexadecimal value for test as below
54657374

Now if you want to update the Hexadecimal you need to do the same thing.

UPDATE TemplateTbl
   SET TemplateConetent = (RAWTOHEX (UTL_RAW.cast_to_raw ('Mugil &nbsp; Nikkhil')))
   WHERE TemplateId = TL2600

The above code seems to be fine but it does not work as the &nbsp; would be interrupted as if a variable prompting you to enter the variable value.

To overcome this issue &nbsp; should be replace with &&nbsp; as below

UPDATE TemplateTbl
   SET TemplateConetent = (RAWTOHEX (UTL_RAW.cast_to_raw ('Mugil &&nbsp; Nikkhil')))
   WHERE TemplateId = TL2600

Cheers. We are Done. :-).

You can create autoincrement column in oracle in two ways.

Method 1 : Using sequence

Table Creation Query

 CREATE TABLE tblusers(UserId INT, UserName VARCHAR(50));

Sequence Creation Query

  CREATE SEQUENCE tblusers_userid_seq 
         MINVALUE 1 MAXVALUE 999999999999999999999999999 
         START WITH 1 INCREMENT BY 1 CACHE 20;

The above code creates a sequence for table tblusers with name tblusers_userid_seq with start value of 1 and limit 999999999999999999999999999.

Insertion Query

  INSERT INTO tblusers(UserId, UserName) VALUES (tblusers_userid_seq.nextVal, 'John')

Method 2 : Using Trigger
In Method 2 we can use triggers to carry out auto increment when rows are added to the table.

Before creating trigger you should make the auto increment column as primary key.For that the code is as below

  ALTER TABLE tblusers ADD (
  CONSTRAINT UserId_pk PRIMARY KEY (UserId));

The Creation of sequence and trigger is as follows

CREATE SEQUENCE tblusers_userid_seq;  
CREATE OR REPLACE TRIGGER tblusers_userid_trigg 
BEFORE INSERT ON tblusers 
FOR EACH ROW
BEGIN
  SELECT tblusers_userid_seq.NEXTVAL
  INTO   :new.UserId
  FROM   dual;
END;

Now during insertion there is no need to worry about the auto increment column and the insert query no need to contain the Id column as below

  INSERT INTO tblusers(UserName) VALUES ('John')