Archive for August, 2007

Web space - 262 APPENDIX A n MORE ADVANCED FEATURES APPENDIX

Friday, August 31st, 2007

262 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES ((Collection) stored.get()).add(mailshot); } return false; } Finally, we don t necessarily have enough information to prepare our mailshot the e-mail address may be missing. If the name field actually represents the e-mail address, then we are fine; but if it represents a key into other objects, and hence tables in the database, then we have to be careful. It is possible to write database logic from within an interceptor, but the risk of accidentally recursing back into your interceptor logic is high, so we don t recommend it. It s slightly less tricky if you are only using a session-scoped interceptor, but there are probably safer ways to achieve the same end result. In this example, the methods that we are not using have been given a default implementation. You will note that some of these methods return null or false. These methods are permitted to change the data that is preserved or returned by the session. Returning to the onSave() method, we will consider another possible implementation, shown in Listing A-28. Listing A-28. Changing the Data from Within an Interceptor public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { if( entity instanceof Booking ) { state[1] = “unknown”; } return true; } Here we are altering the state array. This contains the values of each of the objects fields that are to be stored (in the order defined in the mapping file). In our Booking class, field 0is the id, field 1is the name, and field 2is the seat so here we have changed the name value to be preserved in the database. Returning truecauses Hibernate to reflect this change when it saves the data. If we left the return flag as false, nothing would happen when the method was called. The temptation is to assume that returning falseguarantees the safety of the data to be preserved, but, in fact, this is not the case. The state array represents copies of the data to be preserved but we have also been given access to the actual object (entity) that contains the original values. If you amend the fields of the entity before returning, the flag will not prevent your changes from being made. Listing A-29 illustrates how this might occur. Listing A-29. Changing the Data in an Unorthodox Way public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

Web hosting faq - APPENDIX A n MORE ADVANCED FEATURES 261 n

Thursday, August 30th, 2007

APPENDIX A n MORE ADVANCED FEATURES 261 n MORE ADVANCED FEATURES 261 public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { } public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException { return false; } public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { return false; } public void postFlush(Iterator entities) throws CallbackException { } public void preFlush(Iterator entities) throws CallbackException { } } Our interceptor makes use of the afterTransactionBegin() method to prepare to collect booking details, the onSave()method to collect them, and the afterTransactionCompletion() method to report the successful bookings. This sequence guarantees that bookings will not be reported to the users until after we are confident that they have been retained in the database. A minor deficiency of this implementation is that the e-mail is sent outside the transaction a system failure immediately after the commit completes could cause the e-mail not to be sent. In our scenario, this is unimportant, because e-mail is already an unreliable transport mechanism; but there are other situations, such as the auditing example discussed earlier, in which this may be unacceptable. In these cases, interception may not be appropriate, and an integrated solution tied into a two-phase commit transaction may be required. More importantly, our example assumes that the Bookingobject will not be altered between its addition to the set of e-mails to be sent and their transmission. This is an extremely dangerous assumption! A safer approach would be to create copies of the Bookingobjects or, better yet, to copy their data into a more appropriate object, as shown in Listing A-27. Listing A-27. A Better Approach to Preparing the Mailshot public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { if( entity instanceof Booking ) { Booking booking = (Booking)entity. Mailshot mailshot = new Mailshot(booking.getName(), booking.getSeat() );
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

260 APPENDIX A n MORE ADVANCED FEATURES APPENDIX (Best web hosting site)

Thursday, August 30th, 2007

260 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES while (i.hasNext()) { Booking b = (Booking) i.next(); sendMail(b); } } stored.set(null); } public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { ((Collection) stored.get()).add(entity); return false; } private void sendMail(Booking b) { // Here we would actually send out the e-mail System.out.print(”Name: ” + b.getName()); System.out.println(”, Seat: ” + b.getSeat()); } public void beforeTransactionCompletion(Transaction tx) { } public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { return null; } public Object getEntity(String entityName, Serializable id) throws CallbackException { return null; } public String getEntityName(Object object) throws CallbackException { return null; } public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException { return null; } public Boolean isTransient(Object object) { return null; }
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

Post office web site - APPENDIX A n MORE ADVANCED FEATURES 259 n

Wednesday, August 29th, 2007

APPENDIX A n MORE ADVANCED FEATURES 259 n MORE ADVANCED FEATURES 259 Transaction tx = session.beginTransaction(); // Make our bookings… session.save(new Booking(”dave”,”F1″)); session.save(new Booking(”jeff”,”C3″)); // The confirmation letters should not be sent // out until AFTER the commit completes. tx.commit(); } } The interceptor that we are applying is going to capture the information from the Booking objects that we are storing in the database. Listing A-26 demonstrates the basic mechanism, but it is only a toy example. We will discuss some of its deficiencies in a moment. Listing A-26. An Interceptor Implementation package com.hibernatebook.advanced.events; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import org.hibernate.CallbackException; import org.hibernate.EntityMode; import org.hibernate.Interceptor; import org.hibernate.Transaction; import org.hibernate.type.Type; public class BookingInterceptor implements Interceptor { public BookingInterceptor() { } private ThreadLocal stored = new ThreadLocal(); public void afterTransactionBegin(Transaction tx) { stored.set(new HashSet()); } public void afterTransactionCompletion(Transaction tx) { if (tx.wasCommitted()) { Iterator i = ((Collection) stored.get()).iterator();
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.

258 APPENDIX A n MORE ADVANCED FEATURES APPENDIX (Net web server)

Tuesday, August 28th, 2007

258 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES protected String getName() { return name; } protected void setName(String name) { this.name = name; } protected String getSeat() { return seat; } protected void setSeat(String seat) { this.seat = seat; } private String seat; private String name; } Interceptors have to override the org.hibernate.Interceptor interface. You can set a global interceptor for the configuration (see Listing A-25), or you can apply interceptors on a per-session basis. You have to install the interceptor programmatically there is no syntax for specifying this in the Hibernate configuration file. Listing A-25. Installing a Global Interceptor package com.hibernatebook.advanced.events; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class MailingExample { public static void main(String[] argv) { Configuration config = new Configuration(); // Apply this interceptor at a global level… config.setInterceptor(new BookingInterceptor()); SessionFactory factory = config.configure().buildSessionFactory(); Session session = factory.openSession(); // A local interceptor could alternatively // be applied here: // session.setInterceptor(new BookingInterceptor());
You want to have a cheap webhost for your apache application, then check apache web hosting services.

APPENDIX A n (Web hosting uk) MORE ADVANCED FEATURES 257 n

Monday, August 27th, 2007

APPENDIX A n MORE ADVANCED FEATURES 257 n MORE ADVANCED FEATURES 257 Name When Invoked Comments onFlushDirty() Invoked during a call to flush() after entities have been determined to be dirty. (If the entities are not dirty, then there are no changes to be persisted and Hibernate has no actions to perform therefore, there is no general case interceptor, and this interceptor will not be invoked if the entities are clean.) onLoad() Invoked immediately before an entity object is populated from the database. The loading can be overridden (by returning false), and the instantiated but uninitialized object is available if supplementary initialization from the listener is needed. onSave() Invoked before an object is saved. This permits the state of the object to be changed immediately before it is saved. postFlush() Invoked after the Session object is flushed, if and only if the Session object had to carry out SQL operations to synchronize state with the database. preFlush() Invoked immediately before the Session object is flushed. An Example Interceptor To illustrate how all this works in practice, we will create a simple interceptor from scratch. While the auditing example is a good one, it is rather too involved for our demonstration. Instead, we will consider a concert hall seat-booking system (the entity to represent an entity is shown in Listing A-24) for which the details of bookings will be sent out to customers as they are pushed into the database. Listing A-24. The Booking POJO package com.hibernatebook.advanced.events; public class Booking { public Booking(String name, String seat) { this.name = name; this.seat = seat; } Booking() { }
Check Tomcat Web Hosting services for best quality webspace to host your web application.

256 APPENDIX A n MORE ADVANCED FEATURES APPENDIX (Web site construction)

Sunday, August 26th, 2007

256 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES Financial packages often require considerable auditing information to be maintained to prevent fraud and aid accountability. Auditing is a natural candidate for implementation as an interceptor, as it would normally require that no changes be made to the persistence process at all. The question that usually arises when discussing interceptors is why not use triggers? Triggers should never embody application logic, only business logic. If any application is going to have audit-free access to the database, you cannot implement the auditing in trig gers. Worse, the triggers may not have access to the user information that s needed. In most multi-tier situations, the need to pool the database connections precludes establishing indi vidual user logins to the database. So, for example, the trigger would only know that a user with the login MonolithicApplication carried out an update of last year s sales figures not that it was carried out by, say, Jim from accounts, which is who the auditors are likely to be interested in! Table A-2 summarizes the points in the application life cycle at which the vari ous methods will be invoked. Table A-2. The Interceptor Methods Name When Invoked Comments afterTransactionBegin() Invoked immediately after a call to begin() on a Transaction object retrieved from the Sessionobject. This method can change the state of the transaction for example, it can call rollback(). afterTransactionCompletion() Invoked immediately after the completion of a transaction. beforeTransactionCompletion() Invoked immediately prior to the completion of a transaction. This method can change the state of the transaction for example, it can call rollback(). findDirty() Invoked during calls to flush(). This allows the saving of changes to attributes to be prevented or forced. getEntity() Invoked when an entity not in the Session object s own cache is requested by its identifier. getEntityName() Invoked when the Session object needs to determine the name of a given entity. instantiate() Invoked when the Session object needs to create an entity instance. Because the empty object can be created here, this allows Hibernate (in legacy applications, for example) to use entities that do not have a default constructor. isTransient() Invoked when the Session object needs to determine whether an entity it has been asked to persist is transient for example, during calls to saveOrUpdate(). onDelete() Invoked before an object is deleted. The object s state should not be tampered with at this point.
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

Linux web host - APPENDIX A n MORE ADVANCED FEATURES 255 n

Saturday, August 25th, 2007

APPENDIX A n MORE ADVANCED FEATURES 255 n MORE ADVANCED FEATURES 255 Listing A-23. The Implementation of an Event Listener package com.hibernatebook.advanced.events; import java.io.Serializable; import org.hibernate.HibernateException; import org.hibernate.event.SaveOrUpdateEvent; import org.hibernate.event.def.DefaultSaveOrUpdateEventListener; public class BookingSaveOrUpdateEventListener extends DefaultSaveOrUpdateEventListener { public Serializable onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException { if( event.getObject() instanceof Booking ) { Booking booking = (Booking)event.getObject(); System.out.println(”Preparing to book seat ” + booking.getSeat()); if( booking.getSeat().equalsIgnoreCase(”R1″)) { System.out.println(”Royal box booked”); System.out.println(”Conventional booking not recorded.”); // By returning null instead of invoking the // default behavior we prevent the invocation // of saveOrUpdate on the Session from having // any effect on the database! return null; } } // The default behavior: return super.onSaveOrUpdate(event); } } Interceptors Interceptors are privy to a blow-by-blow account of what is going on as Hibernate carries out its duties. While you can listen in, you can only make limited changes to the way in which Hibernate actually behaves. This is the common requirement; unless you are making substantial changes to the persistence behavior, you will usually want only to track what is going on.
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

254 APPENDIX A n MORE ADVANCED (Web hosting india) FEATURES APPENDIX

Friday, August 24th, 2007

254 APPENDIX A n MORE ADVANCED FEATURES APPENDIX A n MORE ADVANCED FEATURES An Example Event Listener Before we get stuck in a simple example, a word of caution: events are very much an exposed part of the inner workings of the Session. While this is ideal for something requiring the level of interference of a security tool, you will not need this for most purposes. Listing A-22 is more in the nature of an illustrative hack than a real solution. In a real application, you would probably solve this particular problem either within the body of the application, by using interceptors, or by using triggers. Listing A-22 shows how an event listener could be used to prevent the booking of certain seats from being persisted to the database in a concert hall ticket booking application (we revisit this example application in a little more detail with a slightly more realistic scenario in the later section, Interceptors ). Listing A-22. Programmatically Installing an Event Listener public class EventExample { public static void main(String[] args) { Configuration config = new Configuration(); // Apply this event listener (programmatically) config.setListener(”save-update”, new BookingSaveOrUpdateEventListener()); SessionFactory factory = config.configure().buildSessionFactory(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); // Make our bookings… seat R1 is NOT to be saved. session.saveOrUpdate(new Booking(”charles”,”R1″)); session.saveOrUpdate(new Booking(”camilla”,”R2″)); // The confirmation letters should not be sent // out until AFTER the commit completes. tx.commit(); } } Our example is only going to implement the SaveOrUpdateEventListener interface. You will notice that in Listing A-22, the original calls to save() have been replaced with calls to saveOrUpdate(). There is a close correspondence between the methods on the Session interface and the event listeners with similar names. A call to save() will not invoke saveOrUpdate(), and vice versa. Try using the save() method in the EventExample, and you will see that the BookingSaveOrUpdateListener is not invoked. In Listing A-23, we present the logic of the listener registered in Listing A-22.
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.

APPENDIX A n MORE ADVANCED FEATURES 253 n (Cpanel web hosting)

Thursday, August 23rd, 2007

APPENDIX A n MORE ADVANCED FEATURES 253 n MORE ADVANCED FEATURES 253 Type Name Listener pre-delete PreDeleteEventListener pre-insert PreInsertEventListener pre-load PreLoadEventListener pre-update PreUpdateEventListener refresh RefreshEventListener replicate ReplicateEventListener save-update SaveOrUpdateEventListener So, for example, your listener for the SaveOrUpdateEvent is mapped to the type name save-update, must implement the SaveOrUpdateEventListener interface, and would normally have been implemented by the DefaultSaveOrUpdateEventListener class. It is wise to follow a similar convention with your own naming, so your mapping file listener entry might read like this:
Alternatively, a programmatic registration of the same event would be given thus: Configuration config = new Configuration(); config.setListener(”save-update”, new BookingSaveOrUpdateEventListener()); Because they override the default behavior, events are suitable for situations in which you want to fundamentally change the Session s behavior particularly if you want to prevent a certain event from being processed. Probably the best example of this requirement is in authorizing access to the database, and, in fact, Hibernate provides a set of event listeners for just this purpose. The four events listeners in question override the PreDelete, PreUpdate, PreInsert, and PreLoad listeners. The logic in each case (in pseudocode) runs something like this: if( user does not have permission ) throw RuntimeException Invoke default listener Because events are invoked in the same thread as the user s call to the session, the result of an exception in the first step will be an exception (actually a security exception) as the unprivileged user carries out the relevant operation. To enable policy configuration of security, you would add the following:
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.