Sunday 13 December 2015

OCEJBCD -4. Advanced Session Bean concepts

OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification
4.1. Understand the relationship between the EJB container and an EJB component.

EJB components:
  • Remote business interface. exposes business logic to remote clients. 
  • Local business interface. exposes business logic to local clients.
  • Local no-interface. exposes public methods of the bean without using interface.
  • Bean class.
* Note: message driven beans do not have remote or local interface.


EJB Container
Is the run-time container for beans deployed in the application server.
The container manages:
  • Bean life cycle
  • Persistence
  • Transaction
  • Security
  • Concurrency

4.2. Describe the life cycle for stateless and stateful session beans

Stateless life cycle

Stateful life cycle

Note: when there is a timeout or a system exception the bean will be back to does not exist state.

4.3. Implement session bean life cycle methods

import javax.annotation.PostConstruct
import javax.annotation.PreDestroy

@PostConstruct and @PreDestroy are callbacks when bean instances are created or destroyed.

import javax.ejb.PostActivate
import javax.ejb.PrePassivate

@PostActivate and @PrePassivate. To make the bean garbage collected in inactive periods, saving memory resources. The bean can be activated later and will maintain its conversational state.

4.4. Use a session bean to perform asynchronous communication

import javax.ejb.Asynchronous
@Asynchronous 

You can use asynchronous invocation on stateless session bean or singleton session beans.

The return type of the method annotated with Asynchronous can be void or java.util.concurrent.Future<V> (java/util/concurrent/Future.html)

Example of session asynchronous bean implementation:

We need to define a stateless bean with an async method that is going to be invoked from a servlet. In the example we will have a page asking as for a user name and a button to submit. 

After submission our servlet will get the request parameter "username", and will call the async method of the bean using the username as argument.

The bean async method will receive the username, will wait 5 seconds and will return after that time a greeting message: Hello + username.

Bean code: 

Important:

  1. The bean is stateful session with an async method
  2. the async method returns a Future<T> object


Servlet code:

Important:

  1. servlet with a get method, and the bean is injected with annotation @EJB
  2. Observe that we will return the message back to the JSP when Future.isDone() that returns true when the task is completed.


JSP code:


The result when we executes the code above:
http://localhost:8080/TestWeb/helloPage


Remember:


  • TestWeb is the name of our web project(context)
  • helloPage is the name we have indicated in the annotation @WebServlet("/helloPage")



When the button is clicked after 5 seconds the greeting message is displayed in the page:

4.5. Have fine-grained control over packaging and deployment

Enterprise beans can be deployed using ejb-jar or war modules.

ejb-jar
  • root
    • classes
    • META-INF
      • ejb-jar.xml
      • manifest
WAR
In a WAR file we can include the classes under classes folder or include the JAR file under lib.
  • root
    • WEB-INF
      • ejb-jar.xml(optional)
      • classes (*)--> ejb classes included in this folder
      • lib
        • ejb-jar(*) --> JAR file


OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

Tuesday 24 November 2015

Configuring an EJB environment

This is a specific post to describe the steps to configure an environment in your IDE to create EJB applications, and deploy them successfully in a server.

In the example are used:
  • IDE - Eclipse Luna
  • Server - glassfish 3.1
  • JDK - Java 1.7

Create EJB project

EJB project structure - example

*Note: Take into account that the EJB 3.1 API needs to be added to the build path



The implementations details are in the previous post: http://javawithbreakfast.blogspot.com/2015/11/ocejbcd-3-accesing-session-beans.html

Create Web project



Web project structure:

*Note: Take into account that the servlet3.0 API needs to be added to the build path

Make the EJB project visible to the web project

Include the EJB project in the build path of the web project:
-Select web project, right button.
-Build path/Projects/ Add the EJB project




Important: to make the EJBs visible to the web project, the EJB project should be included in the deployment assembly:
- Select web project, right button. 
- Deployment assembly/ Add:  add EJB jar



Deployment
Deploy both projects in the server:


Saturday 21 November 2015

OCEJBCD - 3- Accesing Session Beans

OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

3.1. Understand the purpose and role of JNDI in relation to EJB components

JNDI : Java naming directory
Binding - assigning a name to an EJB object which can be used later.
Lookup - looking up and getting an object of EJB.



3.2. Configure JNDI environment properties

http://docs.oracle.com/javaee/6/tutorial/doc/gipjf.html#girgn

global
java:global[/application name]/module name/enterprise bean name[/interface name]
module
java:module/enterprise bean name/[interface name]
app
java:app[/module name]/enterprise bean name[/interface name]

3.3. Use JNDI to look up a resource

Accessing an enterprise bean can be done by dependency injection or JNDI lookup.

Example using JNDI lookup:
ExampleRemote example = (ExmapleRemote) InitialContext.lookup("java:global/myApp/ExampleRemote");

3.4. Write code that receives a resource reference through injection

The annotations for inject a resource are:
@EJB - used to inject other EJB reference (on fields or on methods).
@Resource - used to inject datasource or singleton services like sessionContext, timerService etc.

We will see a complete code example in the followings sections (3.5- 3.7) and step by step we will create a javaEE application. This simple application is compound by:
  • Web client project : with a servlet and JSP
  • EJB server project :with sessionEJB and its interface.

The purpose will be create an application that allows a user selecting one color from a dropdown list. When submitting the selection a servlet will be executed and will call an EJB bean method. The bean method will return the color that will be displayed in the screen.

3.5. Create a session bean client


We are going to define an stateless session bean with a method that will evaluate a number of options and it will return the hex code corresponding to one color:

If input is 1 -- > color blue
If input is 2 -- > color red
If input is 3 -- > color yellow


3.6. Create a session facade

http://www.oracle.com/technetwork/java/sessionfacade-141285.html

Session facade provides a level of abstraction between the client and the business object. It manages the interactions between client and business services.

For the session bean defined in the previous section we will define an interface, that will be used by the client to access to our bean.


3.7. Use dependency injection to locate an EJB


Now, we will have to define the client that will call the bean (Servlet and JSP).
JSP

Servlet class
The servlet class will have a method doGet, that will be called everytime the button submit is clicked.
The dependency injection to locate the bean is applied by annotation:
  @EJB
  TestBeanLocal colorBean;


After deploying our application (web and EJB) in the server. When entering this url in the browser: http://localhost:8080/ColorWeb/myColor, the page is open:

 When a color is selected the corresponding hex code and color are shown in the screen
Note: The details about environment configuration are described in this post : http://javawithbreakfast.blogspot.com/2015/11/configuring-ejb-environment.html
OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

Sunday 25 October 2015

OCEJBCD - 2- Implementing Session Beans

OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

2.1. Examine session Beans

session bean encapsulates business logic that can be invoked programmatically by a client over local, remote, or web service client views. 

What is a session bean?

2.2. Identify the three types of session beans
  • Stateless
    • they can support multiple clients
    • does not mantain conversational state with the client.
  • Stateful
    • Mantains conversational state with the client.
    • Relationship 1:1 with client.
  • Singleton 
    • new in javaEE6
    • is instantiated once per application and exists for the lifecycle of the application (one per application).
    • A single enterprise bean needs to be accessed by multiple threads concurrently

2.3. Choose the correct session bean type given a business constraint

  • Session stateless - to implement a web service. Transaction-processing applications, which are executed using a procedure call.
  • Session stateful - GUI client (filling fields in a GUI needs conversational state)
  • Singleton- to implement web service endpoints

2.4. Create session beans package and deploy session beans
The javabeans configuration can be defined with annotations or using an xml deployment descriptor located in :
META-INF/ejb-jar.xml

OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

Saturday 17 October 2015

OCEJBCD - 1- Introduction to JavaEE

OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

1.1. Gain an understanding of the Java Platform, Enterprise Edition(JavaEE)


An enterprise application provides business logic modules. It uses architectures of distributed layers and it is executed by an applications server.

The features of JavaEE in every version are defined by several specifications (JSR- Java specification request). 

1.2. Examine the JavaEE application architecture

Summary of JavaEE6 APIs:
    • EJB : Enterprise Java Beans Technology
    • Servlets
    • JSF : Java server faces
    • JSP : Java server pages
    • JSP Tag libraries
    • JPA: Java Persistence API
    • JTA: Java Transaction API
    • JAX-RS Java API for RESTful Web Services
    • Managed Beans
    • CDI JSR 299- Contexts and dependency injection for JavaEE
    • JSR 330- Dependency Injection for Java
    • Bean Validation
    • JMS : Java Message API
    • JavaEE Connector Architecture
    • Java Mail API
    • Java Authorization Contract for Containers
    • JASPIC Java Authentication Service Provider for Containers

1.3. Examine JavaEE container services

Types of containers in JavaEE:

  • Client side
    • Application Web Container
    • Applet Container
  • Server side (JavaEE Container)
    • Web Container
    • EJB Container

Popular web containers: Apache Tomcat, Jetty,..
Popular full JavaEE Containers: Jboss(WildFly), Weblogic, Glassfish, ...

Services provided by a full JavaEE container:


  • Security
  • Transaction management
  • JNDI (Java naming directory interface)
  • Java EE remote connectivity (RMI)
  • Manage servlet and bean lifecycle
  • Database connection and persistence
  • Access to JavaEE APIs.

1.4. Examine the EJB component types
  • Enterprise bean class
    • Session bean -- associated with a client. They can be stateless or stateful.
    • Message-driven bean - allows to receive messages asynchronously (JMS)
  • Business interfaces
  • Helper classes (utilities, exceptions..)

1.5. Evaluate the EJB Lite Container

A lightweight subset of Enterprise JavaBeans(EJB 3.1) functionality.
http://www.oracle.com/technetwork/articles/javaee/javaee6overview-part3-139660.html#ejblite
Features included in EJB lite:
  • Stateless, stateful, and singleton session beans
  • Local EJB interfaces or no interfaces
  • Interceptors
  • Container-managed and bean-managed transactions
  • Declarative and programmatic security
  • Embeddable API
OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification

Sunday 27 September 2015

Producer Consumer Implementation - Blocking Queue

The Producer-Consumer design deals with the solution when different threads are involved in accessing the same shared resource to take or put elements from/to it.

- A consumer, thread class that removes one element from a resource.
- A producer, thread class that adds elements into a resource.
- A shared resource, called also monitor, will be a queue where the elements will be put and taken.

Originally this problem can be solved applying the methods wait() and notify(), and synchronizing the monitor.

The problem can be more simple using one of the collections of the concurrency package as blocking Queue (since 1.5).

BlockingQueue:
public interface BlockingQueue<E> extends Queue<E>

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
Definition from: 
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html

This collection is part of java.util.concurrent package and its main feature is that provides internal locks and concurrency mechanism to be accessed atomically (thread-safe). The methods that can be used to implement the consumer-producer are: put / take.

Example:
Output:
Consumer takes0
Producer puts 0
Producer puts 1
Consumer takes1
Producer puts 2
Consumer takes2
Producer puts 3
Consumer takes3
Producer puts 4
Consumer takes4
Producer puts 5
Consumer takes5
Producer puts 6
Consumer takes6
Consumer takes7
Producer puts 7
Consumer takes8
Producer puts 8
Consumer takes9
Producer puts 9

Thursday 10 September 2015

Java 7 - NIO - Watcher implementation

One of the new features of Java7 was NIO package. 
Java NIO also known as new input output library as is a set of classes defined under package java.nio.* to access files, file attributes and file systems.

The main classes from this package are:
  • Path - to manage file location and directory hierarchy
  • Files - to manage file operations
Some functionalities that can be implemented are:
  • Walking the file tree
  • Watchers - monitoring the creation/modification/deletion of files
  • Copy/Create/Delete files from a directory(atomic operations with synchronization)
  • Find files using matcher expressions
In the following example we are going to see how to implement a watcher. This is useful when we need a process to monitor when a file is created/modified or deleted in a directory.

Steps in this example:
1- watch for new files in a directory
2- evaluate the mime type of the file
3- if it is a text file it will be copied to other directory.


Saturday 5 September 2015

OCEJBD - Oracle Certified Expert, Enterprise JavaBeans Developer - Intro

1Z0-895.- Oracle Certified Expert, Java Platform, Enterprise Edition 6 Enterprise JavaBeans Developer

The next certification I was planning to study is the certification in enterprise java beans Java EE6.
The requirement for this certification is to have passed the exam OCPJP (formely SCPJP).

These are a set of resources I am going to use for preparing the contents (at least initially)

Resources:
http://www.coderanch.com/forums/f-70/java-EJB-SCBCD
http://www.coderanch.com/how-to/java/ScbcdLinks#ejb6

Book:



Important Note: this book (Head First EJB) is based in EJB 2 (the exam is about EJB 3). It is a good book for general understanding of Java Beans, but the contents are not covering the current certification for Java EE6.   EJB 2 is very different from EJB 3.0, they are not related so it is recommended to go for the current version directly, so it is not necessary to learn EJB 2 to understand EJB 3.


You can find this recommendation in the following thread from JavaRanch.

In order to cover all the topics of the exam related with the current EJB3  version I am using this book : O'Reilly Enterprise JavaBeans 3.1



Mock Exams:
-Whizlabs
-Enthuware

Promo information:
There is a promotion this year. Introducing the code Java20 when you book an exam you can benefit of a discount of 20% in a java certification. So, I will try to book the exam before the end of this year.
https://blogs.oracle.com/certification/entry/1131_01

Topics

Introduction to JavaEE
  • Gain an understanding of the Java Platform, Enterprise Edition(JavaEE)
  • Examine the JavaEE application architecture
  • Examine JavaEE container services
  • Examine the EJB component types
  • Evaluate the EJB Lite Container
  • Compare JavaEE application development with traditional enterprise applicaton development.
Implementing Session Beans
  • Examine session Beans
  • Identify the three types of session beans
  • Choose the correct session bean type given a business constraint
  • Create session beans package and deploy session beans
Accesing Session Beans
  • Understand the purpose and role of JNDI in relation to EJB components
  • Configure JNDI environment properties
  • Use JNDI to look up a resource
  • Write code that receives a resource reference through injection
  • Create a session bean client
  • Create a session facade
  • Use dependency injection to locate an EJB
  • Understand the relationship between the EJB container and an EJB component.
  • Describe the life cycle for stateless and stateful session beans
  • Implement session bean life cycle methods
  • Use a session bean to perform asynchronous communication
  • Have fine-grained control over packaging and deployment
Singleton Session Bean
  • Understand the advantages and disadvantages of using a singletion session bean
  • Create a singleton session bean
  • Desribe the life cycle of a singleton session bean
  • Implement singleton session bean life cycle methods
  • Describe singleton concurrency access
  • Implement a concurrency management strategy
Developing Java EE Applications Using Messaging
  • Review JMS technology
  • Describe the roles of the participants in teh JMS API messaging system
  • Create a queue message producer
  • Create a synchronous message consumer
  • Understand the short-comings of using session beans as messaging consumers
  • Describe the properties and life cycle of message-driven beans
  • Create a JMS message-driven bean
  • Create life cycle event handlers for a JMS message-driven bean
  • Configure a JMS message-driven bean
  • Descrie timer services
  • Create a timer notification callback
  • Process a timer notification callback Manage timer objects
  • Describe interceptors and interceptor classes
  • Create a business interceptor method in the enterprise bean class
  • Create an interceptor class
  • Associate multiple business interceptor methods with an enterprise bean
  • Include life cycle callback interceptor methods in an interceptor class
Implementing transactions
  • Describe transaction demarcation management
  • Implement CMT
  • Interact programmatically with an ongoing CMT transaction
  • Implement BMT Apply transactions to messaging
Implementing Security
  • Understand the JavaEE security architecture
  • Authenticate the caller Examine JavaEE authorization strategies
  • Use declarative authorization
  • Use programmatic authorization Examine the responsibilities of the deployer
Using EJB Technology Best Practices
  • Define best practices and state the benefits of using EJB technology best practices
  • Select and apply known patterns to JavaEE application design
  • Incorporate effective exception handling into your JavaEE application design.
Package and Deploy EJB applications

Perform EJB Exception Handling

1Z0-895.- Oracle Certified Expert, Java Platform, Enterprise Edition 6 Enterprise JavaBeans Developer

Tuesday 25 August 2015

Java 8 - Nashorn

One of the new features in Java8 is Nashorn (JSR 292)
It is basically the introduction of an engine to execute javascript in the server side over the JVM.

Over the last years there have been many solutions to execute javascript in the server side. Originally Javascript was used exclusively in the client, but with the emergence of new technologies (some as successful and trendy as node.js) javascript executed in the server is a real option.

My first question when I read about the idea of develop javascript in the server was ... why? what could be the advantage of using javascript in the server side?
If you have been working in web application probably the idea is in your mind...validation. Making validation simple and simplify code could be one of the advantages of this approach. Take into account that one of the principles of a secure development is to validate the data in both client and server.
Another advantage could be the idea of a unique programming language, not splitting anymore in front end/ server side expertise. The third advantage I could think is in re-usability of code routines.

Ok,...and how does it works? Let's see

Calling Javascript function from Java

In this example we will use a javaScript function that validates email format

Now using the js function from java:

We can use javascript in java using these three basic steps:
  • Defining ScriptEngine (see argument "nashorn")
  • Reference our javascript file using eval method.
  • Using invokeFunction or invokeMethod methods from Invocable class to call our javascript.

Saturday 15 August 2015

OCEJWCD Preparing the exam - My experience

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

In this post I will try to summarize how I have completed this certification.

I had been preparing the certification since February. I sat the exam at the end of July, which means seven months preparing the exam. I have to say that it was far away of being full time, because generally I used free time in the weekends and sometimes some hours during the week. There were months I was more focused and others that hardly I could find time. I had previous experience in web applications but it was not an excuse I needed to study and practice.

Materials:

  • Book HeadFirst Servlets & JSP (O'Reilly). Authors: Bryan Basham, Kathy Sierra & Bert Bates.
  • Servlets 3.0 specification (JSR-000315)
  • Whizlabs: OCEJWCD practice test. These test include: Diagnostic test, Practice test(I,II,III) and Final test.

*Note: Initially I was planning to use Enthuware (because is a good relation quality-price, and many people in javaRanch recommends it), but finally I have been using Whizlabs because I had access provided by my company, which is a good point. 
Using whizlabs  you connect to a web platform and you can take the tests (5 mock tests in total, test by section and reporting result). I have to say this platform also helped me a lot in practicing OCPJP7 exam.

- Reading the book the first time:
Reading a chapter carefully until completion, and after that trying to do the questions suggested in the book at the end (generally 6-10 mock questions). Evaluate the errors and read carefully the explanations.
This task was completed intermittently, in several weeks.
The approximately grade of advance was 1 topic per week.
I realized that when I was completing the last sections I hardly remember some details for the firsts chapters, so the most sensible was to start again, so...

- Reading the book the second time:
I started to read the book again. This time I took notes in a notebook, something useful for a quick refresh. This time the reading was more fluent and help me to consolidate concepts.
This time I started to use Whizlabs mock exams by section at the same time I was advancing in studying.

- Further resources
new features included in Servlets 3.0 (annotations, asynchronous application, web fragments) are not included in the book. 

- Trying full mock tests from Whizlabs:
Between June and the beginning of July I completed Dignostic Test, Test1, Test2, Test3.

- Reading the book third time:
This time was a reading marathon. I re-read the entire book in one weekend(15 days before the exam).

- The last week:
I took again the demo test from Enthuware.  (I took the same by February the first time), because I wanted to compare results and progression. The score was good.
I completed the last Mock Test from Enthuware (good result). I focused in the question I failed, and I review the content.
I also reviewed my notes and summaries.

- The big day: 
I had the exam at 10.30, it is recommend to arrive to the Pearson Vue test center with enough time in advance, so I arrived at 10.00. After waiting I was conducted to the exam area. You have to sign a paper and also provide a proof of identity (passport). Then you are taken a picture (not the best face before the exam :) ). 

The exam: I found a different range of questions in terms of difficulty. Some of them quite obvious an other very complex. 
The good thing is that there is plenty of time to finish the exam (not like OCPJP7 that makes time a very important factor). I had enough time to review carefully full exam and also I had time left. 

I found it difficult (but much less than OCPJP7). 

I could check the results after 30 minutes approximately. I received a mail from Oracle, and then I could connect to Oracle CertView page and see the results. I was very nervous because I was not entirely happy with my performance during the exam. Fortunately I passed, not a very impressive result but very happy for passing (it is a big relief).
- Retrospective I can see the improvement after studying.

I decided to start publishing little summaries, diagrams and little pieces of code about the topics in the exam. I hope the posts can be useful but they are far away to be a complete guide to pass the exam. I think is a good way to see if you know the objectives of the exam. For example the book head first is structured in a different way of the current exam for OCEJWCD6

But independently of a test score I feel I have progressed a lot in web knowledge. I have learnt a lot of new things I did not know, even with experience in web applications. That is why my experience with certifications is positive because helps you to make a studying target, and the result is always rewarding.

In my opinion the actual value resides in the time spent reading, practicing and enjoying around areas specific in technology; not in the certification itself. Is a good way to be up to date and to refresh knowledge. I think also you can gain confidence as developer.

My next certification in mind.....probably Oracle certified Expert, Java EE6 Enterprise JavaBeans Developer.

I wish you all the best if you decide to prepare this certification and I hope any of these posts can be useful for you.

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

Saturday 25 July 2015

OCEJWCD-12.Web application security

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

12.1. Understand the role of the container in security

-Authentication
-Authorization
-Confidentiality
-Data integrity

The security should be declared in the deployment descriptor (it is possible to use annotations too).

<security-constraint>

  <web-resource-collection>
    <web-resource-name>EditPage</web-resource-name>
    <url-pattern>/DemoServlet/Edit/*</url-pattern>
    <http-method>POST</http-method>
  </web-resource-collection>

  <auth-constraint>
    <role-name>Admin</role-name>
    <role-name>User1</role-name>
  </auth-constraint>

</security-constraint>

When <role-name>*</role-name> or no auth constraint defined all roles have access to the resources described.

When <auth-constraint/> no roles have access.

12.2. Describe and implement four authentication models

  • BASIC Data is encoded in base64(not encrypted).
  • DIGEST Data is encrypted (not SSL) but no all JEE containers support it.
  • CLIENT-CERT Using Public key certificates. Clients need to have a certificate to use it.
  • FORM Creating a custom login form. Data are sent in http request with no encryption

The authentication type is declared in DD
<login-config>
  <auth-method>FORM</auth-method>

In the Form authentication type the loginPage should be defined (using these three fields: j_security_check, j_username, j_password

<form method="POST" action="j_security_check">
  <input type="text" name="j_username">
  <input type="password" name="j_password">
  <input type="submit" value="Enter">
</form>

12.3. Force the use of encryption between a web application and the client browser.

Annotation ServletSecurity.TransportGuarantee
-NONE
-CONFIDENTIAL: All user data must be encrypted by the transport (typically using SSL/TLS).

@ServletSecurity(@HttpConstraint(transportGuarantee =  TransportGuarantee.CONFIDENTIAL))

12.4. Understand the role of JAAS in pluggable/extensible authentication for web applications

JAAS can be used for two purposes:
  • for authentication of users, 
  • for authorization of users to ensure they have the access control rights required to do the actions performed.
More details about how to athenticate a subject (user or service):

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification