Tuesday, July 31, 2007


Bar[camp] Bangalore

28th July Morning around 9:00 inside IIMB campus me and selva were the 7th and 8th person to register for the BCB4, from there we started waiting after waiting for more than 1/2 hour we went for breakfast in IIMB canteen orgainsed by BCB4 when we came to R-desk, we saw a huge number of people of registeration and we started waiting since its our first barcamp we are don't know anyone over there ..atlast around 11:00 we enetered audi and it was full and intro starts, the count was some where near to 450 to 500, collective leaders told what are the collective about and what's in collective today i was curoius abt BOJUG and selva was intereseted in BOJUG and as well as Ruby but ruby has nothing on the morning it was only on the afternoon so selva decided to sit for BOJUG

After the intro was over we searched for classrooms ....the campus is really huge and kudos to our organizers they have posted diretions all the way to the classrooms.Finally arrived at BOJUG short intro of what's BOJUG and everyone who attened BOJUG. The first presentation is reagrding project woodStock by Venakatesh Babu from Sun, got some hint's since i am working in JSF.Its mainly abt how to use ready made components and enhance your web-app.

After that Java puzzles from BOJUG ...really me and selva tried ........no chance we only able to answer some of the questions you can find the questions HERE..after that lunch break next selva went to Ruby and I am back in BOJUG afternoon peter took a session on Apache wicket he tried to brainwash everybody that wicket is the next big thing ...anyway good try peter ...after that Sathish took session on ICG do not ask what is ICG i am almost sleepy in that session selva joined me at the end of ICG session.In between a guy from Functional Programming Collective came to BIJUG and have some information about scala. Next is very small information about hudson a CI (Continuous integration tool) good features (GUI instead of dying with xml files Cruise Control) There are some places were CC will score and some places Hudson will score.The last for the day was in Audi ....Music from some of the guys (Music Collective) and head to home ....


Next Day we arrived at 9:30 again Registration to take count of the day ...now with shiva and me siging in at 14 & 15. BCB4 day two starts...straight to canteen had breakfast and to Audi Collective leads announcements and speaker also have a very short note on what they are speaking 30 seconds and then back to BOJUG and shiva to AJAX Rohan have hand's on how to built netbeans plugin in 30 seconds but it really took more than 1 hour after that some usefull discussion and one more small presentation on CC. And that's it BOJUG is over ...siva was also back form AJAX went for Lunch and then ...the next session for 3 but there's no BOJUG i need to go to some other collective but it was weekend so we decided to finish the BCB4 there we returned back to our home.

But i thought i should stayed back and attened some of the session which i decided earlier.Any way next time i won't concetrate on BOJUG alone, which ever i find interesting i will attened that's what i am having in my mind ok cool i am waiting for BCB5

Friday, July 27, 2007

Creating Shortcut for Locking WorkStation


I was looking a way to create a shortcut for locking the workstation, XP has windows+l shortcut key, But there is cute way to create the shortcut for locking workstation.Go to your winnt folder, be careful find rundll32.exe and create a shortcut place it in desktop.Now go to the properties of the shortcut which you created before and look in to the target, add the below content to the target after a space from the existing one user32.dll,LockWorkStation,Rename your shortcut to Lock and try to click it.Oops! ....it works



Tuesday, July 24, 2007

Filters for Authentication & Security


In developing web application security is the most important one,for example a web application is running on port number 8080 (default for tomcat) the application name be Sample.For connecting the application we will
the type the following address in the url http://localhost:8080/Sample and then logging inside the application the url changes as you click the pages and navigate inside the app.Try to collect any of the url from the app that your r navigating and and paste in different browser if that particular page is opened then your app needs as security checks.In Java there is cool concept called Filters.

Filters are are application-level Java code components within a J2EE Web application.They can act as gatekeeper's to your web-app checking the logging in credentials, validating from which page request came and the other very useful things

In the web.xml you have to define the filters



<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.filter.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>



In the above mapping whatever request goes to your web-app it is first intercepted by Filter

Filter has ServletRequest and ServletResponse you need it to type cast to HttpServletRequest and HttpServletResponse for getting the username from the request and session. The Logic of the below program is simple.

we are checking whether the request comes from the loginpage if yes the user has entered username in the loginpage so the parameter we are getting using request and checking whether that value is null if it is not null then setting that value to session and leaving the process to application.

If the request is not from the loginpage we are checking whether the username is in session if yes then allow him to go through the app if not throw the user to login page and ask him to enter


Sample Filter Code



public class AuthFilter implements Filter {

private FilterConfig config;

public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
this.config=arg0;
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

/* Type Casting request and response */
HttpSession session = ((HttpServletRequest) request).getSession();
ServletContext context = config.getServletContext();
HttpServletResponse serresponse=(HttpServletResponse)response;
/*
* use the ServletContext.log method to log filter messages
*/
String AUTH_PAGE="/LoginPage.jsp";
String username=null;
String sessusername=null;
String filename=null;
HttpServletRequest serrequest=null;
serrequest=(HttpServletRequest)request;
/* Getting the File Name */
filename=serrequest.getServletPath()+serrequest.getPathInfo();

/* Checking the File Name*/
if(AUTH_PAGE.equals(filename))
{
/* Getting the username from the MainPage */
username=serrequest.getParameter("usernname");
if(username==null)
{
sessusername=(String)session.getAttribute("usernname");
if(sessusername==null&&sessusername.trim().equals(""))
{
serresponse.sendRedirect(serrequest.getContextPath()+AUTH_PAGE);
}
serresponse.sendRedirect(serrequest.getContextPath()+AUTH_PAGE);
}
session.setAttribute("username",username);
chain.doFilter(request, response);
}
else
{ if(session.getAttribute("username")!=null&&!session.getAttribute("username").toString().trim().equals(""))
{
chain.doFilter(request, response);
}
else
{

serresponse.sendRedirect(serrequest.getContextPath()+AUTH_PAGE);
}
}
}

public void destroy() {
}
}

Powered by ScribeFire.

Sunday, July 15, 2007

Reading xml from WEB-INF Directory and Building XML Document

We had a requirement of reading a xml file from the WEB-INF folder of web-app
and to build a xml document from the file, after building the document its very much easy to
parse through the document and get the date.Here are the steps and code-snippets to do it.

Since its a web-app we need to get the ServletContext.


ServletContext context = pageContext.getServletContext();



After getting the context we need get the file as Stream for building xml document


InputStream inputStream=context.getResourceAsStream("/WEB-INF/example.xml");



We have got the inputStream we need a build the xml document.The below DomRead.java
will build the document


Document document = DomReadUtil.parse(inputStream);




public class DomRead
{
public static Document parse(InputStream stream )
{
Document document = null;
// Initiate DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// To get a validating parser
factory.setValidating(false);
// To get one that understands namespaces
factory.setNamespaceAware(true);
try
{
// Get DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// Parse and load into memory the Document
document = builder.parse(stream);
return document;
}
catch (SAXParseException spe)
{
// Error generated by the parser
System.out.println("\n** Parsing error , line " + spe.getLineNumber()
+ ", uri " + spe.getSystemId());
System.out.println(" " + spe.getMessage() );
// Use the contained exception, if any
Exception x = spe;
if (spe.getException() != null)
x = spe.getException();
x.printStackTrace();
}
catch (SAXException sxe)
{
// Error generated during parsing
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
}
catch (ParserConfigurationException pce)
{
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
}
return null;
}
}



Now we got the XMLDocument document we can parse the xml document and get the
information we need.

Note :

The inputStream passing to the DomRead.java should be opened or Read, if so it will give
Premature End Of File - SaxParseException.


ServletContext context = pageContext.getServletContext();
InputStream inputStream=context.getResourceAsStream("/WEB-INF/example.xml");
StringBuffer sb=new StringBuffer();
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
while(br.readLine()!=null)
{
sb.append(br.readLine()+"\n");
}
System.out.println("fpath "+sb.toString());
Document document = DomReadUtil.parse(inputStream);



The above code will give you Premature End Of File - SaxParseException.Because we have opened the inputStream and Read the contents.when trying to build the Doc from the stream,its already read.so there is premature end of file

Tuesday, July 10, 2007


Selecting a particular row in Datatable – JSF

Selecting a particular row in Datatable in a web-app which is developed on JSF,If the requirements is to display data in the datatable with check boxes in every row and user will select a particular row and then clicks the respective buttons to do the operation.

Html Page for Displaying DataTable

Sample:




<table align="center">
<tr>
<td>
<h:dataTable border="1" cellpadding="2" cellspacing="0" headerClass="headerClass" footerClass="footerClass"
rowClasses="rowClass1" styleClass="dataTable" value="#{beanname.data}" var="pagination" binding="#{beanname.datatable}">
<h:column>
<f:facet name="header">
<h:outputText value="Select"/>
</f:facet>
<h:selectBooleanCheckbox id="selectid" styleClass="selectBooleanCheckbox" binding="#{beanname.checked}">
</h:selectBooleanCheckbox>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Header Variable"/>
</f:facet>
<h:outputText value="#{pagination.headerid}"/>
<h:inputHidden id="hidden" value="#{pagination.variable2}" binding="#{beanname.variable2}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Header Variable1"/>
</f:facet>
<h:outputText value="#{pagination.variable2}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Header Variable2"/>
</f:facet>
<h:outputText value="#{pagination.variable3}"/>
</h:column>
</h:dataTable><BR>
<h:commandButton value="Opertion1" action="actionparam" id="Opertion1ID" >
<f:actionListener type="ListenerClassName" /></h:commandButton>
<h:commandButton value="View Opertion1" action="actionparam1" id="Opertion2ID" >
<f:actionListener type="com.anz.cpr.listener.TransactionHeaderListener" /></h:commandButton>
<h:commandButton value="Opertion1 TxHeader" action="actionparam2" id="Opertion3ID">
<f:actionListener type="ListenerClassName" />
</h:commandButton>
</td></tr>
</table>


Java Bean which holds the data (Backing Bean)


This bean is used by the above page to display the data
beanname.methodname

getData() method returns a list which contains the DB data

In the Bean create a method which will return a list which contains bean Object

Sample :




Public class SampleBean
{
private String variable;
private String variable1;
private String variable2;
private UISelectBoolean checked;
private UIData datatable;
public List tbllist;
/* Getter Setter Methods for variable1,2,3 and for other variables*/
public List getData()
{
/* Query DB and get the Resultloop through the result setsample i am using hibernateget Session for hibernate*/
List hquery=session.createQuery("from XYZ").list();
if (hquery != null && hquery.size() > 0)
{
tbllist=new ArrayList(hquery.size());
for (int i=0; i< hquery.size(); i++)
{
Tblxyz xyz=(Tblxyz)hquery.get(i);
SampleBean bean=new SampleBean();
/* get value from the db and set in the bean */
tbllist.add(bean);
}
}
}
}


ListenerBean


Since we are Implementing ActionListener we need implement the methods




public BeanListener implements ActionListener
{
public void processAction(ActionEvent event) throws AbortProcessingException
{
/* This will give the id name of the particular h-link which
* generated this action
* /
String sCommandName=event.getComponent().getId();
/*Getting the faces context*/
FacesContext context=FacesContext.getCurrentInstance();

/* Since we have three H-links we are cheking which one got triggred
* i.e operation1ID got triggred now i need that particular row data
*/
if(sCommandName.equals("Opertion1ID"))
{
ValueBinding valueBinding=Util.getValueBinding("#{beanname}");
SampleBean samplbean=(SampleBean)valueBinding.getValue(context);
/* since we have used binding the jsf we can get the entire datatable from the JSF page*/
UIData datatable=samplbean.getDatatable();
/* getting the totalRowCount */
int rowCount=datatable.getRowCount();
/* Looping through the datatable to check which row got selected*/
for (int index = 0; index < hvalue="samplbean.getVariable2().getValue().toString();">