2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library 10. JavaServer Faces Technology 11. Using JavaServer Faces Technology in JSP Pages 12. Developing with JavaServer Faces Technology 13. Creating Custom UI Components 14. Configuring JavaServer Faces Applications 15. Internationalizing and Localizing Web Applications 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes 19. SOAP with Attachments API for Java 21. Getting Started with Enterprise Beans Building, Packaging, Deploying, and Running thecart Example Building, Packaging, and Deploying thecart Example Using NetBeans IDE Running thecart Application Client Using NetBeans IDE Building, Packaging, and Deploying thecart Example Using Ant Running thecart Application Client Using Ant A Web Service Example:helloservice The Web Service Endpoint Implementation Class Stateless Session Bean Implementation Class Building, Packaging, Deploying, and Testing thehelloservice Example Building, Packaging, and Deploying thehelloservice Example Using NetBeans IDE Building, Packaging, and Deploying thehelloservice Example Using Ant Testing the Service without a Client Building, Packaging, Deploying, and Running thetimersession Example Building, Packaging, Deploying, and Running thetimersession Example Using NetBeans IDE Building, Packaging, and Deploying thetimersession Example Using Ant 23. A Message-Driven Bean Example 24. Introduction to the Java Persistence API 25. Persistence in the Web Tier 26. Persistence in the EJB Tier 27. The Java Persistence Query Language 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | Using the Timer ServiceApplications that model business work flows often rely on timed notifications. The timerservice of the enterprise bean container enables you to schedule timed notifications forall types of enterprise beans except for stateful session beans. You can schedulea timed notification to occur at a specific time, after a duration oftime, or at timed intervals. For example, you could set timers to gooff at 10:30 AM on May 23, in 30 days, or every12 hours. When a timer expires (goes off), the container calls the method annotated@Timeoutin the bean’s implementation class. The@Timeout method contains the business logic that handlesthe timed event. TheTimeout MethodMethods annotated@Timeout in the enterprise bean class must returnvoid and takeajavax.ejb.Timer object as the only parameter. They may not throw application exceptions. @Timeoutpublic void timeout(Timer timer) { System.out.println("TimerBean: timeout occurred");}Creating TimersTo create a timer, the bean invokes one of thecreateTimer methods oftheTimerService interface. (For details on the method signatures, see thejavax.ejb.TimerService API documentation.)When the bean invokescreateTimer, the timer service begins to count down thetimer duration. The bean described inThetimersession Example creates a timer as follows: Timer timer = timerService.createTimer(intervalDuration, "Created new timer"); In thetimersession example,createTimer is invoked in a business method, which iscalled by a client. Timers are persistent. If the server is shut down (or even crashes), timersare saved and will become active again when the server is restarted. Ifa timer expires while the server is down, the container will callthe@Timeout method when the server is restarted. TheDate andlong parameters of thecreateTimer methods represent time with theresolution of milliseconds. However, because the timer service is not intended for real-time applications,a callback to the@Timeout method might not occur with millisecond precision. Thetimer service is for business applications, which typically measure time in hours, days,or longer durations. Canceling and Saving TimersTimers can be canceled by the following events:
If a method is invoked on a canceled timer, the container throws thejavax.ejb.NoSuchObjectLocalException. To save aTimer object for future reference, invoke itsgetHandle method andstore theTimerHandle object in a database. (ATimerHandle object is serializable.) Tore-instantiate theTimer object, retrieve the handle from the database and invokegetTimeron the handle. ATimerHandle object cannot be passed as an argument of amethod defined in a remote or web service interface. In other words, remoteclients and web service clients cannot access a bean’sTimerHandle object. Localclients, however, do not have this restriction. Getting Timer InformationIn addition to defining thecancel andgetHandle methods, theTimer interfacedefines methods for obtaining information about timers: public long getTimeRemaining();public java.util.Date getNextTimeout();public java.io.Serializable getInfo(); ThegetInfo method returns the object that was the last parameter of thecreateTimer invocation. For example, in thecreateTimer code snippet of the preceding section, thisinformation parameter is aString object with the valuecreated timer. To retrieve all of a bean’s active timers, call thegetTimers methodof theTimerService interface. ThegetTimers method returns a collection ofTimerobjects. Transactions and TimersAn enterprise bean usually creates a timer within a transaction. If this transactionis rolled back, the timer creation is also rolled back. Similarly, if abean cancels a timer within a transaction that gets rolled back, the timercancellation is rolled back. In this case, the timer’s duration is reset asif the cancellation had never occurred. In beans that use container-managed transactions, the@Timeout method usually has theRequiredorRequiresNew transaction attribute to preserve transaction integrity. With these attributes, the EJB containerbegins the new transaction before calling the@Timeout method. If the transaction isrolled back, the container will call the@Timeout method at least onemore time. Thetimersession ExampleThe source code for this example is in thetut-install/javaeetutorial5/examples/ejb/timersession/timersession-ejb/src/java/ directory. TimerSessionBean is a stateless session bean that shows how to set a timer.In the source code listing ofTimerSessionBean that follows, note thecreateTimerand@Timeout methods. Because it’s a business method,createTimer is defined inthe bean’s remote business interface (TimerSession) and can be invoked by theclient. In this example, the client invokescreateTimer with an interval duration of30,000 milliseconds. ThecreateTimer method creates a new timer by invoking thecreateTimer methodofTimerService. ATimerService instance is injected by the container when the bean iscreated. Now that the timer is set, the EJB container will invoke thetimeout method ofTimerSessionBean when the timer expires, in about 30 seconds. Here’sthe source code for theTimerSessionBean class: package com.sun.tutorial.javaee.ejb;import java.util.logging.Logger;import javax.annotation.Resource;import javax.ejb.Stateless;import javax.ejb.Timeout;import javax.ejb.Timer;import javax.ejb.TimerService;@Statelesspublic class TimerSessionBean implements TimerSession { @Resource TimerService timerService;private static final Logger logger = Logger .getLogger("com.sun.tutorial.javaee.ejb. timersession.TimerSessionBean"); public void createTimer(long intervalDuration) { Timer timer = timerService.createTimer(intervalDuration, "Created new timer"); } @Timeout public void timeout(Timer timer) { logger.info("Timeout occurred"); }}Note -Application Server has a default minimum timeout value of 7000 milliseconds, or 7seconds. If you need to set the timeout value lower than 7000milliseconds, change the value of theminimum-delivery-interval-in-millis element indomain-dir/config/domain.xml. Due to virtual machine constraints,the lowest practical value forminimum-delivery-interval-in-millis is around 10 milliseconds. Building, Packaging, Deploying, and Running thetimersession ExampleYou can build, package, deploy, and run thetimersession example using either NetBeansIDE or Ant. Building, Packaging, Deploying, and Running thetimersession Example Using NetBeans IDEFollow these instructions to build, package, and deploy thetimersession example toyour Application Server instance using NetBeans IDE.
This builds and packages the application intotimersession.ear, located intut-install/javaeetutorial5/examples/ejb/timersession/dist/, deploys thisEAR file to your Application Server instance, and then runs the application client. You will see the output from the application client in the Outputtab: ...Creating a timer with an interval duration of 3000 ms.run-timersession-app-client:run-nb:BUILD SUCCESSFUL (total time: 16 seconds) The output from the timer is sent to theserver.log file located inthedomain-dir/server/logs/ directory. To view this file:
Look for the following line at the bottom ofserver.log: Timeout occurred Building, Packaging, and Deploying thetimersession Example Using AntFollow these instructions to build, package, and deploy thetimersession example toyour Application Server instance using Ant.
Running thetimersession Application Client Using AntTo run the application client, perform the following steps.
The output from the timer is sent to theserver.log file located inthedomain-dir/server/logs/ directory. View the output in the Admin Console:
Alternatively, you can look at the log file directly. After about 30 seconds,openserver.log in a text editor and you will see the following lines: TimerSessionBean: Timeout occurred Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |