how to access faces context and backing beans in a servlet filter

// You need an inner class to be able to call FacesContext.setCurrentInstance
// since it's a protected method
private abstract static class InnerFacesContext extends FacesContext
{
protected static void setFacesContextAsCurrentInstance(FacesContext facesContext) {
FacesContext.setCurrentInstance(facesContext);
}
}

private FacesContext getFacesContext(ServletRequest request, ServletResponse response) {
// Try to get it first
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) return facesContext;

FacesContextFactory contextFactory = (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
LifecycleFactory lifecycleFactory = (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);

// Either set a private member servletContext = filterConfig.getServletContext();
// in you filter init() method or set it here like this:
// ServletContext servletContext = ((HttpServletRequest)request).getSession().getServletContext();
// Note that the above line would fail if you are using any other protocol than http

// Doesn’t set this instance as the current instance of FacesContext.getCurrentInstance
facesContext = contextFactory.getFacesContext(servletContext, request, response, lifecycle);

// Set using our inner class
InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);

// set a new viewRoot, otherwise context.getViewRoot returns null
UIViewRoot view = facesContext.getApplication().getViewHandler().createView(facesContext, “yourOwnID”);
facesContext.setViewRoot(view);

return facesContext;
}

Preventing cloning of Object in while using singleton design pattern

Hi All,

Using singleton design pattern is a best way to access a valuable resource. In this case we do use Singleton design pattern and stops clients classes to create multiple instances of the Class.

But there is a loophole in this pattern and one can create instance of the Singleton class using object cloning.

So we should prevent cloning of object in this class as well if required.

Code given below gives a brief idea of how to stop client class to clone an object.

package com.sun;

/** * @author Sunil Chauraha */

class Clone1 implements  Cloneable{

@Override protected Object clone() throws CloneNotSupportedException

throw new CloneNotSupportedException(“Cloning of this class is not supported by me…”);

}
public class CloneTest  {

public static void main(String[] args) {

try{

Clone1 clone1 = new Clone1();

Clone1  clone2 = (Clone1)clone1.clone();

}catch (CloneNotSupportedException e) {

System.err.println(e.getMessage()+”: “+e);

}

}

}

Interview questions

1. Define your profession and carrear skills.
2. What is the difference between struts and jsf.
3. What the scope of application and request.
4. What is AJAX.
5. Where will you rate yourself in SQL.
6. Do you know any design pattern? if yes describe.
7. What is value binding and component binding.
8. Define lifecycle of richfaces.
9. How does a request completes?
10. What is jsf components?
11. What is component and events in jsf?
12. What did you do for performance inprovement?
13. What is IOC?
14. What is transaction management?
15. What is the life cycle of spring bean?
16. How will you configure spring and hibernate?
17. What is sessionfactory and session?
18. What is generics?
19. what is run time polymerphism?
20. how will you integrate spring in jsf?
21. what is hibernate?
22. what is difference between load and get in hibernate?
23. what is save, update and merge?
24. what is factory pattern?
25. what is spring mvc?
26. how will you integrate hibernate with spring?
27. what is aop?
28. what is criteria?
29. What is criteria and detached criteria?
30. one sql query for group by operation.
31. select second highest salary of an employee from emp table.
32. What is difference between struts and spring.
33 what is difference between jsp and servlet.
34 what is the life cycle of jsp.
35 what is the difference between requestForward method of servlet context and servlet config.

36. How we can instantiate a bean of abstract class having 2 subclasses.

37. How can we maintain a collection having the same order of insertion and unique values of object.

38. How can we use JPA in spring.

39. We have a singleton class and constructor is private, how can we create a bean in spring.

40. What is the mechanism used by Java for maintaining set and HashSet objects.

41. What is the significance of equals and hashCode methods in java and object comparison.

Class loading and java reflection

Here is some simple example of class loading and java reflection.

package com.sun;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.sun1.TestClass;
public class MainClass {
@SuppressWarnings(“unchecked”)
public static void main(String[] args) {
System.out.println(“Testing classloading…”);
try{
Class clazz = Class.forName(“com.sun1.TestClass”);
Method [] methods = clazz.getDeclaredMethods();
TestClass tc = new TestClass();
for (Method method : methods) {
try{
method.invoke(tc, new Object[]{“Sunil Chauraha”});
}catch(InvocationTargetException e){
System.err.println(e.getMessage());
}catch (IllegalAccessException e) {
System.err.println(e.getMessage());
}
}
}catch(ClassNotFoundException cnf){
System.err.println(cnf.getMessage()+” : “+cnf);
}
}
}

package com.sun1;
public class TestClass {
public void pring(String value){
System.out.println(“The value passed is : “+value);
}
}

UML Diagram and Eclipse

Hello………….

Here are the links for uml plug in configuration with eclipse.

http://www.seasar.org/en/tutorial/eclipse/uml_omondo/index.html

http://www.vogella.de/articles/UML/article.html#umltools_diagram

Global warming

When the word “Global warming” comes into mind or on voice or in ears. I start thinking who is responsible for this ever ending problem? I think, in fact i am sure that me, you and they all are responsible for this outcome. As a human being what we are doing or what we have done or what we are going to do. Some where that follows Einstein’s E=MC2 and produces unnecessary energy and the global warming increases by 0.000000001 % or more.

My dear friend please think something outstanding or wonderful thing that can decrease the rate of increase in temperature……… Read more

Singleton design pattern

As the name says… Singleton -> means just single.

There are so many situations where we need to create many or one instance of our class.  Like we will have a single database connection manger.

There are many ways to create a singleton design (i.e. Using User Defined exception class, using static class).

rather there is the most useful way that most programmer uses.  That is static method having a private default constructor.

public class IsSingle {
static boolean instanceFlag = false;
private IsSingle(){}
public static IsSingle getInstance(){
if(!instanceFlag){
instanceFlag = true;
return new IsSingle();
}
else{
return null;
}
}
// finalize is needed here, because if object IsSingle is garbage collected then isInstance must be false to invoke new.
public void finalize(){
instanceFlag = false;
}
}

Reading a Doc file using Java

Hi by using a simple java IO we can’t read contents of a doc file.

Jakarta poi has some utilities to read contents of a file using its api.

Every line of the doc file is considered as a paragraph.

import java.io.FileInputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class ReadandWrite {
public static void readDocFile(String filePath) {
POIFSFileSystem fs = null;
try {
fs = new POIFSFileSystem(new FileInputStream(filePath));
HWPFDocument doc = new HWPFDocument(fs);
WordExtractor we = new WordExtractor(doc);
String[] paragraphs = we.getParagraphText();
System.out.println(“Word Document has ” + paragraphs.length+ ” paragraphs”);
for (int i = 0; i < paragraphs.length; i++) {
paragraphs[i] = paragraphs[i].replaceAll(“\\cM?”, “”);
System.out.println(paragraphs[i]);
}
} catch (Exception e) {
}
}
public static void main(String[] args) throws Throwable {
readDocFile(“yourfile.doc”);
}
}

For this i used  poi-3.0-FINAL.jar.

How to use Gmail as your SMTP server – JAVA

Hi Here is an interesting code to send an email using gmail smtp server.

This asks for the login and password of any gmail accound and uses gmail smtp to send emails…

**************************************************************************************

package com.sunil.mail;
import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class SimpleJavaMail {

private Session mailSession;
protected PasswordAuthentication authentication;
private String user = null;
private String password = null;
private Properties props;

public SimpleJavaMail(){
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
props = new Properties();
props.setProperty(“mail.transport.protocol”, “smtp”);
props.setProperty(“mail.host”, “smtp.gmail.com”);
props.put(“mail.smtp.auth”, “true”);
props.put(“mail.smtp.port”, “465″);
props.put(“mail.smtp.socketFactory.port”, “465″);
props.put(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);
props.put(“mail.smtp.socketFactory.fallback”, “false”);
props.put(“mail.user”, “xxxxxxx@gmail.com”);
props.put(“mail.password”, “xxxxx”);
props.setProperty(“mail.smtp.quitwait”, “false”);
}

public void initMail(String user, String password) {
this.user = user;
this.password = password;
mailSession = createMailSession();
}

private Session createMailSession() {
Session session = null;
try {
session = Session.getDefaultInstance(props,    new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user,password);
}
});
} catch (Exception e) {
e.printStackTrace();
}
return session;
}

public synchronized void sendMail(String subject, String body, String sender, String recipients)
throws Exception{
String host;
String mailUserName = (String) getProps().get(“mail.user”);
String mailPassword = (String) getProps().get(“mail.password”);
host = (String) getProps().get(“mail.host”);
host = host.toLowerCase();
initMail(mailUserName, mailPassword);
MimeMessage message = new MimeMessage(mailSession);
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setContent(body, “text/plain”);
if (recipients.indexOf(‘,’) > 0){
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
}else{
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
}
Transport.send(message);
}

public Properties getProps() {
return props;
}

public void setProps(Properties props) {
this.props = props;
}

public static void main(String[] args) {
try{
String subject = “Test mail…”;
String body = “Hi Buddy…”;
String sender = “noname@noname.com”;
String recipients = “sunilxxxx@gmail.com”;
SimpleJavaMail mailJava = new SimpleJavaMail();
mailJava.sendMail(subject, body, sender, recipients);
} catch (Exception e) {
Logger.getLogger(SimpleJavaMail.class.getName()).error(e);
e.printStackTrace();
}
System.out.println(“Mail sent!”);
}

}

Running DOS command using java!

Hi…

Here is a small example.

We can use to run a dos command using java code.

/***************Code ******************/

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

class SunilCmd {

static public void main(String args[]) {
try {
StringBuffer sb = new StringBuffer();
BufferedReader buff = new BufferedReader(new InputStreamReader(    Runtime.getRuntime().exec(“cmd.exe /C dir”).getInputStream()));
/* Here Runtime.getRuntime creates environment to run the command */
/* .exec executes the parameters given inside the method */

/*
* here “cmd.exe /C” will invoke the DOS in exclusive mode and “dir”
* is a command that will be executed…..
*/

String line = buff.readLine();
while (line != null) {
sb.append(line + “\n”);
line = buff.readLine();
}
System.out.println(sb);
File f = new File(“output.txt”);
/**
*All the output will be written into output.txt file
*/
FileOutputStream fos = new FileOutputStream(f);
fos.write(sb.toString().getBytes());
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}

}

Follow

Get every new post delivered to your Inbox.