001    package net.databinder.components.hib;
002    
003    import net.databinder.hib.Databinder;
004    
005    import org.apache.wicket.Page;
006    import org.apache.wicket.markup.html.link.BookmarkablePageLink;
007    import org.apache.wicket.model.IModel;
008    
009    /**
010     * Boomarkable link with object identifier set automatically from the attached object.
011     * @author Nathan Hamblen
012     */
013    public class PageSourceLink extends BookmarkablePageLink {
014            private String idParameter;
015            /**
016             * Construct a link to a page using the model object's Hibernate identifier set to the
017             * "id" parameter.
018             * @see #setParameters()
019             * @param id component id
020             * @param pageClass target page class
021             * @param model model to bind to component
022             */
023            public PageSourceLink(String id, Class pageClass, IModel model) {
024                    this(id, pageClass, model, null);
025            }
026            /**
027             * Construct a link to a page using the model object's Hibernate identifier set to the
028             * given identifier parameter.
029             * @param id component id
030             * @param pageClass target page class
031             * @param model model to bind to component
032             * @param idParameter name for identifying parameter
033             */
034            public PageSourceLink(String id, Class pageClass, IModel model, String idParameter) {
035                    super(id, pageClass);
036                    setModel(model);
037                    this.idParameter = idParameter == null ? "id" : idParameter;
038            }
039            /**
040             * @return true if pointing to a different page class than the current and a different model object
041             */
042            @Override
043            public boolean isEnabled() {
044                    Page thisPage = getPage();
045                    if (!getPageClass().isInstance(thisPage))
046                            return true;
047                    Object o = getPage().getModelObject();
048                    return o == null || !o.equals(getModelObject());
049            }
050            /** Calls setParameters() */
051            @Override
052            protected void onBeforeRender() {
053                    super.onBeforeRender();
054                    setParameters();
055            }
056            /** Sets the id parameter to  the identifier given by Hibernate*/
057            protected void setParameters() {
058                    setParameter(idParameter, 
059                                    Databinder.getHibernateSession().getIdentifier(getModelObject()).toString());
060            }
061    }