Filters are helpful in performing filter functionality in Java web application Application. A filter implements the javax.servlet.Filter interface. The primary filter functionality is implemented by the doFilter() method of the filter.

A filter is used to perform a particular task either before or after the actual functionality of a web application is performed. For example, if a request is made for a particular resource such as a Servlet in web application and a filter is used, the filter code may execute and then pass the user on to the Servlet. The filter may run a check before letting the user to the actual page.The filter checks the user permissions to access a particular servlet, and it might send the user to an error page rather than to the requested resource.

Below is a code which shows the filter in web.xml file

web.xml

 <webapp>
  <filter>
    <filter-name>SampleFilter</filter-name>
    <filter-class>com.mugil.filter.TestFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SampleFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  </web-app>

Filter code is java is as below
TestFilter.java

public class TestFilter implements Filter 
{
  public void init(FilterConfig fConfig) throws ServletException 
  {
     System.out.println("Filter Initialized");
  }
  
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException 
  {	
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();
     out.print("Filter Executed");		
     chain.doFilter(request, response);
  }

  public void destroy() 
  {
    System.out.println("Filter Destroyed");
  }
}

The init() method will be executed every time the server starts.The doFilter method is executed every time a Servlet or JSP page is accessed in the context.Filter destroy() method is called when the server is stopped.

context – circumstances that form the setting for an event.For our scenario context represents virtual host within which our web application runs.The environment where the WAR file is deployed.

Below is an Example of File which stores variable in context.xml and is available for the whole application.The context.xml file contains the default Context element used for all web applications in the system.

context.xml

  <Context>      
     <Parameter name="companyName" value="My Company, Incorporated"/>
  </Context>

The same thing can be defined in the web.xml file as below
web.xml

  <context-param>
     <param-name>companyName</param-name>
     <param-value>My Company, Incorporated</param-value>
   </context-param>

To access the context variable in Servlet you can use the following code in doGet() Method as below
Test.java

 
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
  ServletContext servletContext = getServletContext();		  
  PrintWriter out = response.getWriter();
  out.print(servletContext.getInitParameter("companyName"));  
}

Case1: The context variable in web.xml will have highest priority than context.xml in server and application if override attribute is set to true or if it is undefined.

Case2: Defining a context variable in $CATALINA_BASE/conf/context.xml and context.xml file inside your application the former will have more privilege.

Declaring context attributes in web.xml is better since they will work when you deploy your app in other App Servers other than Tomcat.

What is Context Path
A web applications context path is the directory that contains the web applications WEB-INF directory.It points to WebContent directory in your project.

Server context path is the one which tells the location where the WebContent directory is placed during project deployment in server.The following code tells you how to find server context path.

Test.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
{	
   ServletContext servletContext = getServletContext();		
   String contextPath = servletContext.getRealPath(File.separator);
   PrintWriter out = response.getWriter();
   out.println("<br/>Context path: " + contextPath);
}  

The above code outputs some directory within tomcat folder like one below
Output

Context path:  D:\Tomcat\wtpwebapps\CustomTag\ 

In my case D:\Tomcat\ is where my tomcat is installed and wtpwebapps\ is the context where my project
\CustomTag\ is deployed

CustomTags.java
This is the File which defines the Property of the Tag

package com.mugil.custTags;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class CustomTags extends TagSupport  
{
  private static final long serialVersionUID = 1L;
	
  public int doStartTag() throws JspException 
  {		
     StringBuffer SamBuffer = new StringBuffer();
     SamBuffer.append("Sample Message");
		
     try
     {
	pageContext.getOut().write(SamBuffer.toString());
     }
     catch (IOException e)
     {
	e.printStackTrace();
     }
		
  	return EVAL_PAGE;
   }
	
   public int doEndTag() throws JspException 
   {
      return EVAL_PAGE;
   }
}

DisplayName.tld
This xml file creates the Relation between the tag and the property of the tag as defined in the java file.

<?xml version="1.0" encoding="UTF-8"?>
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <shortname>Example TLD</shortname>
  <tag>
    <name>Hello</name>
    <tagclass>com.mugil.custTags.CustomTags</tagclass>
    <bodycontent>empty</bodycontent>
  </tag>
</taglib>

Sample.jsp
JSP File in which the custom tag is Used.

<%@taglib prefix="DisplayName" uri="/WEB-INF/tld/DisplayName.tld"%>
.
.
.
.
<body>
 <h1>
    <DisplayName:Hello/>
 </h1>
</body>
.
.
.

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
  <web-app version="3.0">
   <servlet>
     <servlet-name>TestServlet</servlet-name>
     <servlet-class>com.mugil.custTags.TestServlet</servlet-class>
   </servlet>
   <servlet-mapping>
     <servlet-name>TestServlet</servlet-name>
     <url-pattern>/TestServlet/</url-pattern>
   </servlet-mapping>
  </web-app>

Output

OP

c:forEach

 <body>
   <c:forEach var="i" begin="1" end="100">
     <c:out value="${i}"/><br/>
   </c:forEach>
 </body>

Accessing Value in Bean
SampleMenu.java(bean)

  public class SampleMenu
  {
    String name;
  
    public String getName()
    {
      return name;
    }
	
    public void setName(String name)
    {
      this.name = name;
    }
  }

MenuList.java

   List<SampleMenu> arrMenuList = new ArrayList<SampleMenu>();		
   SampleMenu objSampleMenu     = new SampleMenu();

   objSampleMenu.setName("Link1");
   arrMenuList.add(objSampleMenu); 

   objSampleMenu.setName("Link2");
   arrMenuList.add(objSampleMenu);

   objSampleMenu.setName("Link3");
   arrMenuList.add(objSampleMenu);

   request.setAttribute("arrMenuList", arrMenuList);
   RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/Sample.jsp");
   dispatcher.forward(request, response);

Sample.java

 
   <body>
     <c:forEach	var="i" items="${arrMenuList}">
	     <c:out value="${i.name}"/>
     </c:forEach>
   </body>

Output
Link1 Link2 Link3

If Else

 
<c:if test="${user.userGender eq 1}">Male</c:if>
<c:if test="${user.userGender eq 0}">Female</c:if>

(or)

 
  <c:choose>
    <c:when test="${user.userGender eq 1}">Male</c:when>
    <c:otherwise>Female</c:otherwise>
  </c:choose>

Alternative to If Else Statement

 
 <c:out value="${user.userGender eq 1 ? 'Male': 'Female'}"/>

If Else If

<c:choose>
    <c:when test="${empty example1}"> 
        <!-- do stuff -->
    </c:when> 
    <c:otherwise> 
        <c:choose>
            <c:when test="${empty example2}"> 
                <!-- do different stuff -->
            </c:when> 
            <c:otherwise> 
                <!-- do default stuff -->
            </c:otherwise>
        </c:choose>
    </c:otherwise> 
</c:choose>

If Else If

<c:choose>
    <c:when test="${empty example1}">
    </c:when>
    <c:when test="${empty example2}">
    </c:when>
    <c:otherwise>
    </c:otherwise>              
</c:choose>

Passing a Variable from Java to JSP Page By SetAttribute

Sample.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
  request.setAttribute("Name", "Mugil Vannan");
  RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/Sample.jsp");
  dispatcher.forward(request, response);
}

Sample.jsp

  <body>
    <c:out value="${Name}"/>
  </body>

Web.xml

  <servlet>
     <servlet-name>Sample</servlet-name>
     <servlet-class>com.sponsor.infonovum.MenuList</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>Sample</servlet-name>
     <url-pattern>/Sample/</url-pattern>
  </servlet-mapping>

How to remove last element in a array and store it in same Array

 
import java.util.Arrays;

public class SimpleArray 
{
  public static void main(String[] args) 
  {
    String[] arrNames1 = {"Mugil", "Mani", "Vinu", "Shivaji", "Raman"};
    String[] arrNames2 = new String[arrNames1.length-1]; 
		
    for(int i=0;i<arrNames1.length-1;i++)
      arrNames2[i] = arrNames1[i];
		
    arrNames1 = arrNames2.clone();
		
    for (int i = 0; i < arrNames1.length; i++) 
      System.out.println(arrNames1[i]);		
  }
}

Equity financing – from fund raiser point of view
Money without the hassle of repayment or interest.

Advantages to equity financing:

  • Its less risky than a loan because you dont have to pay it back, and its a good option if you cant afford to take on debt.You tap into the investors network, which may add more credibility to your business.
  • Investors take a long-term view, and most don’t expect a return on their investment immediately.
  • You wont have to channel profits into loan repayment.
  • You will have more cash on hand for expanding the business.
  • There’s no requirement to pay back the investment if the business fails.

Disadvantages to equity financing:

  • It may require returns that could be more than the rate you would pay for a bank loan.
  • The investor will require some ownership of your company and a percentage of the profits. You may not want to give up this kind of control.
  • You will have to consult with investors before making big (or even routine) decisions — and you may disagree with your investors.
  • In the case of irreconcilable disagreements with investors, you may need to cash in your portion of the business and allow the investors to run the company without you.
  • It takes time and effort to find the right investor for your company.

Debt financing
Advantages to debt financing:

  • The bank or lending institution (such as the Small Business Administration) has no say in the way you run your company and does not have any ownership in your business.
  • The business relationship ends once the money is paid back.
  • The interest on the loan is tax deductible.
  • Loans can be short term or long term.
  • Principal and interest are known figures you can plan in a budget (provided that you don’t take a variable rate loan).

Disadvantages to debt financing:

  • Money must paid back within a fixed amount of time.
  • If you rely too much on debt and have cash flow problems, you will have trouble paying the loan back.
  • If you carry too much debt you will be seen as “high risk” by potential investors – which will limit your ability to raise capital by equity financing in the future.
  • Debt financing can leave the business vulnerable during hard times when sales take a dip.
  • Debt can make it difficult for a business to grow because of the high cost of repaying the loan.
  • Assets of the business can be held as collateral to the lender. And the owner of the company is often required to personally guarantee repayment of the loan.

Bonds
Businesses often need loans to fund operations, move into new markets, innovate and grow in general. But the amount they need often surpasses what a bank can provide. So another useful way for corporations to raise the necessary funds is to issue bonds to whoever wants to buy them.

When you buy a bond, you’re lending money to the organization that issues it. The company, in return, promises to pay interest payments to you for the length of the loan. How much and how often you get paid interest depends on the terms of the bond. The interest rate, also called the coupon, is typically higher with long-term bonds

F­or you, the lender, a bond is a kind of investment, like a stock. The difference is that stocks aren’t loans. Rather, stocks represent partial ownership in a company, and the returns represent a share in profits. For that reason, stocks are riskier and more volatile — they closely reflect the success of a company. Bonds, on the other hand, often have a fixed interest rate. Some bonds, however, are floating-rate bonds, meaning their interest rates adjust depending on market conditions.Like stocks, bonds can be traded. When someone sells a bond at a price lower than the face value, it’s said to be selling at a discount. If sold at a price higher than the face value, it’s selling at a premium.

Alternative investment
Investments other than Stocks, Bonds and Equity comes under alternative investments.

It includes tangible assets such as precious metals, art, wine, antiques, coins, or stamps and some financial assets such as commodities, private equity, hedge funds, carbon credits, venture capital, forests/timber, film production and financial derivatives.

Difficult to predict the actual cost since it primarily lack a good quality data.They are relatively illiquid. It is very hard to determine its current market value

Dividend
Corporations may pay out part of their earnings as dividends to you and other shareholders as a return on your investment. Share dividends, which are generally paid yearly, are in the form of cash.

Dividend is always calculated on this face value.

Suppose you own 100 shares of XYZ bank. The face value of shares is Rs 10 each. Then the Total face nominal value of your holding is Rs 1000. (This is independent of the purchase value of the shares).

If the dividend declared is 110%, it is calculated on the face value of shares. For example, you will get a dividend of 1100 on your shares. That means, the dividend per share is Rs 11.

Dividend payout ratio
You can calculate a dividend payout ratio by dividing the dividend a company pays per share by the company’s earnings per share.

Dividend yield
If you own dividend-paying shares, you figure the current dividend yield on your investment by dividing the dividend being paid on each share by the share’s current market price. Dividend yield, which increases as the price per share drops and drops as the share price increases, does not tell you what you’re earning based on your original investment or the income you can expect to earn in the future. However, some investors seeking current income or following a particular investment strategy look for high-yielding shares.

How to Calculate Dividend Yield?
Not all of the tools of fundamental analysis work for every investor on every stock. If you are a value investor or looking for dividend income then there are a couple of measurements that are specific to you. For dividend investors, one of the telling metrics is Dividend Yield.

This measurement tells you what percentage return a company pays out to shareholders in the form of dividends. Older, well-established companies tend to payout a higher percentage then do younger companies and their dividend history can be more consistent.

You calculate the Dividend Yield by taking the annual dividend per share and divide by the stock’s price.

Dividend Yield = Annual dividend per share / Stock’s price per share

For example, if a company’s annual dividend is Rs. 1.50 and the stock trades at Rs. 25, the Dividend Yield is 6%. (Rs. 1.50 / Rs. 25 = 0.06)

Dividend usually declared by the companies in % terms to the face value of the share. For Example, Company trading at Rs. 50 with a face value of Rs. 10 per share declares 10% dividend. That means company will pay dividend of Rs. 1 per share to its share holders. Hence in such a case, Dividend Yield is 2% (Rs. 1 / Rs. 50 = 0.02)

The below examples are specific to Junit4

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

Basic Test case which Fails

import static org.junit.Assert.*;
import org.junit.Test;

public class Junit1 {	
 @Test
 public void basicTestFail()
 {
  fail("The Test Failed");
 }
}

There is No pass method in JUnit like fail method.

As long as the test doesn’t throw an exception, it passes, unless your @Test annotation specifies an expected exception. I suppose a pass() could throw a special exception that JUnit always interprets as passing, so as to short circuit the test, but that would go against the usual design of tests (i.e. assume success and only fail if an assertion fails) and, if people got the idea that it was preferable to use pass(), it would significantly slow down a large suite of passing tests (due to the overhead of exception creation). Failing tests should not be the norm, so it’s not a big deal if they have that overhead.

Tests to verify the correctness of a program’s behavior.Verifying the correctness of a program’s behaviour by inspecting the content of output statements.Its looking manually for abnormal output.

Example1

StringHelper.java

package com.mugil.junit.tutor;

public class StringHelper
{	
	public static void main(String[] args)
	{
		StringHelper objStringHelper = new StringHelper();
		System.out.println(objStringHelper.wordATrimmer("PABBB"));
	}
	
	public String wordATrimmer(String pWord)
	{
  	   String pTempString = pWord.substring(0, 2);			   
           if(pTempString.contains("A")) return pWord.replace("A", "");		
 	   pTempString = pWord.substring(2);		
	   return pWord;
	}
}

StringHelperTest.java

package com.mugil.junit.tutor;

import static org.junit.Assert.*;
import org.junit.Test;

public class StringHelperTest 
{
	@Test
	public void test() 
        {
		StringHelper objStringHelper = new StringHelper();
		String expectedOP            = "MMG";
		String actOP                 = objStringHelper.wordATrimmer("AAMMG");
		
		assertEquals(expectedOP, actOP);
	}
}

@Test comes from org.junit.Test Package
assertEquals – helps in performing String, Boolean and Other Comparison.

As you have seen above StringHelper.java is the actual file that has the function.StringHelperTest.java is the file in which test of the functionality is to be carried out. This java file is created in a new source folder test. By using the assert equals method we are comparing whether the expected Op and actual OP are the same.

@Test annotation at the top of the test method tells the JVM to run this method

assertTrue(boolean)
assertTrue(boolean true) will return true
assertFalse(boolean false) will return true

To make sure the code is behaving the right way we can use asserttrue() and assertfalse() methods.
StringHelper.java

package com.mugil.junit.tutor;

public class StringHelper
{	
	public boolean areFirstTwoandLastTwoStringsSame(String Name)
	{
		if(Name.length() <  2) return false;		
		if(Name.length() == 2) return true;
		
		String firstChars = Name.substring(0, 2);
		String lastChars  = Name.substring(Name.length()-2);
		
		if(firstChars == lastChars)
		  return true;
		else
		  return false;
	}
}

StringHelperTest.java

 package com.mugil.junit.tutor;

import static org.junit.Assert.*;
import org.junit.Test;

public class StringHelperTest 
{
  @Test
  public void test() 
  {
    StringHelper objStringHelper = new StringHelper();
    assertTrue(objStringHelper.areFirstTwoandLastTwoStringsSame("AB"));
    assertFalse(objStringHelper.areFirstTwoandLastTwoStringsSame("ABAB"));
  }
}

The above code checks whether First and Last two characters are the same and return true or false based on input to method areFirstTwoandLastTwoStringsSame.

@Before and @After Annotations
The before and after methods are used to run a case before and after the actual test started.

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class StringHelperTest 
{
	
  @Before
  public void before()
  {	
    System.out.println("Before Test");
  }
	
  @After
  public void after()
  {	
    System.out.println("After Test");
  }

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

The output of the above code would be
Output

Before Test
Test1
After Test
Before Test
Test2
After Test

You can also run a test before and after the class run as below

import org.junit.AfterClass;
import org.junit.BeforeClass;

@BeforeClass
public static void beforeClass()
{	
  System.out.println("Before Test");
}
	
@AfterClass
public static void afterClass()
{	
  System.out.println("After Test");
}

@Test
public void test1() 
{
  StringHelper objStringHelper = new StringHelper(); 
  System.out.println("During Test");
}

Output

Before Test
During Test
After Test

BeforeClass and AfterClass is run only once when object for class is created.Note the static before beforeClass and afterClass methods.

Typical Example for Using before and after methods where object for class created in before method and object assigned null in after method.

public class StringHelperTest 
{	
  StringHelper objStringHelper1;
	
  @Before
  public void before()
  {	
     objStringHelper1 = new StringHelper(); 
  }
	
  @After
  public void afterClass()
  {	
    objStringHelper1 = null;
  }

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

How to check expected array is returned in Output

 
import static org.junit.Assert.*;
import org.junit.Test;

public class StringHelperTest 
{
  @Test
  public void test1() 
  {
    int[] arrNums1 = {5,4,3,2,1};
    Arrays.sort(arrNums1);		
    int[] arrNums2 = {1,2,3,4,5};
		
    assertArrayEquals(arrNums1, arrNums2);
  }
}

assertArrayEquals method comes from org.junit.Assert Package

We are going to look for the expected exception is getting thrown or not

Testing for Exception

import java.util.Arrays;
import org.junit.Test;

public class StringHelperTest 
{
  @Test(expected=NullPointerException.class)
  public void test1() 
  {
    int[] arrNums1 = null;
    Arrays.sort(arrNums1);
  }
}

Testing for Performance – How Much time is taken by code block to execute the code.

In the below code we are going to estimate actual time taken by the code block to execute

 public class StringHelperTest 
 {
   @Test(timeout=100)
   public void test1() 
   {
     for (int i = 0; i < 1000000; i++) 
     {
	    int[] arrNumbs = {i-1, i, i+1};
          Arrays.sort(arrNumbs);
     }
   }
}

timeout=100 – is going to tell the code should complete the execution within 100 milliseconds.If it fails I should optimize the code by performance tweaks to boost codes performance.

When ever you deploy website into web server or application server you need to wrap it into WAR file rather than copying files as folder.

Below we will see how to deploy war file into tomcat server.There are two ways to do that.

Method 1
1.You need to export your project as war file.
2.now copy the war file to the tomcat folder.In my case D:\tomcat7\webapps\.
3.After copying the war file to webapps folder you should restart your server to make the folder dispatched in the webapps folder.
4.Now our final step is to make sure what ever we have done in working by typing the local url in browser say if i have copied a war file by name Acme.war I should able to access the folders in project by name http://localhost:8081/Acme/

Method 2
1.In this method you I will use Tomcat manager to deploy the WAR file.
2.If you have used tomcat binary version you need to configure tomcat manager user name and password
as below

  1. Open D:\tomcat7\conf\tomcat-users.xml
  2. Add the below entries in tomcat-users.xml
  3. Now the tomcat manager username and password is set to admin and secret

3.We are ready to go and access the tomcat manager now.

tomcat-users.xml

  <role rolename="manager-gui"/>
  <role rolename="manager-status"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
<user username="tomcat" password="secret" roles="manager-gui,manager-status,manager-script,manager-jmx"/> 

You can see the following browse for WAR option under Deploy Tab

War image

You need to browse for the war file and restart the server.

Posted in WAR.

How to Run a Java file from ANT Script

 <java classname="com.mugil.tutor.Sample">
   <classpath path="test/classes/"></classpath>
 </java>

Where Sample points to Sample.class which we got through compilation and test/classes/ contains the Sample.class file. Below is the whole code in build.xml file

<project name="ANT2" default="copyTarget">
  <target name="copyTarget">
  <mkdir dir="test/classes/"/>
  <javac srcdir="src/com/mugil/tutor/" destdir="test/classes/" includeantruntime="false"></javac>
    <java classname="com.mugil.tutor.Sample">
  	<classpath path="test/classes/"></classpath>
     </java>
   </target>
</project>

How to get Current time in ANT Script

 <project name="default" default="target1">
     <target name="target1">		
	<tstamp>
	   <format property="current.time" pattern="yyyyMMdd" />
	   <format property="archive.name" pattern="'MyArchive_'yyyyMMdd_hh:mmaa'.jar'" />
	</tstamp>
	<echo>${current.time}</echo>
	<echo>${archive.name}</echo>		
     </target>
</project>

ANT Script to concatenate two variables and Create directory based on that

<project name="default" default="target1">
  <property name="mugil.dir" value="D:/Mugilvannan/"/>		
     <target name="target1">		
	<tstamp>
	  <format property="current.time" pattern="yyyyMMdd" />
	  <format property="archive.name" pattern="'MyArchive_'yyyyMMdd_hhmmaa" />
	</tstamp>
	<property name="whole.dir" value="${mugil.dir}${archive.name}"/>
	  <echo>
	    ${whole.dir}
	  </echo>		
	<mkdir dir="${whole.dir}"></mkdir>
     </target>
</project>
Posted in ANT.