Saturday, January 7, 2012

CDI Bean Example

We have seen our main bean MainSampleViewBean.java when we discussed JSF Bean Basics, and we have explored our EJBs handling our persistence layer, but now, we need to implement the rest of the presentation logic.  We do that with a three more beans.  Most of the concepts presented in these beans have already been discussed.  So, now we need to discuss the logic and the interaction with the view, but without seeing the view, the discussion will be a bit lacking.  I present the beans here, but we will go through the logic as we process the JSF page.


One thing to note is the @Dependent scope.  The two beans with that annotation are dependent on the MainSampleViewBean and will be injected into it when it is created.

OrderBean.java

package com.sample.beans;
import com.sample.entities.OrderEntity;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;
import org.primefaces.context.RequestContext;
/**
 * CDI Bean to manage an order
 * @author Thomas Dias
 */
@Named(value = "orderBean")
@SessionScoped
public class OrderBean implements Serializable {
    private OrderEntity selectedOrder, newOrder;
    private List<OrderEntity> orders;
    private boolean nameValid;
    private String otherName;
    private String msg = "Starting Message";
    @Inject
    private MainSampleViewBean mainSampleViewBean;
    /** Creates a new instance of OrderBean */
    public OrderBean() {
    }
    @PostConstruct
    public void init() {
        orders = mainSampleViewBean.getOrderEntityFacade().findAll();
        newOrder = new OrderEntity();
        nameValid = false;
        if (!orders.isEmpty()) {
            setSelectedOrder(orders.get(0));
            open(null);
        }
    }
    public void open(ActionEvent event) {
        if (selectedOrder != null) {
            mainSampleViewBean.orderSelected(selectedOrder);
        }
    }
    public MainSampleViewBean getMainSampleViewBean() {
        return mainSampleViewBean;
    }
    public void setMainSampleViewBean(MainSampleViewBean mainSampleViewBean) {
        this.mainSampleViewBean = mainSampleViewBean;
    }
    public OrderEntity getSelectedOrder() {
        return selectedOrder;
    }
    public void setSelectedOrder(OrderEntity selectedOrder) {
        this.selectedOrder = selectedOrder;
    }
    public List<OrderEntity> getOrders() {
        return orders;
    }
    public void setOrders(List<OrderEntity> orders) {
        this.orders = orders;
    }
    public void deleteOrder(ActionEvent event) {
        if (selectedOrder == null) {
            return;
        }
        if (selectedOrder.equals(mainSampleViewBean.getOrderEntity())) {
            mainSampleViewBean.orderSelected(null);
        }
        mainSampleViewBean.getOrderEntityFacade().remove(selectedOrder);
        this.orders.remove(selectedOrder);
        selectedOrder = null;
    }
    public void createOrder(ActionEvent event) {
        if (newOrder.getName() != null) {
            this.mainSampleViewBean.getOrderEntityFacade().create(newOrder);
            this.mainSampleViewBean.orderSelected(newOrder);
            RequestContext.getCurrentInstance().
                    addCallbackParam("valid", true);
        }
    }
    public OrderEntity getNewOrder() {
        return newOrder;
    }
    public void setNewOrder(OrderEntity newOrder) {
        this.newOrder = newOrder;
    }
    public boolean isNameValid() {
        return nameValid;
    }
    public void setNameValid(boolean nameValid) {
        this.nameValid = nameValid;
    }
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if (value == null || value.toString().isEmpty()) {
            FacesMessage message = new FacesMessage("A Unique Name Less Then 21 Characters Must Be Supplied");
            setNameValid(false);
            throw new ValidatorException(message);
        }
        OrderEntity orderEntity = mainSampleViewBean.getOrderEntityFacade().findByName(value.toString());
        if (orderEntity != null) {
            FacesMessage message = new FacesMessage("Name is not unique.");
            setNameValid(false);
            throw new ValidatorException(message);
        }
        setNameValid(true);
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public String getOtherName() {
        return otherName;
    }
    public void setOtherName(String otherName) {
        this.otherName = otherName;
    }
    public void listener(ActionEvent event) {
        msg = "Called Action Listener";
    }
    public String actionCall() {
        msg = "Called Action method";
        return null;
    }
    public String sendAlert() {
        return "showMessage('Executed a bean that returned a JavaScript Command');";
    }
}

OrderPartsBean.java

package com.sample.beans;
import com.sample.facades.OrderPartsEntityFacade;
import com.sample.facades.PartEntityFacade;
import com.sample.entities.OrderPartsEntity;
import com.sample.entities.PartEntity;
import java.io.Serializable;
import java.util.List;
import javax.enterprise.context.Dependent;
import javax.inject.Named;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
/**
 * @author Thomas Dias
 */
@Named("orderPartsBean")
@Dependent
public class OrderPartsBean implements Serializable {
    private PartEntity selectedPart;
    private List<PartEntity> availableParts;
    private MainSampleViewBean mainSampleViewBean;
    @Inject
    OrderPartsEntityFacade orderPartsEntityFacade;
    @Inject
    PartEntityFacade partEntityFacade;
    public OrderPartsEntityFacade getOrderPartsEntityFacade() {
        return orderPartsEntityFacade;
    }
    public void setOrderPartsEntityFacade(OrderPartsEntityFacade orderPartsEntityFacade) {
        this.orderPartsEntityFacade = orderPartsEntityFacade;
    }
    public PartEntityFacade getPartEntityFacade() {
        return partEntityFacade;
    }
    public void setPartEntityFacade(PartEntityFacade partEntityFacade) {
        this.partEntityFacade = partEntityFacade;
    }
    /** Creates a new instance of OrderPartsBean */
    public OrderPartsBean() {
    }
    public void init() {
        TreeNode selectedNode = mainSampleViewBean.getTreeBean().getSelectedNode();
        if (selectedNode == null) {
            return;
        }
        if (selectedNode.getData() instanceof OrderPartsEntity) {
            availableParts = partEntityFacade.getAvailableParts(((OrderPartsEntity) selectedNode.getData()).getPart().getId());
        } else {
            availableParts = partEntityFacade.getAvailableParts(null);
        }
    }
    public List<PartEntity> getAvailableParts() {
        return availableParts;
    }
    public PartEntity getSelectedPart() {
        return selectedPart;
    }
    public void setSelectedPart(PartEntity selectedPart) {
        this.selectedPart = selectedPart;
    }
    public MainSampleViewBean getMainSampleViewBean() {
        return mainSampleViewBean;
    }
    public void setMainSampleViewBean(MainSampleViewBean mainSampleViewBean) {
        this.mainSampleViewBean = mainSampleViewBean;
    }
    public void removeOrderParts(ActionEvent event) {
        TreeNode selectedNode = mainSampleViewBean.getTreeBean().getSelectedNode();
        if (selectedNode != null && selectedNode.getData() instanceof OrderPartsEntity) {
            TreeNode parentNode = selectedNode.getParent();


            // Remove the parts from the parent
            OrderPartsEntity selectedEntry = (OrderPartsEntity) selectedNode.getData();
            if (parentNode != null && parentNode.getData() instanceof OrderPartsEntity) {
                selectedEntry.getParent().getSubOrderParts().remove(selectedEntry);
            }
            // Remove the parts from the order
            selectedEntry.getOrderEntity().getOrderedParts().remove(selectedEntry);
            // Remove the node from the tree
            parentNode.getChildren().remove(selectedNode);
            // Remove the parts from the database
            orderPartsEntityFacade.remove(selectedEntry.getId());
            // Select the parent node, then act on the selection
            mainSampleViewBean.getTreeBean().setSelectedNode(parentNode);
            mainSampleViewBean.getTreeBean().onNodeSelect(null);
        }
    }
    public void addOrderParts(ActionEvent event) {
        TreeNode selectedNode = mainSampleViewBean.getTreeBean().getSelectedNode();
        if (selectedNode != null && selectedPart != null) {
            OrderPartsEntity parent = null;
            if (selectedNode.getData() instanceof OrderPartsEntity) {
                parent = (OrderPartsEntity) selectedNode.getData();
            }
            OrderPartsEntity newOrderedPart = new OrderPartsEntity(mainSampleViewBean.getOrderEntity(), selectedPart, parent);
            TreeNode newNode = new DefaultTreeNode(newOrderedPart, selectedNode);
        }
    }
}

TreeBean.java

package com.sample.beans;
import com.sample.entities.OrderEntity;
import com.sample.entities.OrderPartsEntity;
import java.io.Serializable;
import javax.enterprise.context.Dependent;
import javax.inject.Named;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
/**
 * @author Thomas Dias
 */
@Named("treeBean")
@Dependent
public class TreeBean implements Serializable {
    MainSampleViewBean mainSampleViewBean;
    /** Creates a new instance of TreeBean */
    public TreeBean() {
    }
    private TreeNode selectedNode;
    private TreeNode treeRoot;
    private void addNode(OrderPartsEntity part, TreeNode parent) {
        TreeNode newNode = new DefaultTreeNode(part, parent);
        for (OrderPartsEntity subPart : part.getSubOrderParts()) {
            addNode(subPart, newNode);
        }
    }
    public TreeNode getOrderTree() {
        return treeRoot;
    }
    public void buildTree(OrderEntity orderEntity) {
        treeRoot = new DefaultTreeNode(null, null);
        if (orderEntity == null) {
            selectedNode = null;
            return;
        }
        TreeNode node = new DefaultTreeNode(orderEntity, treeRoot);
        for (OrderPartsEntity part : orderEntity.getOrderedParts()) {
            if (part.getParent() == null) {
                addNode(part, node);
            }
        }
        setSelectedNode(node);
        onNodeSelect(null);
    }
    public TreeNode getSelectedNode() {
        return selectedNode;
    }
    public void setSelectedNode(TreeNode selectedNode) {
        this.selectedNode = selectedNode;
    }
    public void onNodeSelect(NodeSelectEvent event) {
        if (selectedNode != null) {
            selectedNode.setSelected(true);
            selectedNode.setExpanded(true);
            Object nodeData = selectedNode.getData();
            StringBuilder msg = new StringBuilder("Selected Node: ");
            msg.append(nodeData);
            msg.append(", Parts Id: ");
            Long id = null;
            if (nodeData instanceof OrderPartsEntity) {
                id = ((OrderPartsEntity) nodeData).getPart().getId();
                msg.append(id);
                msg.append(", Order Entity Id: ");
                msg.append(((OrderPartsEntity) nodeData).getOrderEntity().getId());
            } else {
                msg.append("null, Order Entity Id: ");
                msg.append(((OrderEntity) nodeData).getId());
            }
        }
        mainSampleViewBean.partSelected();
    }
    public MainSampleViewBean getMainSampleViewBean() {
        return mainSampleViewBean;
    }
    public void setMainSampleViewBean(MainSampleViewBean mainSampleViewBean) {
        this.mainSampleViewBean = mainSampleViewBean;
    }
    public TreeNode getTreeRoot() {
        return treeRoot;
    }
    public void setTreeRoot(TreeNode treeRoot) {
        this.treeRoot = treeRoot;
    }
}

No comments:

Post a Comment