0

Семинар: Новости в Java платформата.

Posted by JOKe on 7/21/2011 05:12:00 PM

 

Анонса е леко нахално взаимстван от блога на Наков(http://www.nakov.com/blog/2011/07/21/seminar-java-7-java-ee-6-bgjug-27-july-2011/) поради мързел от моя страна да го напиша. Общо взето промените са replace на Найден Гочев с Аз.

 

Имам прекрасна новина за всички Java фенове. След като Java 7 официално излезе, дойде ред и на Българскота общност от Java разработчици да се присъедини към поредицата “Java 7 Launch” събития. Благодарение на много хора :+) ще си направим семинарче и парти по случай Java 7 и новостите от Java света, които идват заедно с нея.

Програма на семинара

    Kакво ново в Java 7?
    Kакво ново в Java EE 6?
    Kакво ново в JavaFX 2.0?
    Kакво ново в JavaME?

Лекциите са част от официалния “Oracle Java 7 Launch Kit”, който е предоставен от Oracle за Българската Java потребителска група (BGJUG) заедно с тениски и други рекламни материали.

Кога и къде?

Семинарът “Новости от Java платформата” ще се проведе на 27 юли (сряда) от 19:00 часа в учебната зала на Академията на Телерик за софтуерни инженери. Адресът е: София, Младост-1, бул. Александър Малинов 33, партер.

Лектор

Лектор ще бъда аз.

Благодарности

Благодарностите за организирането на семинара са за:

    BGJUG – организатор на събитието
    Oracle Corp. които предоставиха Java 7 Launch Kit, тениски и рекламни материали за BGJUG
    Петър Тахчиев, който поръча тениските и launch kit-a.   
    Академия на Телерик – домакин на събитието
    Светлин Наков, който помогна с намирането на домакин ;)



|
0

JavaScript inheritance (object-oriented programming)

Posted by JOKe on 7/05/2011 04:47:00 PM in

 

There are many posts explaining what JavaScript inheritance is how it works, is it bad or good, how it is comparable with Java inheritance with millions of examples using third party apis or function to make inheritance look more like C#/C++/Java Inheritance.

This post is just to show HOW inheritance looks without anything else except browser so next time when you need to find it you can open this post which explains everything you need.

JavaScript uses so called prototype inheritance you don’t need to know more except it is different then a C#/C++/Java way of doing inheritance

Define a class

In JavaScript you can define class like this:

function A(){
    this.aMethod = function (){
        alert("A method");
    }
    this.bMethod = function () {
        alert( "B Method");
    }
}

Yes, yes there are different ways I find this one the most easy one  you can read more about the ways how to create a class in JavaScript here : http://www.phpied.com/3-ways-to-define-a-javascript-class/

Next you have a class how can you use it ?

var a = new A();
a.bMethod(); //will print B method
a.aMethod(); //will print A method

BAM nothing else, easy right?

ok so what if you want to extend this class ?

Prototype Inheritance

First you will create another class:

function B(){
    this.cMethod = function () {
        alert("C method");
    }
}

ok but how can I say that B extends A ? Simple : B.prototype = new A();

Example :

B.prototype = new A();

var b = new B();
b.aMethod(); //will print A method
b.bMethod(); //will print B method
b.cMethod(); //will print C method

Overriding is fine too.

function B(){
    this.bMethod = function() {
        alert("overriding");
    }
    this.cMethod = function () {
        alert("C method");
    }
}

And use it as before ( keep in mind the .prototype = new A is required only ones)

B.prototype = new A();

var b = new B();
b.aMethod(); //will print A method
b.bMethod(); //will print overriding
b.cMethod();// will print C method

Full example:


function A(){
    this.aMethod = function (){
        alert("A method");
    }
    this.bMethod = function () {
        alert( "B Method");
    }
}

function B(){
    this.bMethod = function() {
        alert("overriding");
    }
    this.cMethod = function () {
        alert("C method");
    }
}

B.prototype = new A();

var b = new B();
b.aMethod(); //will print A method
b.bMethod(); //will print overriding
b.cMethod(); //will print C Method

 

Inheritance through Functions

If you don’t like prototypes for some reason you can use a inheritance through functions.

Example:

you just need when you define a class B (the subType) to call this.someFunctionName = supertype and then invoke this.someFunctionName(). Example this.extends = A; this.extends();

Full Example:


function A(){
    this.aMethod = function (){
        alert("A method");
    }
    this.bMethod = function () {
        alert( "B Method");
    }
}

function B(){
    this.extends = A;
    this.extends();
   
    this.bMethod = function() {
        alert("overriding");
    }
    this.cMethod = function () {
        alert("C method");
    }
}

var b = new B();
b.aMethod(); //will print A method
b.bMethod(); //will print overriding
b.cMethod(); //will print C method



UPDATE: Under Internet Explorer if you want to use inheritance through Functions the FUNCTION name that you have to use SHOULD NOT BE "extends" the above example with extends will not work because IE don't like extends :), use some other name like "inheritFrom" for example


|
1

[LINUX] How to find a specific String in file content with specific file name in specific folder

Posted by JOKe on 5/19/2011 12:19:00 PM

 

This is really the dumbest thing ever in linux, there are many many dumb things but this is the dumbest. Ultra trivial task you want to “find a specific string in a file content of specific file type starting from root folder” this is the easiest thing ever, it was not available in Windows XP/98 and because of that I was keeping one JBuilder which can search normally in any java file containing XXX in starting from this folder. But in Windows Vista / 7 this is done EASY just press F3! In Linux on the other hand it is a NIGHTMARE I was having a trivial task which takes… 10 seconds to search for a properties file which contains a default.session.timeout=600 which is a row in this file and this took me more then 30 mins because there are TONS of posts how this is done but none have worked there ware examples using grep, egrep whatever NOTHING is working total CRAP really. So in short I found it somewhere and I want to post it in order to have another POST in google which gives the answers.

So In short:

How to search for a file content in linux in specific file names starting from specific root folder.

find . -name "*.properties" -print | xargs grep default.session.timeout=600

Which will give you all properties files which contains default.session.timeout=600 it doesn’t have to be the match the whole row you can search for just default.session which will give you all files which contains default.session. This command is typed in the folder that you want to start the search from for example /opt/hybris/


|
2

Generate JavaDoc with UML diagrams

Posted by JOKe on 3/11/2011 12:08:00 PM in

In my life many times has happened when I am assigned to a totally new project that I have no idea what it is about, that has to go live in 2 weeks and that I have to fix some issues in this ultra strange code sometimes even code written in different language.

On my question is there any documentation the answer is: Yes but it is very old or no. So in short they want me to start working on a project with no documentation at all.

My second question is is there a javadoc and the anwer is : yeah … kind of … so I am in a project with 30% javadoc with methods in French language for example ( I don’t know even a single word in French) so in short I am loosing 2 weeks to understand what is using what what is the model what is PersonnePhysique  and what is this crazy domain model.

I believe this has happened with everyone of you at least once so what can you do ?

  • You can start digging into the java code like crazy ( like everyone of us have tried many times)
  • You can install intellij idea and use the great reverse engineering way to create UML diagrams for specific classes but intelliJ idea costs money.
  • You can install netbeans 6.5 and do the same but you have to use this out dated version of NetBeans because this doesn’t exist in newer versions, thanks Oracle.
  • You can install Eclipse + MoDisco + MDT + KML to generate xmisomething file then to generate xml file with KML thingy then to use UML2 tools to view this diagram blah.
  • Or you can find some other way… this is the other way which I believe is very nice and useful and you should use it in every project that you can actually this should be the first thing that the architect should put in the project.

So in short the other way is to generate a UML diagrams each time when a javadoc is generated it will generate a UML diagrams for each class and package which contains whatever you want operations,attributes,constructors just names you can click on them and navigate using them it is AWESOME.

How this will look like ? like this:

uml1

And you can click on items for example on Category which will forward you to the Category javadoc which has a diagram as well which looks like this :

UML2

Awesome right ?

How you can do it ? In my example I will use maven so what you have to do :

use of UmlGraph

use of Graphviz

change of maven pom.xml update (for ant integration check the last link in the blog post)

1) install graphviz on the machine that will generate the javadoc .. usually this is a linux machine which runs hudson or whatever so in case of ubuntu you just need apt-get install graphviz4 otherwise you can download the msi/deb/rpg/source from here http://www.graphviz.org/Download..php then just type “dot –-help” in console to check that the dot executable is in your path.

2) update your pom.xml adding UmlGraph just add:

<plugin>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <aggregate>true</aggregate>
                    <show>private</show>
                    <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet>
                    <docletArtifact>
                        <groupId>org.umlgraph</groupId>
                        <artifactId>doclet</artifactId>
                        <version>5.1</version>
                    </docletArtifact>
                    <additionalparam>
                        -inferrel -attributes -types -visibility -inferdep -quiet -hide java.* -collpackages java.util.* -qualify -postfixpackage
                        -nodefontsize 9
                        -nodefontpackagesize 7
                            </additionalparam>
                </configuration>
            </plugin>

3) invoke mvn javadoc:javadoc … and you are done. :+) easy right ? You can see explanation about all umlgraph options here http://www.umlgraph.org/doc/indexw.html like do you don’t want to see the attributes, but you want the operations and etc..

Example with operations will look like this:

 

For ant integration check http://java.dzone.com/articles/reverse-engineer-source-code-u


|
6

Using of Collections.emptyList() the right way in Java 1.5+

Posted by JOKe on 7/27/2010 04:07:00 PM

It is little strange that no one really uses emptyList like he should in Java.
So this is small post showing how to use the emptyList method in the Collections class.

Question: How to create an empty list ?
lets assume that we have a class Book with multiple titles.
So the class in our examples will be:

import java.util.List;

public class Book {

      private List<String> titles;

      public void setTitles(List<String> titles) {

            this.titles = titles;

      }

      public List<String> getTitles() {

            return titles;

      }

}

Lets say that in our snippet we have something like :

  Book myCrazyBook=new Book();

and we want to assign an empty list to the titles in this book. This is a common scenario if you want to set something to be emptyList in specific case instead of null.

So of course your first try will be something like:
Answer 1:

  myCrazyBook.setTitles(new ArrayList()); 

-WARRNING - ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized

Ok changing to:

  myCrazyBook.setTitles(new ArrayList<String>());   

WTF ? the problem in this answer is not small one :
- you are creating empty ArrayList which basiclly is not needed. ( what if you are in a loop 1000+ empty ArrayLists ? )

Answer 2.

   myCrazyBook.setTitles(Collections.EMPTY_LIST);

-WARNING : Type safety: The expression of type List needs unchecked conversion to conform to List<String>, because the EMPTY_LIST is raw type, which was heavily used before Java 1.5.
The definition of this list is :

    /**

     * The empty list (immutable).  This list is serializable.

     *

     * @see #emptyList()

     */

    public static final List EMPTY_LIST = new EmptyList();

So you see it is not ArrayList or LinkedList or MyCrazyCustomListWhichIUseEveryWhereList.

Answer 3:
Eclipse will tell you this answer : Replace with Collections.emptyList();

      myCrazyBook.setTitles(Collections.emptyList());

COMPILE TIME ERROR: why ? because emptyList invoked like that means List of Objects not List of String. The other thing is that you cannot cast to List<String> because you cannot cast List<Object>  to List<String>.

Answer 4:
You know that there is Collections.emptyList() AND YOU KNOW THAT IT RETURNS List<T>
so your answer is:

            Book myCrazyBook=new Book();

            List<String> titles = Collections.emptyList();

            myCrazyBook.setTitles(titles);

           

And this will work WITHOUT any WARNINGS or ERRORS. The type of the List is taken from the type of the variable that you are trying to assign to.
Of course why you need this local variable ? I want to remove it it is not needed and used, but if you remove it you are in Answer 3. So what can you do ?

Answer 5: The right but strange looking answer.

            Book myCrazyBook=new Book();

            myCrazyBook.setTitles(Collections.<String>emptyList());

Yes this is not a joke there is a dot (.) then the generic type before the method name. This compiles, runs, no warnings thats the real way.
It is a little strange that most people dont know this aspect of generics in Java even I didn't know it, I was thinking that you cannot pass a generic type like this but as it looks you can.

So if you have some static method like this one:

public class Main{

      public static <G> List<G> someGreatMethod(){

            List<G> gList= new ArrayList<G>();

            return gList;

      }

}

you can invoke it with Main.<String>someGreatMethod(); for example.

|
0

Spring MVC, Spring Bean Validation Framework and validating confirm password / confirm email fields.

Posted by JOKe on 6/29/2010 12:19:00 PM

How to write validation like confirm password, confirm email and etc in Spring MVC.

NOTE: To make bean validation to work its nice to read this tutorial: <a href="http://wheelersoftware.com/articles/spring-bean-validation-framework.html"></a>

Today I was busy making some validations and implementations on very common scenario:
change email and password.
So we have a new password AND a new email also for both of them we have a confirm email/password field. And we want to validate everything nicely and to show to the user the real validation message if there is some error.
So ... I've to use a form which already uses some annotations like @NoBlank and etc I think everyone of you is using annotations framework if you don't use it SHAME ON YOU !:)


Anyway so I've added some fields to existing form bean:

private String newPassword;
private String confirmNewPassword;
private String newEmail;
private String confirmNewEmail;

Basiclly in my case this is very big form and none of this fields is mendatory so the user can leave all of them blank. My first idea was to add at least Length for the password and Email annotations for the email so I do:

@Length(min=6,max=20)
private String newPassword;
private String confirmNewPassword;
@Email
private String newEmail;
private String confirmNewEmail;

Ok but the confirm fields should have the same rules ? Maybe...
The problem that I saw is that length and email by default means NotBlank.
To make email validator to work or length validator they first check is the field blank. In my case I want the blank to be OK.. so I asked god google what to do.
The answer applyIf.
So at the end I get :

@Length(min = 6, max = 20, applyIf = "newPassword is not blank") //cool right ?
private String newPassword;
private String confirmNewPassword;
@Email(applyIf = "newEmail is not blank") //cool right ?
private String newEmail;
private String confirmNewEmail;

Cool right ? yep it is cool. but let me add the validation for confirmNewPassword and confirmNewEmail.

@Length(min = 6, max = 20, applyIf = "newPassword is not blank")
private String newPassword;
@NotBlank(applyIf = "newPassword is not blank")
private String confirmNewPassword;

@Email(applyIf = "newEmail is not blank")
private String newEmail;
@NotBlank(applyIf = "newEmail is not blank")
@Email(applyIf = "newEmail is not blank")
private String confirmNewEmail;

Nice.. so I have validation on new* fields only if they are not blank. Also I have a validation on the confirm fields only if again new* fields are not blank.
Cool... what left ? ahh the most hard part to check is the confirmpassword the same as the newPassword and is the confirmEmail same as the newEmail.

the first idea ofcourse is to write a custom validator.
So I write this :

class NewPassAndEmailValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return PersonalDetailsFormBean.class.equals(clazz);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        PersonalDetailsFormBean personalDetailsFormBean = (PersonalDetailsFormBean) obj;
        if (personalDetailsFormBean.getNewPassword() != null
                && !personalDetailsFormBean.getNewPassword().equals("")) {
            if (!personalDetailsFormBean.getNewPassword().equals(personalDetailsFormBean.getConfirmNewPassword())) {
                errors.rejectValue("confirmNewPassword", "PersonalDetailsFormBean.confirmNewPassword[customvalidator]");
            }
        }
        if (personalDetailsFormBean.getNewEmail() != null && !personalDetailsFormBean.getNewEmail().equals("")) {
            if (!personalDetailsFormBean.getNewEmail().equals(personalDetailsFormBean.getConfirmNewEmail())) {
                errors.rejectValue("confirmNewEmail", "PersonalDetailsFormBean.confirmNewEmail[customvalidator]");
            }
        }
    }

}

and then in the controller submit method.

validator.validate(personalDetailsFormBean, result); //this invokes the annotation based validator.

NewPassAndEmailValidator newPassAndEmailValidator = new NewPassAndEmailValidato();
newPassAndEmailValidator.validate(personalDetailsFormBean, result);

if (result.hasErrors()) {
... return...
}

This .... WORKS FINE. BUT... ah its not cool :( ... I mean even in struts 1 in 2001 we ware having a validation based on expression. AND we have even better way here... Awesome :D

So I've removed this validator... and write only "this":

@Expression(value = "confirmNewPassword = newPassword", applyIf = "newPassword is not blank")

So the final example looks like this:

@Length(min = 6, max = 20, applyIf = "newPassword is not blank")
private String newPassword;
@NotBlank(applyIf = "newPassword is not blank")
@Expression(value = "confirmNewPassword = newPassword", applyIf = "newPassword is not blank")
private String confirmNewPassword;

@Email(applyIf = "newEmail is not blank")
private String newEmail;
@NotBlank(applyIf = "newEmail is not blank")
@Email(applyIf = "newEmail is not blank")
@Expression(value = "confirmNewEmail = newEmail", applyIf = "newEmail is not blank")
private String confirmNewEmail;

:) ok this looks cool :D maybe not so cool than 20+ if statements to checks for null for some of you to but I like this way :))


|
9

JavaEE 5 (JSF + JPA + EJB3) using Eclipse

Posted by JOKe on 10/26/2009 05:56:00 PM in
Today I will show you how to create Enterprise Application using Java EE 5 and GlassFish.
I will use
- Eclipse 3.5 + WTP
- GlassFish v. 2.1
- JSF Mojarra implementation.
- EJB 3.0.
- JPA Toplink essentials implementation.
- MySQL
No NetBeans or JDeveloper magic involved :)
The prerequirement is:
Add datasource in glassfish. Read this how you can make this here: http://gochev.blogspot.com/2009/10/creating-datasource-in-glassfish-v-21.html

1) First you need to add glassfish in your eclipse.
- Go to Servers View
- Right Click, New
- Choose GlassFish v 2.1 if you dont have glassfish click on Download additional adapters link choose glassfish wait and restart eclipse. Than try again.




2) Create the database

CREATE TABLE `lesson`.`USERS` (
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`username` VARCHAR(45) NOT NULL,
`password` VARCHAR(45) NOT NULL,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE = InnoDB;



3) Create EJB project





4) Add persistance.xml file in META-INF folder

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">

<persistence-unit name="toursUnit">
<jta-data-source>lessonMySQL</jta-data-source>
<class>org.joke.model.User</class>
</persistence-unit>

</persistence>



5) Create Simple Entity org.joke.model.User

package org.joke.model;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "USERS")
public class User {

private Long id;
private String name;
private String username;
private String password;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

@Basic
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Basic
public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

@Basic
public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}



}


6) Create HelloService EJB that will use EntityManager

- The local interface is:
package org.joke.service;
import javax.ejb.Local;

import org.joke.model.User;

@Local
public interface HelloService {
public User login(String username,String password);
}


-The implementation is:

package org.joke.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.joke.model.User;

/**
* Session Bean implementation class HelloServiceImpl
*/
@Stateless
public class HelloServiceImpl implements HelloService {

@PersistenceContext(unitName = "toursUnit")
EntityManager em;

public HelloServiceImpl() {
}

@Override
public User login(String username, String password) {
Query query = em
.createQuery("select u from User u where u.username = :username and u.password = :password");
query.setParameter("username", username);
query.setParameter("password", password);

List<User> result = query.getResultList();

if (result != null && result.size() > 0) {
return result.get(0); //first user
}
return null;
}

}


7) Create Dynamic Web Project





8) Add JSF to this Dynamic Web Project

- Edit web.xml and add FacesServlet
 <servlet>
<display-name>FacesServlet</display-name>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>


9) I will use a very simple login form (login.jsp) and home.jsp where you will go if login is successfull.

<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html" version="2.1">
<jsp:directive.page language="java"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" />
<jsp:text>
<![CDATA[ <?xml version="1.0" encoding="UTF-8" ?> ]]>
</jsp:text>
<jsp:text>
<![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ]]>
</jsp:text>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hello JSF Page</title>
</head>
<body>
<f:view>
<h:messages style="color:red;"></h:messages>
<h:form id="loginForm">
<table>
<tr>
<td align="right"><h:outputText value="Username: " /></td>
<td><h:inputText id="username"
value="#{userBean.currentUser.username}" required="true">
<f:validateLength maximum="10" minimum="3" />
</h:inputText></td>
<td><h:message for="username" style="color:red;" /></td>
</tr>
<tr>
<td align="right"><h:outputText value="Password: " /></td>
<td><h:inputSecret id="password"
value="#{userBean.currentUser.password}" required="true" /></td>
<td><h:message for="password" style="color:red;" /></td>
</tr>
<tr>
<td colspan="3"><h:commandButton value="login"
action="#{userBean.login}" /></td>
</tr>
</table>


</h:form>
</f:view>
</body>
</html>
</jsp:root>


- The home.jsp looks like this:

<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html" version="2.1">
<jsp:directive.page language="java"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" />
<jsp:text>
<![CDATA[ <?xml version="1.0" encoding="UTF-8" ?> ]]>
</jsp:text>
<jsp:text>
<![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ]]>
</jsp:text>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hello JSF Page</title>
</head>
<body>
<f:view>
Welcome user

</f:view>
</body>
</html>
</jsp:root>



- and faces-config.xml looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
version="1.2">
<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/home.jsp</to-view-id>
</navigation-case>
</navigation-rule>

<managed-bean>
<managed-bean-name>userBean</managed-bean-name>
<managed-bean-class>mbeans.UserBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>


-The UserBean source is:

package mbeans;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.joke.model.User;
import org.joke.service.HelloService;

public class UserBean {
private User currentUser = new User();
@EJB
private HelloService helloService ;

public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
}

public User getCurrentUser() {
return currentUser;
}

public String login() {
User result = helloService.login(currentUser.getUsername(),
currentUser.getPassword());
if (result!=null) {
currentUser = result;
return "success";
}
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage("username and password not found"));
return null;
}

}

10) You can notice that I use HelloService and User model class in the Dynamic web project. To do this you have to add the service project as referenced by the web project.
- Right click on the web project and choose Properties

-Go to Build path/Projects

-Add the services project

-Now check the UserBean it should not contain any errors.
11) Create Enterprise Applicatin and add Web and EJB module to this application



12) Right click on the Enterprise Application and choose Run on server.

13) go to http://localhost:8080/HelloWeb/login.jsf and test it :)



That's all.
Note that we did not include any third party jar files in this projects. This is because GlassFish include JSF 1.2 Mojarra implementation and Toplink JPA implementation.

*Update : full source code of the example you can download from: http://dl.getdropbox.com/u/887821/HelloJavaEE5.rar

|

Copyright © 2009 JOKe's Blog All rights reserved. Theme based on the Theme by Laptop Geek with changes by JOKe. | Bloggerized by FalconHive.