Posted by: rajnautiyal | June 10, 2009

Create Filters in Java

Filter is basically a component that is invoked when a client request a resource that the Filter is mapped to, such as a URL pattern or a Servlet name. Normally, a filter is used to wrap and manipulate Request, Response or header values before or after the execution of the original request target and do not itself return any response to the client.

Filters can be configured to act upon a certain request or upon different requests. Filters can also be put into a chain, where a number of Filters can be invoked after each other. Any Filter taking part of such a chain can at any time give control to the next Filter or redirect the request out of the chain .

Method for creating the filter

public void doFilter(final ServletRequest request, final ServletResponse response, FilterChain chain)

The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain.

public void init(FilterConfig filterConfig)

Called by the web container to indicate to a filter that it is being placed into service. The servlet container calls the init method exactly once after instantiating the filter. The init method must complete successfully before the filter is asked to do any filtering work.
public void destroy()

Called by the web container to indicate to a filter that it is being taken out of service. This method is only called once all threads within the filter’s doFilter method have exited or after a timeout period has passed. After the web container calls this method, it will not call the doFilter method again on this instance of the filter.

For creating your own  filter you have to  map  your filter in  web.xml

<filter>
		<!-- controls access for administrators' resources -->
		<filter-name>AdminAccessFilter</filter-name>
		<filter class>foo.bar.filter.AccessControlFilter</filter-class>
	</filter>

	<filter-mapping
		<filter-name>AdminAccessFilter</filter-name>
		<url-pattern>/admin/*</url-pattern>
	</filter-mapping>

	<filter-mapping>
		<filter-name>AdminAccessFilter</filter-name>
		<url-pattern>/admin/</url-pattern>
	</filter-mapping>

after mapping create a filter class for e.g

package foo.bar.filter;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import foo.bar.model.Admin;

/**
 * Servlet Filter to attach the user under <code>USER_KEY</code> (session) to the current
 * execution thread.
 */
   public class AccessControlFilter implements Filter {

	private static Logger log = Logger.getLogger(AccessControlFilter.class.getName());
	private FilterConfig filterConfig;
        private static final String LOGIN_PAGE = "/admin/adminlogin.action";
	private static final String INTERCEPTION_PREFIX = "/admin/";
	public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException,       ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		String servletPath = request.getServletPath();
		if (! servletPath.startsWith(INTERCEPTION_PREFIX)) {
			HttpSession httpSession = request.getSession();
			Admin user = (Admin) httpSession.getAttribute("Adminuser");
			if (user == null) {
			 	RequestDispatcher dispatcher = request.getRequestDispatcher(LOGIN_PAGE);
				dispatcher.forward(request, (HttpServletResponse) res);
				return;
			}
		}
		chain.doFilter(req, res);
	return;
   }

   public void init(FilterConfig config)
    {
        this.filterConfig = config;
    }

   public void destroy()
    {
        this.filterConfig = null;
    }

    public FilterConfig getFilterConfig()
    {
        return filterConfig;
    }

}
Posted by: rajnautiyal | May 4, 2009

Thickbox z-index of Flash Objects

I had an issue with thickbox where it would show the image behind a flash video in FireFox.I found really intersenting solution on this .I wanted to blog this  information for my own record , plus to help ‘index’ the solution for others.

Solution

    1. Wrap your flash content in a div
    2. Add <param name=”wmode” value=”transparent”> to your object tag
    3. Set wmode=”transparent” in the embed tag
    4. Use css to set the position and z-index for your div (don’t set negative z-index values as it will make your flash disappear)

The CSS

#flash {
position: relative; /*or absolute*/
z-index: 0;
}

The XHTML

<div id=”flash”>
<object …>
<param name=”wmode” value=”transparent”>
<embed … wmode=”transparent”>
</object>
</div>

Create charts and Graph to your web Application Using Cewolf and Jfree API

Cewolf is based on Jfree and uses it’s rendering engine to render the final chart image into the clients response stream. No files are created on server side. Everything is based on lightweight session objects and dynamic data analysis. Cewolf consists of one servlet which handles the chart rendering and a taglibrary which translates the chart definition included in the JSP into an HTML img tag which consults the rendering servlet for retrieval of the appropriate chart.

How to Create Graph using Cewolf

For creating graph using cewolf  Api download cewolf  from http://cewolf.sourceforge.net/new/index.html after downloading  the cewolf   add the cewolf  libraies in your lib folder and  give the servlet  mapping on your web.xml file

<servlet><servlet-name>CewolfServlet</servlet-name>

<servlet-class>de.laures.cewolf.CewolfRenderer</servlet-class>

<init-param>
<param-name>storage</param-name>
<param-value>de.laures.cewolf.storage.TransientSessionStorage</param-value>

</init-param>

<!-- turn on or off debugging logging -->

<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>

</init-param>

</servlet>

After servlet mapping you can use cewolf  tag  in the jsp . For using the cewolf  api you  have to create dataset using jfree chart .(Below is the example of the how to create dataset using Jfree chart ). You can use different – different dataset according to the your need   http://www.jfree.org/jfreechart/api/javadoc/index.html

package foo.bar.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.data.category.DefaultCategoryDataset;
import java.io.Serializable;
import de.laures.cewolf.DatasetProduceException;
import de.laures.cewolf.DatasetProducer;

public class  ProduceData implements DatasetProducer, Serializable {
private static final Log log = LogFactory
public ProduceData () {
}

public Object produceDataset(Map params) throws DatasetProduceException {
DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();
defaultcategorydataset.addValue(1, "a", "12-3-05");
defaultcategorydataset.addValue(5, "a", "13-3-05");
defaultcategorydataset.addValue(8, "a", "14-3-05");
defaultcategorydataset.addValue(4, "a", "12-3-05");
defaultcategorydataset.addValue(6, "b", "13-3-05");
defaultcategorydataset.addValue(9, "b", "14-3-05");
defaultcategorydataset.addValue(1, "b", "12-3-05");
defaultcategorydataset.addValue(12, "c", "13-3-05");
defaultcategorydataset.addValue(13, "c", "14-3-05");
defaultcategorydataset.addValue(4, "c", "12-3-05");
return defaultcategorydataset;
}
}

After creating the dataSet object for eg.(ProduceData  produceData=new ProduceData (); ) pass the object to  your jsp and use that dataset ( produceData  object ) inside cewolf  tag.Below is the example how to use  dataset inside the jsp

<%@ include file=”/common/taglibs.jsp” %>
<%@ taglib uri=’/WEB-INF/cewolf.tld’ prefix=’cewolf’ %>
<c:if test=”${produceData ne null}”>
<cewolf:chart id=”scatter” title=”" type=”line” xaxislabel=”" yaxislabel=”Rating” showlegend=”true”>
<cewolf:data>
<cewolf:producer id=”produceData “/>
</cewolf:data>
</cewolf:chart>
<div>
<cewolf:img chartid=”scatter” renderer=”cewolf” width=”900″ height=”300″/>
</div>
</c:if>
<c:if test=”${produceData eq null}”>
<div>
No data found
</div>
</c:if>

By this way the graph or chart  is rendered on your jsp .But  If you want any graphic on your chart such as your want to change the background color , dotted line in the graphs , stroke points in  lines such as triangle ,curicular etc for all these things you have to write chartpostprocessor . Below is the example how to write chartpostprocessor and how to use chartpostprocessor inside the cewolf  tag .

Create a  chartpostprocessor class using Jfree api  for example :

package com.foo.util;
import java.awt.*;
package foo.bar.util
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.Range;

public class  MyChartPostProcessor implements ChartPostProcessor {

public void processChart(java.lang.Object object, java.util.Map map) {

JFreeChart jfreechart = (JFreeChart) object;
jfreechart.setBackgroundPaint(Color.white);

CategoryPlot categoryplot = (CategoryPlot) jfreechart.getPlot();
categoryplot.setBackgroundPaint(Color.white);
categoryplot.setRangeGridlinePaint(Color.lightGray);

NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();

Range range = new Range(0, 11);
numberaxis.setRange(range, false, true);

final CategoryPlot plot = (CategoryPlot) jfreechart.getPlot();

final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();

rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
rangeAxis.setAutoRangeIncludesZero(true);

final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();

renderer.setSeriesStroke(
0, new BasicStroke(
2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[] {10.0f, 6.0f}, 0.0f
)
);

renderer.setSeriesStroke(
1, new BasicStroke(
2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[] {6.0f, 6.0f}, 0.0f
)
);

// rotate x-axis label by 90degrees

CategoryAxis domainAxis = categoryplot.getDomainAxis();
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 2.0));
}
}

Now create a object of  your  chartpostprocessor in your jsp and use that object inside the cewolf  tag for example

<%@ include file=”/common/taglibs.jsp” %>
<%@ taglib uri=’/WEB-INF/cewolf.tld’ prefix=’cewolf’ %>
<c:if test=”${produceData ne null}”>
<jsp:useBean id=”postproducer” class=”foo.bar.util.MyChartPostProcessor “/>

<cewolf:chart id=”scatter” title=”" type=”line” xaxislabel=”" yaxislabel=”Rating” showlegend=”true”>
<cewolf:data>
<cewolf:producer id=”produceData “/>
</cewolf:data>
<cewolf:chartpostprocessor id=”postproducer“/>
</cewolf:chart>
<div>
<cewolf:img chartid=”scatter” renderer=”cewolf” width=”900″ height=”300″/>
</div>
</c:if>
<c:if test=”${produceData eq null}”>
<div>
No data found
</div>
</c:if>

By using the chartpostprocessor you can make your chart or graph more attractive .

Free Flash Graph Or Chart – Create Graph Using Fusion Chart (http://www.fusioncharts.com/free/)

FusionCharts Free is a flash charting component that can be used to render data-driven & animated charts for your web applications and presentations.

It is a cross-browser and cross-platform solution that can be used with PHP, Python, Ruby on Rails, ASP, ASP.NET, JSP, ColdFusion, simple HTML pages or even PowerPoint Presentations to deliver interactive and powerful flash charts.

How to Create Chart  Using Fusion Chart

Chart creating using fusion free is very easier . You have only create a xml of your data and includue FusionChartsHTMLRenderer.jsp , and swf file (according to the type of graph you need which is inside the \FusionChartsFree\Charts folder ) in your jsp . It automatically generate  flash chart in your jsp.

Here is the example how to fusion chart in the jsp

<%@ page import=”foo.bar.model.RatingGraph” %>
<%@ page import=”java.util.List” %>
<%@ include file=”/common/taglibs.jsp” %>
<%

String strXML = “”;
strXML += “<graph caption=” xAxisName=” yAxisName=” decimalPrecision=’0′ formatNumberScale=’0′ chartRightMargin=’30′>”;
strXML += “<set name=’” One “‘ value=’” 1 “‘ hoverText=’one’/>”;
strXML += “<set name=’” two “‘ value=’” 2 “‘ hoverText=’one’/>”;
strXML += “<set name=’” three”‘ value=’” 3 “‘ hoverText=’one’/>”;
strXML += “<set name=’” four”‘ value=’” 4 “‘ hoverText=’one’/>”;
strXML += “</graph>”;
}
%>

<jsp:include page=”/includes/FusionChartsHTMLRenderer.jsp” flush=”true”>
<jsp:param name=”chartSWF” value=”/flash/FusionCharts/FCF_Bar2D.swf”/>
<jsp:param name=”strURL” value=”"/>
<jsp:param name=”strXML” value=”<%=strXML%>”/>
<jsp:param name=”chartId” value=”myNext”/>
<jsp:param name=”chartWidth” value=”200″/>
<jsp:param name=”chartHeight” value=”150″/>
<jsp:param name=”debugMode” value=”false”/>
</jsp:include>

Fusion chart look more attractive and cool .

Posted by: rajnautiyal | April 23, 2009

Create your own custom tag for Jsp:Using tag file

What are JSP tags?

Well, if you know HTML, XML etc then you know what are tags. In any tag based language ( e.g. HTML ) anything between ‘<’ and ‘>’ is a tag e.g. <title> is a title tag. These HTML tags are used on the client side in the browser to format the display of data on the user screen. Likewise in JSP we have tags between ‘<’ and ‘>’ and you can do just about anything you can think of on the server-side with them e.g. <star:firsttag />.

One distinction between HTML and JSP tags is that all JSP tags obey XML tag rules. Meaning there by, all starting tags must have an end tag e.g. <star:firsttag> </star:firsttag>. If there is no end tag, then you should put ‘/’ before the > tag e.g. <star:firsttag />.

One other thing to notice is that all JSP tags have a prefix e.g. ’star’ in <star:firsttag /> tag.

Like HTML and XML tags, JSP tags can have attributes e.g. <star:firsttag attrib1=”value1″ attrib2=”value2″ /> has two attributes with two values.

Why build and use JSP tags?

Following are some of the uses which to mind :

  • Tags allow separation of Java ( server-side ) and HTML ( client-side ) code. Very important when you are building big projects and have separate people for client and server-side development.
  • Tags allow easy reuse of Java code.
  • You can build and pack a custom tag library with useful functions and provide it to the end-user.
  • Due to their ease of use tags can be used by non-Java programmers e.g. HTML developers.
  • Tags are easier to maintain. You don’t have to edit every JSP page when you want to make a change, just change the JSP tag and change will be manifested by all the JSP pages.

These were only the few important uses which come to mind immediately. Only once you learn how to build JSP tags, you’ll realize how important JSP tags can be.

How to create your own custom tag for jsp

Suppose We have to create tag for the country list for that first we have to create a folder tag  and inside that create a file called countryList.tag. Inside that file write your own code using following convention

<%@ tag %>
<%@ tag import=” foo.bar.AppContext” %>
<%@ tag import=” foo.bar.service.SchoolManager” %>
<%@ tag import=”java.util.List” %>
<%@ tag import=”foo.bar.model.School” %>
<%@ attribute name=”id” required=”true” rtexprvalue=”true” %>
<%
SchoolManager schoolManager = (SchoolManager) AppContext.getBean(“schoolManager”);
List<School> schoolList = schoolManager.getAllSchool();
jspContext.setAttribute(id, schoolList, PageContext.REQUEST_SCOPE);
%>

The tag folder should be inside the (\web\WEB-INF)

now give a mapping of your tag folder in  your taglibs.jsp (web/commons)

<%@ taglib tagdir=”/WEB-INF/tags” prefix=”mytag” %>

Now we can use our custom tag in the jsp   .This the example how to use the custom tag in the jsp

<mytag:getSchoolList id=”schoolList”/>

Now how to Create custom tag with passing argument

suppose the tag file  name is schoolName inside the tag folder which is mention above

The tag file is like

<%@ tag %><%@ tag import=”foo.bar.AppContext” %><%@ tag import=”foo.bar.util.Util” %><%@ tag import=”java.util.List” %><%@ tag import=”foo.bar.model.Student” %><%@ tag import=”foo.bar.model.Reply” %><%@ tag import=”foo.bar.model.Kudos” %>
<%@ tag import=”foo.bar.service.SchoolManager” %>
<%@ taglib uri=”http://java.sun.com/jstl/core” prefix=”c” %><%@ taglib uri=”http://java.sun.com/jstl/fmt” prefix=”fmt” %><%@ attribute name=”name” required=”true” rtexprvalue=”true” %><%@ attribute name=”value” required=”false” rtexprvalue=”false” %><%

SchoolManager schoolManager = (SchoolManager)AppContext.getBean(“schoolManager”);
String names = jspContext.getAttribute(name, PageContext.REQUEST_SCOPE).toString();
String schoolState = schoolManager.getState(names);
if(schoolState != null && !schoolState.equals(“”))
out.println(schoolState);
else
out.println(“”);
%>

here we are passing name in  the tag

In the jsp we can use the tag like :

<mytag:schoolName name=”name”></mytag:schoolName>
Posted by: rajnautiyal | February 9, 2009

Upload files more than 2097152 bytes in Strut2.0

Struts 2 utilizes the service of File Upload Interceptor to add the support for uploading files in the Struts applications. The Struts 2 File Upload Interceptor is based on MultiPartRequestWrapper, which is automatically applied to the request if it contains the file element. Then it adds the following parameters to the request (assuming the uploaded file name is MyFile). But when I am uploading a file more than 2 mb I am getting 

Unable to load bean org.apache.struts2.dispatcher.multipart.MultiPartRequest (jakarta) -Error

When I am trying to reslove this problem I got two interesting solution of this problem 

 

  1. write struts.multipart.maxSize=6092328  line in the strut.properties file which override the default size (2 MB)
  2. write  <interceptor-ref name=”fileUpload”>
                   <param name=”maximumSize” >1024</param>
                   <param name=”allowedTypes”>image/png,image/gif,image/jpeg,image/jpg</param>
           </interceptor-ref>
      lines inside of your action definition in your struts.xml. 

Categories