Wednesday, February 6, 2013

JSF Logged Interceptor


Logged JavaEE Interceptor for JSF logging

import java.io.Serializable;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

/**
 *
 * @author happyFace
 */
@Logged
@Interceptor
public class LoggedInterceptor implements Serializable {

    public static final Logger LOGGER = Logger.getLogger(LoggedInterceptor.class.getName());
    public LoggedInterceptor() {
    }

    @AroundInvoke
    public Object logMethodEntry(InvocationContext invocationContext)
            throws Exception {
        LOGGER.log(Level.INFO, "Entering method: {0} in class {1} at Time {2}.",
                new Object[]{invocationContext.getMethod().getName(),
                    invocationContext.getMethod().getDeclaringClass().getName(),
                    new Date()});
        return invocationContext.proceed();
    }
//}  
}
---------------------------------------------------------------------------


import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;

/**
 *
 * @author happyFace
 */

@Inherited
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Logged {
}


--------------------------------------------------------------------------------------
import java.security.Principal;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.interceptor.Interceptors;

/**
 *
 * @author happyFace
 */
@Named
@ViewScoped
@Interceptors({ LoggedInterceptor.class})
public class Index {
    private String name = "Get A Lawyer";

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    
    public String logout(){
        Principal userPrincipal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
        System.out.println("Principal: "+userPrincipal);
        return "login?faces-redirect=true";
    }
    
}

JSF Managed Bean Session Logout

Session Logout Code For JSF With Faces-Redirect


From http://stackoverflow.com/questions/2206911/best-way-for-user-authentication-on-javaee-6-using-jsf-2-0

<h:form>
    <h:outputLabel for="username" value="Username" />
    <h:inputText id="username" value="#{auth.username}" required="true" />
    <h:message for="username" />
    <br />
    <h:outputLabel for="password" value="Password" />
    <h:inputSecret id="password" value="#{auth.password}" required="true" />
    <h:message for="password" />
    <br />
    <h:commandButton value="Login" action="#{auth.login}" />
    <h:messages globalOnly="true" />
</h:form>



@ManagedBean
@ViewScoped
public class Auth {

    private String username;
    private String password;
    private String originalURL;

    @PostConstruct
    public void init() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

        if (originalURL == null) {
            originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
        } else {
            String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

            if (originalQuery != null) {
                originalURI += "?" + originalQuery;
            }
        }
    }

    @EJB
    private UserService userService;

    public void login() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

        try {
            request.login(username, password);
            User user = userService.find(username, password);
            externalContext.getSessionMap().put("user", user);
            externalContext.redirect(originalURL);
        } catch (ServletException e) {
            // Handle unknown username/password in request.login().
            context.addMessage(null, new FacesMessage("Unknown login"));
        }
    }

    public void logout() throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        externalContext.invalidateSession();
        externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
    }

    // Getters/setters for username and password.
}




public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login?faces-redirect=true";
}


This is for getting the principal

FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();

JSF CommandLink JQuery Call To BootStrap Modal

JSF h:commandLink with JQuery onclick BootStrap modal.

<h:commandLink onclick="$('#myModal1').modal('show'); return false;" value="Launch Modal"/>


Modal

<br />
<div class="modal hide fade" id="Modal" style="display: none;">
<div class="modal-header">
<a class="close" data-dismiss="modal" href="http://www.blogger.com/blogger.g?blogID=5930143319420917182#">×</a>
              <br />
<h3>
Action!</h3>
</div>
<div class="modal-body">
Item Name: #{item.name}<br />
Item Location: #{item.name2}</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal" href="#">Cancel</a>
           
              <h:commandlink action="#{bean.method}" styleclass="btn btn-danger btn-small" value="Delete">
            </h:commandlink></div>
</div>