Showing posts with label Java Certification. Show all posts
Showing posts with label Java Certification. Show all posts

Sunday, 30 October 2016

OCEJBCD - Package and Deploy EJB applications

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

Package and Deploy EJB applications

EJB3 bean classes are packaged in regular JAR files.

The javabeans configuration can be defined with annotations or using a deployment descriptor ejb-jar that will be located under META-INF folder:
  • META-INF
    • ejb-jar.xml
    The configuration specified in the descriptor will override the configuration specified by annotations.


    The JAR generated will be placed under lib folder in the WAR generated for the application.

    • WAR
      • WEB-INF
        • lib
          • ejbModule.jar



      Example of deploying an EJB project in a Glassfish server using Eclipse in this post .


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

      Sunday, 23 October 2016

      OCEJBCD - Perform EJB Exception Handling

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

      EJB container considers two exception types:

      • System Exceptions
      • Application Exceptions


      System Exceptions .- internal errors

      • EJBException is a subclass of java.lang.RuntimeException
      • They always cause a rollback in transactions.
      • Runtime exceptions are unchecked exceptions, so they are thrown from the method (not need to throws or try/catch clauses)
      • Way the container hands system exceptions:
        • Roll back transaction
        • Log exception
        • Discard EJB instance
      • The EJB wraps the exception into RemoteException and throws it to the client.
      • If the client started the application and it was propagated to the EJB, the system exception will be rethrown as EJBTransactionRolledbackException

      Application Exceptions.- errors in the business logic

      • The do not cause a rollback by default. To rollback the transaction automatically it can be used the annotation @ApplicationException(rollback=true), or doing it explicity with a call the method setRollbackOnly()
      • They are sent to the client directly. The container does not wrap the exception.

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

      Sunday, 9 October 2016

      OCEJBCD -11. Implementing Security

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

      11.1. Understand the JavaEE security architecture

      -Declarative security (using deployment description and annotations)
      -Programmatic security

      More details in securing java beans section from javaEE tutorial. 


      11.2. Authenticate the caller 

      Authenticate on a remote EJB can be done by JNDI:

      properties.put(Context.SECURITY_PRINCIPAL, "usename");
      properties.put(Context.SECURITY_CREDENTIALS, "password");

      Context jndiContext =  new InitialContext(properties);
      Object ref = jndiContext.lookup("SecureBean/remoteObject");

      11.3. Examine JavaEE authorization strategies

      Details about web application security can be review here.

      • Basic Authentication

      Data is encoded in base64 (not encrypted).


      • Form-based authentication

      Creating a custom login form.
      data are sent in http request with no encryption.

      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>



      • Digest authentication

      Data is encrypted (not SSL) but not all JEE containers support it.


      • Client authentication

      Using Publick Key Certificates
      Clients need to have a certificate to use it.


      • Mutual authentication
      The server and client authenticate each other. It can be certificate based or user/password based.

      11.4. Use declarative authorization

      Annotations:

      @DeclareRoles (class level)
      @RolesAllowed (class or method level)
      @PermitAll(class or method level)
      @DenyAll (class or method level)

      These annotations can be used at class or method level. At class level means that those roles will be applied to all the method in the class. The annotation at method level will override the class annotation.



      Java Security identity between the client and EJBcontainer is the identity of the caller.

      Propagating security between EJB containers by default will be the identity of the caller, but also can be specified configuring the bean with annotation(@RunAs("nameOfTheRole"))

      Message-driven beans have only @Run As as identity, they are not allowed to use method permissions or execute under caller identity.

      11.5. Use programmatic authorization 

      Methods from javax.ejb.EJBContext

      -getCallerPrincipal()

      -isCallerInRole("role")

      11.6. Examine the responsibilities of the deployer

      To override security annotations at deployment time it can be used security elements in the deployment descriptor.

      The deployer customises an EJB for a specific operational environment and deploy it into the server.
      Interprets the deployment descriptor from the application assembler and the bean provider and knows the security roles and users for this system.


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

      Sunday, 2 October 2016

      OCEJBCD -10. Implementing transactions

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

      10.1. Describe transaction demarcation management

      JTA (Java Transaction API).

      Transaction demarcation involves indicating when a transaction begin and ends.

      There are three kind of demarcation management:

      • Bean managed
      • Container managed (by default)
      • Client managed

      10.2. Implement CMT

      CMT (Container Managed transaction)

      Transaction attributes

      Transactions attributes can be used at class or method level.

      • Required
      @TransactionAttribute(REQUIRED)
      Start transaction or continue with client transaction.
      • RequiresNew
      @TransactionAttribute(REQUIRES_NEW)
      Start new transaction (stop client and resume later).


      • Mandatory
      @TransactionAttribute(MANDATORY)
      Always with client transaction, if not throws an exception


      • Not supported
      @TransactionAttribute(NOT_SUPPORTED)
      No transaction (if client running within trans stop and resume later)


      • Supports
      @TransactionAttribute(SUPPORTS)
      Bean runs within client transaction if related only.


      • Never
      @TransactionAttribute(NEVER)



      10.3. Interact programmatically with an ongoing CMT transaction

      A transaction will rollback automatically in CMT when a system exception ocurrs. It can be invoked by setRollbackOnly() method.

      Methods not allowed in CMT are ( commit, rollback, getUserTransaction...)

      10.4. Implement BMT Apply transactions to messaging

      @TransactionManagement(BEAN)

      Use of commit, rollback, getUserTransaction(setTransactionTimeout..etc)
      Not allowed get/setRollbackOnly()

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

      Sunday, 28 August 2016

      OCEJBCD -9.Implementing Interceptor Classes and Methods

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

      9.1. Describe interceptors and interceptor classes

      An interceptor is a class used to intercept calls to EJB.

      They are usually used for logging, authentication or validation purposes.

      A typical example can be logging at the beginning and end of a method. This can be a tedious task, imagine to create logging entries for a big application. With interceptors it is avoided this duplicity of code, only specifying this behaviour in an interceptor class and used by annotations in the classes of your application.

      The interceptor can be used by all methods of the class if we annotate our bean with :
      @Interceptors(MyInterceptor.class)
      We can apply more than one interceptor separating list with comma:
      @Interceptors(MyInterceptor1.class, MyInterceptor2.class)

      Or we can define which methods will be intercepted with annotations at method level with: 
      @Interceptors(MyInterceptor.class)

      Also we can exclude class interceptors to be executed in some methods with:
      @ExcludeClassInterceptors


      9.2. Create a business interceptor method in the enterprise bean class

      Also we can define an interceptor method inside the bean class. 
      This interceptor method will be the last one to be invoked before the actual bean method:



      2016-08-28T10:50:05.833+0100|Info: Entering method:public void example.TestBean.firstMethod()
      2016-08-28T10:50:05.833+0100|Info: Leaving method:public void example.TestBean.firstMethod()

      9.3. Create an interceptor class


      There are three kinds of interceptor method:
      • method interceptor methods for methods of a target class.
        • @AroundInvoke
      • timeout method interceptor methods for timeout methods of a target class 
        • @AroundTimeout
      • lifecycle callback interceptor methods : 
        • @PostConstruct and @PreDestroy 
        • (and for @PrePassivateand @PostActivate methods of EJB stateful session beans).



      9.5. Associate multiple business interceptor methods with an enterprise bean


      Applying the interceptor class defined in the previous section to our test bean. In the output log we can verify that two interceptors method are being invoked for firstMethod: first the interceptor at class level, and second the one at method level.
      The second method will be called only by the interceptor at bean method due to annotation of excluding class interceptors.




      2016-08-28T11:07:55.689+0100|Info: **Begin public void example.TestBean.firstMethod()
      2016-08-28T11:07:55.689+0100|Info: Entering method:public void example.TestBean.firstMethod()
      2016-08-28T11:07:55.689+0100|Info: Leaving method:public void example.TestBean.firstMethod()
      2016-08-28T11:07:55.689+0100|Info: **End public void example.TestBean.firstMethod()
      2016-08-28T11:07:55.689+0100|Info: Entering method:public void example.TestBean.secondMethod()

      2016-08-28T11:07:55.689+0100|Info: Leaving method:public void example.TestBean.secondMethod()

      9.6. Include life cycle callback interceptor methods in an interceptor class
      The lifecycle of an interceptor instance is the same as that of the target class instance with which it is associated.

      @PostConstruct @PreDestroy
      public void interceptLifeCycle(InvocationContext ctx){...

      This callbacks can be used to initialize the state of the bean.
      Because callbacks have not return value, the return type must be void.

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

      Saturday, 26 March 2016

      OCEJBCD -8.Using Timer Services

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

      8.1. Describe timer services

      Timer services is a service of scheduling notifications in the bean container.
      (Available for all bean types except from stateful session beans).

      Timers services can be created 
      -Programmatically, using TimerService interface
      -By annotations @Schedule

      Functionality that a bean with timer services can perform:
      • Create a timer notification callback
      • Process a timer notification callback
      • Manage timer objects (list notification, cancel timer etc...)




      The timers can be classified as:
      • Single notifications
      • Interval (multiple notifications at specified interval)
      • Calendar based schedule 
        • second, minute, hour 
        • dayOfWeek, dayOfMonth
        • month
        • year
        • Expressions : wildcard (*), list(,), range(-),intervals(/)

      8.2. Create a timer notification callback
      • By timerService interface
        • Single:
                Timer timer = timerService.createSingleActionTimer(data, new             TimerConfig());
        • Calendar based: using javax.ejb.ScheduleExpression
                ScheduleExpression schedule = new ScheduleExpression();
                schedule.dayOfMonth("1,Last");//first and last day of the month
                Timer timer = timerService.createCalendarTimer(schedule);

             When a timer expires the container calls the bean's method annotated              with @Timeout (*Note: this method must return void and the argument is optional).

      • By annotation
             Example : @Schedule(dayOfWeek="Mon", hour="0")

      8.3. Process a timer notification callback 

      Example with timerService interface

      To execute this bean we need to make a call from a client (for example a servlet class) to the method setTimer that indicates the milliseconds after the timeout will happen: scheduleBean.setTimer(30000);

      Results in server console:
      2016-03-26T11:58:33.313+0000|Info: TestBean was successfully deployed in 362 milliseconds.
      2016-03-26T12:00:26.816+0000|Info: the next timeout is programed Sat Mar 26 12:00:56 GMT 2016 happening in 29968 milliseconds

      2016-03-26T12:00:56.787+0000|Info: Timeout occurred

      Example with schedule annotation
      The following example is a stateless session bean, with a timer scheduled every 1 min.
      When it is deployed in the server, after 1 minute the timeout method is called:

      Results in server console:
      2016-03-26T10:03:00.001+0000|Info: Automatic timeout occured
      2016-03-26T10:04:00.002+0000|Info: Automatic timeout occured
      2016-03-26T10:05:00.001+0000|Info: Automatic timeout occured
      2016-03-26T10:06:00.002+0000|Info: Automatic timeout occured
      2016-03-26T10:07:00.002+0000|Info: Automatic timeout occured

      8.4. Manage timer objects

      -Cancel() - cancel a timer
      -getHandle() - obtain a serializable object
      -getTimeRemaining()
      -getNextTimeout()
      -getInfo()

      When using container-managed transactions @Timeout can use attributes: Required or RequiredNew to preserve transaction integrity, which means that in case of rollback the timeout will be reset.

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

      Sunday, 28 February 2016

      OCEJBCD -7.Developing Message-Driven Beans

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

      7.1. Understand the short-comings of using session beans as messaging consumers

      Using a session bean as consumer has the problem of blocking server resources, because it will be a synchronous process (instead of asynchronous processing with message-driven bean ).

      Using session bean receive() method will block the thread indefinitely until the message becomes available :

      Message m = consumer.receive()

      How to handle the blocking synchronous problem with session bean? Using a timed synchronous receive.

      A parameter can be used to indicate the time waiting the message to arrive:
      Message m = consumer.receive(1); //time in milliseconds
      Message m = consumer.receiveNoWait();

      See an example of Writing the Clients for the Synchronous Receive.

      7.2. Describe the properties and life cycle of message-driven beans




      7.3. Create a JMS message-driven bean


      To create a message-driven bean the bean class:
      • is annotated with @MessageDriven
        • @ActivationConfigProperty Settings(*):
          • Acknownledge_Mode
            • Auto-Acknownledge
            • Client-Acknownledge
            • Dups-ok-aknownledge
          • DestinationType
            • Queue
            • Topic
          • Subscription durability
            • Durable
            • Non-durable
          • ClientId
          • SusbscriptionName
          • MessageSelector 
          • AddressList
      • implements MessageListener inteface
      • overrides onMessage() method

      (*)Example of @ActivationConfigProperty configuration:
      @MessageDriven(mappedName = "jms/Topic", activationConfig =  {
          @ActivationConfigProperty(propertyName = "messageSelector",
                  propertyValue = "NewsType = 'Sports' ")
          , @ActivationConfigProperty(propertyName = "subscriptionDurability",
                  propertyValue = "Durable")
          , @ActivationConfigProperty(propertyName = "clientId",
                  propertyValue = "MyID")
          , @ActivationConfigProperty(propertyName = "subscriptionName",
                  propertyValue = "MySub")
          })

      There is an example of a message-driven bean class at the last section of this post.

      7.4. Create life cycle event handlers for a JMS message-driven bean

      See this post : Configuring a JMS environment, to know how to configure a server and include jms resources as connection factory and destination

      Once the connection factory and the destination(Queue or topic) have been created, we can use dependency injection to use them in our message beans
      like:
      • Connection factory
      @Resource(name="jms/MyConnectionFactory")
      private QueueConnectionFactory connectionFactory;
      • Destination
      @Resource(name="jms/MyQueue")

      private Queue queue;

      With the connectionFactory we can define the context to create the producer and the consumer.
      • Connection and Session
      Connection con = connectionFactory.createConnection();
      Session session = con.createSession(true,0);
      • MessageProducer
      MessageProducer producer = session.createProducer(topic);
      • Message types(TextMessage, MapMessage, ObjectMessage and others).
      TextMessage message = session.createTextMessage();


      7.5. Configure a JMS message-driven bean

      Here is an example of using a message-driven bean:

      • A client where the user request to send a message (with a jsp page and a servlet, in the same way as examples described in previous posts : calling a session bean from a servlet).
      • A session bean (stateless) that will define a producer that put the message in the JMS queue.
      • A message-driven bean that will consume the message from the queue.


      Session bean:

      Message bean:

      When executing the application in our configured server:
      Write a message in the textarea and submit the message.
      In the log can be read the producer sending the message and the consumer receiving it:
      producer sends the message...
      consumer receives message...

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

      Saturday, 13 February 2016

      Java Web Component Developer Certification OCEJWCD at a glance

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

      This post a is summary of info related Oracle JavaEE6 web component certification with all info available in this blog and other useful links:

      Topics:


    • Exam:

      Further resources:

      • Books. I used HeadFirst Servlets & JSP (O'Reilly), but there are others like OCEJWCD Study Companion recommended in javaRanch.                    
      • Servlets 3.0 specification. You can download the JSR-000315 from here      
      • Java EE 6 API here                                                                                           
      • MockExams: 
        • Enthuware : there is trial version and full version.
        • Whizlabs : there is a free test and tests under purchase.



      Good luck!

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

      Sunday, 31 January 2016

      OCEJBCD -6.Developing Java EE Applications Using Messaging

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

      6.1. Review JMS technology

      JMS (Java Messaging Service) is an API to send/receive messages :

      1) Asynchronously:
      JMS works asynchronously because it sends messages to the client without a previous request, also it sends messages without having to wait for a reply.

      2) Loosely coupled: 
      Provides vendor-independent access to messaging systems.

      Messaging domain types:

      • Point to point :
        • Every message has a consumer
        • The messages are requested from the queue by the consumer.

      • Publish/Subscribe 
        • Every message has several consumers
        • The messages are pushed to the consumers without requesting.

        6.2. Describe the roles of the participants in the JMS API messaging system

      Components is a JMS system:
      • JMS Provider.- The messaging system
      • JMS Clients .- Any java component that is producer or consumer of messages
        • Producer
        • Consumer(Listener and selectors)
      • Messages .- the objects that contain the information.
      • Administered objects.- Destinations and connection factories.
      • Session.- single threaded context.
      • Connection.- connection with JMS provider.
      • Queue browsers.
      • Exception handling .


      6.3. Create a queue message producer
      MessageProducer producer = session.createProducer(queue);
      producer.send(message);
      See JMS message producer from the oracle java EE tutorial

      6.4. Create a synchronous message consumer
      MessageConsumer consumer = session.createConsumer(queue);
      connection.start();
      Message m = consumer.receive();
      See JMS message consumer from the oracle java EE tutorial

      The message can be consumed synchronously or asynchronously. 
      - synchronously : the consumer call the receive() method, that blocks until the message arrives
      - asynchronously : the consumer call the onMessage() message listener method.

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

      Monday, 18 January 2016

      OCEJBCD -5. Singleton Session Bean

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

      5.1. Understand the advantages and disadvantages of using a singleton session bean

      A singleton is a stateless bean whose instance is accessed by all request in the application. Singletons have to be thread safe in order to manage the concurrently access.

      Advantages:
      - Only one instance. The bean will be created when the application is started and will exist during all application life.

      Disadvantages:
      - Could cause bottle-neck and performance, if it is not handle accurately.

      5.2. Create a singleton session bean
      javax.ejb.Singleton 
      @Singleton
      public class SingletonBean { ... }
      
      
      
      
      
      
      Other annotations that can be used with singleton are:
      
      
      
      
      @Startup (For eager initialization; it means the instance will be created at deployment time)
      
      
      @DependsOn (For adding dependencies)

      5.3. Describe the life cycle of a singleton session bean


      5.4. Implement singleton session bean life cycle methods

      For a full example using singleton see last section of this post.

      5.5. Describe singleton concurrency access

      Singleton beans are designed for concurrency access. There are two ways to manage concurrency.
      • Container-managed concurrency (by default)
      • Bean-managed concurrency
      Example:
      @ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
      @Singleton
      public class ExampleSingletonBean {...}

      For managing concurrrency, there are the following annotations to lock blocks of code:

      @Lock(LockType.READ)
      @Lock(LockType.WRITE)

      5.6. Implement a concurrency management strategy

      The following example describes the use of a singleton bean called by a servlet in order to get a random number in the page after clicking a button.

      The method that gets the random number can be accessed concurrently and the value will be consistent from different client accesses.

      Bean class:

      Servlet class:
      JSP:
      After running the application in the server, when the page is opened in a browser the first time:

      If we open another browser (emulating another client), the request accesses the same value of the counter. The counter value is going to be shared by all the requests:
      OCEJBCD (SCBCD) - 1Z0-895 - Enterprise JavaBeans Developer Certification