Coding

 
Main Page
Web.xml
Index.xhtml
template.xhtml
Partoffers.xhtml
categorylist.xhtml
offers.xhtml
Java Files
         MenuController.java



Web.xml      
<welcome-file> tag will call the index.xhtml file as follows
<welcome-file>faces/index.xhtml</welcome-file>
 
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Production</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
<error-page>
<error-code>500</error-code>
<location>/faces/error/error.xhtml</location>
</error-page>
</web-app>
 
 




File Name: Index.xhtml                
The <ui:composition tag will load the template.xhtml as follows
<ui:composition template="/template.xhtml">
               
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
>
<script type="text/javascript">
var i = 0;
var ni = 0;
function scrolldiv()
{
ni = setInterval(flash, 50);
}
function flash()
{
if (scroller.scrollLeft & lt; 500)
scroller.scrollLeft += 1;
else
scroller.scrollLeft = 0;
}
var link = "cartview/itemsList.xhtml";
function fn1()
{
window.location.href = link;
}
function fn2()
{
window.location.href = link;
}
function fn3()
{
window.location.href = link;
}
</script>
<style type="text/css">
#scroller {
width: 900px;
height: 200px;
border: 1px solid blue;
overflow: scroll;
margin: 0 auto;
}
#inner-scroller {
width: 1500px;
height: 210px;
border: 1px solid yellow;
color:red;
}
</style>
<ui:composition template="/template.xhtml">
<ui:define name="title">
<h:outputText value="#{bundle.ListItemsTitle}"></h:outputText>
</ui:define>
<ui:define name="body" >
<p:galleria value="#{imagesView.images}" var="image" panelWidth="500" panelHeight="313" showCaption="false" style="margin-left: 20%">
<p:graphicImage value="/images/#{image}" width="500" alt="Image Description for #{image}" title="#{image}"/>
</p:galleria>
<br/>
<body onload="scrolldiv();">
<div id="scroller">
<div id="inner-scroller" style="text-align: center">
<input type="image" onclick="fn1()" src="./images/pen.jpg" width="220" height="200" style="text-align: right" border="2px"/>
<input type="image" onclick="fn2()" src="./images/pens.jpg" width="220" height="200" style="text-align: right" border="2px"/>
<input type="image" onclick="fn3()" src="./images/laptop.jpg" width="220" height="200" style="text-align: right" border="2px"/>
</div>
</div>
<br />
</body>
</ui:define>
</ui:composition>
</html>
 
 




File Name: Template.xhtml                    
In the template we have  east and west sections. The east section that is towards left we include a file catagorylist.xhtml. This file contains all the item wise categories. we search items based on these categories like ‘electronics’. The statement to include file is
<ui:include src="/catgMas/catagorylist.xhtml" />
and in the west section that is towards right we include file catgDetails,xhtml. This file will show all the offers from database MySql. The statement to include file is
<ui:include src="catgDetails/offers.xhtml"/>
In the south region that is at footer we include partyoftemplate.xhtml
The statement to include file is
<ui:include src="partoftemplate.xhtml"/>

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns ="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h= "http://xmlns.jcp.org/jsf/html"
xmlns:p= "http://primefaces.org/ui"
xmlns:pe="http://primefaces.org/ui/extensions"
xmlns:f= "http://xmlns.jcp.org/jsf/core"
xmlns:c= "http://xmlns.jcp.org/jsp/jstl/core">
<h:head>
<title><ui:insert name="title">Default Title</ui:insert></title>
<h:outputStylesheet library="css" name="blue.css" />
<h:outputScript library="js" name="jsfcrud.js" />
<h:outputScript library="js" name="common.js" />
<script>
function fn_css()
{
css_input= document.getElementById("outputcss").value;
if (css_input =="") css_input="blue";
// alert(css_input);
var css= document.getElementsByTagName("link");
var css1=css[1].href;
css1=css1.substr(0,css1.lastIndexOf("resource/"))+"resource/"+css_input+".css?ln=css";
document.getElementsByTagName("link")[1].href=css1;
// document.getElementById("outputcss").value=css_input;
//scroll in home.page
if (getpagename() =="index.xhtml")
{
scrolldiv();
}
}
function getpagename()
{
return(location.pathname.substring(location.pathname.lastIndexOf("/") + 1));
}
</script>
</h:head>
<h:body onload="fn_css()">
<p:growl id="growl" life="3000" />
<p:layout fullPage="true" >
<p:layoutUnit position="north" >
<p:panelGrid columns="5" style="width:100%;background: yellowgreen!Important" >
<h:graphicImage value="/images/modulename.png" height="30" style="margin-left:5%"/>
<p:panelGrid columns="6" style="float:right !important;margin:0px 0px 0px 0px;">
<p:commandButton style="background-color: red" id="loginButton" value="My Accounts" actionListener="#{usernmController.prepareCreate}" update=":loginCreateForm" oncomplete="PF('dlg').show()"/>
<p:commandButton style="background-color: red" value="FeedBack" styleClass="sel-background-color"/>
<p:commandButton style="background-color: red" value="My Cart" styleClass="sel-background-color" action="/cart/listcart.xhtml?faces-redirect=true"/>
<p:commandButton style="background-color: red" value="Track Order" styleClass="sel-background-color" action="/schedule/listschedule.xhtml?faces-redirect=true"/>
<br/>
<p:clock />
<h:panelGroup>
<p:inputText type="hidden" id="sessionrole" value="Role:#{commonbean.getsess('sessionrole')}" />
<c:set var="sessionrole" value="#{commonbean.getsess('sessionrole')}" />
<c:if test="${sessionrole eq 'c'}" > <p:outputLabel id="role" value="Role: Customer" /></c:if>
<c:if test="${sessionrole eq 'a'}" > <p:outputLabel id="role" value="Role: Adminstrator" /></c:if>
<c:if test="${sessionrole eq 's'}" > <p:outputLabel id="role" value="Role: Supplier" /></c:if>
</h:panelGroup >
<p:outputLabel id="sessionuser" value="User:#{session.getAttribute('username')}" />
<p:outputLabel id="sessioncatg" value="Category:#{commonbean.getsess('sessioncatg')}"/>
<p:outputLabel id="sessionitemcode" value="Item Selected:#{commonbean.getsess('sessionitemcode')}"/>
<p:inputText id="sessionuser2" type="hidden" value="User:#{session.getAttribute('username')}" />
<p:inputText id="outputcss" value="#{commonbean.getsess('sessioncss')}" placeholder="blue"/>
</p:panelGrid>
<pe:analogClock width="50" />
</p:panelGrid>
<h:form id="searchform">
<p:menubar id="menubar" model="#{menuController.model1}" >
<f:facet name="options">
<p:panelGrid columns="5">
<p:inputText id="search1" value="#{commonbean.sfilter}" >
<p:ajax event="keyup" update=":sessionitemcode"/>
</p:inputText>
<p:commandButton icon="ui-icon-search" action="/cartview/itemsList.xhtml?faces-redirect=true" update="growl" >
<p:ajax listener="#{commonbean.setsess('sessionitemcode', commonbean.sfilter)}" update=":sessionitemcode"/>
</p:commandButton>
<p:commandButton action="#{commonbean.clearsearch()}" update="growl,sessioncatg,sessionitemcode,search1" value="Clear Search" />
<p:selectOneMenu id="css" value="#{commonbean.css}" style="width:150px" >
<p:ajax listener="#{commonbean.setsess('sessioncss', commonbean.css)}" update="outputcss" oncomplete="fn_css()" />
<!-- select single item -->
<f:selectItem itemLabel="Select Template" itemValue="" noSelectionOption="true" />
<!-- select list of items -->
<f:selectItems value="#{['blue','yellow','violet','red']}" id="selcss" >
</f:selectItems>
</p:selectOneMenu>
<p:commandButton actionListener="#{commonbean.logout()}" update=":sessionuser2,:growl" value="Log Out" oncomplete="javascript:window.location.reload()"/>
</p:panelGrid>
</f:facet>
</p:menubar>
</h:form>
</p:layoutUnit>
<p:layoutUnit position="south" size="30" >
<div class="footer">
<ui:insert name="footer" />
<p:panelGrid columns="4" >
<p:commandLink value="About Us" oncomplete="PF('aboutusDialog').show()" styleClass="footer"/>
<p:commandLink value="Site Map" oncomplete="PF('sitemapDialog').show()" styleClass="footer"/>
<p:commandLink value="Contact us" oncomplete="PF('contactusDialog').show()" styleClass="footer"/>
<p:commandLink value="FAQ" oncomplete="PF('faqDialog').show()" styleClass="footer"/>
</p:panelGrid>
</div>
</p:layoutUnit>
<p:layoutUnit position="center">
<ui:insert name="body"/>
</p:layoutUnit>
<p:layoutUnit position="west" size="170" header="Shop By Category" collapsible="true" >
<div class="left" >
<ui:insert name="left"/>
<ui:include src="/catgMas/catagorylist.xhtml" />
</div>
</p:layoutUnit>
<p:layoutUnit position="east" size="170" header="Offers" collapsible="true">
<div class="right">
<ui:include src="catgDetails/offers.xhtml"/>
</div>
</p:layoutUnit>
</p:layout>
<ui:include src="/usernm/login.xhtml"/>
</h:body>
<ui:include src="partoftemplate.xhtml"/>
</html>


 


File Name: partoftemplate.xhtml                
File partoftemplate.xhtml  has the following dialogs which are called on click of each button.
1. About us
2. Contact us.
3. SiteMap.
4. FAQ.
                  
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<p:dialog id="aboutus" widgetVar="aboutusDialog" resizable="false" appendTo="@(body)" header="About Us">
<h:form id="formaboutus">
This is a online Shopping Cart.<br/><br/>
The Supplier can log on and display their product.<br/><br/>
The Customer can log on and choose the product to purchase and buy.<br/><br/>
The Administrator will define and customize menu for supplier,seller and customer.<br/><br/>
</h:form>
</p:dialog>
<p:dialog id="sitemap" widgetVar="sitemapDialog" resizable="false" appendTo="@(body)" header="Site Map">
<h:form id="formsitemap">
<p:panel header="#{bundle.ListMenuTitle}">
<p:dataTable id="datalist" value="#{menuController.items}" var="item"
selectionMode="single" selection="#{menuController.selected}"
paginator="false"
rowKey="#{item.id}"
style="width :400px"
>
<p:column width="100">
<f:facet name="header">
<h:outputText value="Menu"/>
</f:facet>
<h:outputText value="#{item.menuShortName}"/>
</p:column>
<p:column width="100">
<f:facet name="header">
<h:outputText value="Menu Items"/>
</f:facet>
<h:outputText value="#{item.menuLongName}"/>
</p:column>
<f:facet name="footer">
<h:commandButton value="Exit" onclick="history.go(-1)" />
</f:facet>
</p:dataTable>
</p:panel>
</h:form>
</p:dialog>
<p:dialog id="contactus" widgetVar="contactusDialog" resizable="false" appendTo="@(body)" header="Contact Us">
<h:form id="formcontactus">
Site Help Line : 00-000000000.<br/><br/>
Customer Care : 99-999999999.<br/><br/>
E Mail : abc@xyz.com<br/><br/>
</h:form>
</p:dialog>
<p:dialog id="faq" widgetVar="faqDialog" resizable="false" appendTo="@(body)" header="Faq Us">
<h:form id="formfaq">
At Present not available.
</h:form>
</p:dialog>
</html>

File Name: categorylist.xhtml
This file contains list of categories like ‘electronics’ for selection of related items.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:p="http://primefaces.org/ui"
      xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
    <ui:composition>
    
            <h:form id="CatgMasListForm1">
                <p:panel  styleClass="fontsmall">
                    <p:dataTable id="datalist" value="#{catgMasController.items}" var="item"
                                 selectionMode="single" selection="#{catgMasController.selected}"
                              
                                 rowKey="#{item.id}"
                                 rows="10"
                                 rowsPerPageTemplate="10,20,30,40,50"
                                 >
                       <p:column>
                                 
                           <h:commandButton  styleClass="button-noborder" value="#{item.catgCode}"  action="#{commonbean.setsess('sessioncatg',item.catgCode)}" />
                         
                       </p:column>
                       
                       <f:facet name="footer">
                       </f:facet>
                    </p:dataTable>
                </p:panel>
            </h:form>
    </ui:composition>
</html>
File Name: offers.xhtml
This file contains list of offers like ‘10% discounts..’.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:p="http://primefaces.org/ui">
     <h:form id="CatgDetailsListForm1">
                <p:panel >
                           <p:dataTable id="datalist" value="#{catgDetailsController.items}" var="item"
                            selectionMode="single" selection="#{catgDetailsController.selected}"
                            rowKey="#{item.id}"
                           >
                        <p:column>
                            <h:outputText value="#{item.discountsProviderName}"/>
                            <p:separator/>
                            <h:outputText value="#{item.discountsDetails}"/>
                        </p:column>
                              <f:facet name="footer">
                              </f:facet>
                    </p:dataTable>
          </p:panel>
     </h:form>
</html>




Java Files
File:MenuController.java
package di.di.cart;

import di.di.cart.util.JsfUtil;
import di.di.cart.util.JsfUtil.PersistAction;

import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSubMenu;
import org.primefaces.model.menu.MenuModel;


@Named("menuController")
@SessionScoped
public class MenuController implements Serializable {


    @EJB private di.di.cart.MenuFacade ejbFacade;
    private List
items = null;
    private Menu selected;
    private MenuModel model1;

    public MenuModel getModel1() {
        return model1;
    }

    public void setModel1(MenuModel model1) {
        this.model1 = model1;
    }

    public MenuController() {
    }

    public Menu getSelected() {
        return selected;
    }

    public void setSelected(Menu selected) {
        this.selected = selected;
    }

    protected void setEmbeddableKeys() {
    }

    protected void initializeEmbeddableKey() {
    }

    private MenuFacade getFacade() {
        return ejbFacade;
    }

    @PostConstruct
    public void init()
    {
        model1 =new DefaultMenuModel();
        //add home item to submenu.
        DefaultMenuItem home = new DefaultMenuItem("Home");
        home.setUrl("/faces/index.xhtml");
        this.model1.addElement(home);
     
        DefaultSubMenu submenu=null;
        String oldmenuname =null;
        String role = '%'+"a"+'%';  //role a is for admin will get the variable from session role;
        //        for (Menu r : ejbFacade.findAll())
        for (Menu r : ejbFacade.findq("select m from Menu m where m.role like :role order by m.menuShortName",
                "role", role))
        {
            if (r!=null)
            {
                if (!r.getMenuShortName().equals(oldmenuname))
                {
                   //create and add submenu name
                    submenu = new DefaultSubMenu();
                    submenu.setIcon(null);
                    submenu.setLabel(r.getMenuShortName());
                    model1.addElement(submenu);
                }
                oldmenuname = r.getMenuShortName();
                 // add menu item to submenu.
                DefaultMenuItem item = new DefaultMenuItem();
                item.setValue(r.getMenuLongName());
                item.setUrl(r.getMenuRunOption());
                submenu.addElement(item);
            }
        }
            // add quit option to submenu
            DefaultMenuItem quit = new DefaultMenuItem();
            quit.setUrl("http://www.google.co.in");
            this.model1.addElement(quit);
    }
    public Menu prepareCreate() {
        selected = new Menu();
        initializeEmbeddableKey();
        return selected;
    }

    public void create() {
        persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("MenuCreated"));
        if (!JsfUtil.isValidationFailed()) {
            items = null;    // Invalidate list of items to trigger re-query.
        }
    }

    public void update() {
        persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("MenuUpdated"));
    }

    public void destroy() {
        persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("MenuDeleted"));
        if (!JsfUtil.isValidationFailed()) {
            selected = null; // Remove selection
            items = null;    // Invalidate list of items to trigger re-query.
        }
    }

    public List
getItems() {
        if (items == null) {
            items = getFacade().findAll();
        }
        return items;
    }

    private void persist(PersistAction persistAction, String successMessage) {
        if (selected != null) {
            setEmbeddableKeys();
            try {
                if (persistAction != PersistAction.DELETE) {
                    getFacade().edit(selected);
                } else {
                    getFacade().remove(selected);
                }
                JsfUtil.addSuccessMessage(successMessage);
            } catch (EJBException ex) {
                String msg = "";
                Throwable cause = ex.getCause();
                if (cause != null) {
                    msg = cause.getLocalizedMessage();
                }
                if (msg.length() > 0) {
                    JsfUtil.addErrorMessage(msg);
                } else {
                    JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
                }
            } catch (Exception ex) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            }
        }
    }

    public Menu getMenu(java.lang.Integer id) {
        return getFacade().find(id);
    }

    public List
getItemsAvailableSelectMany() {
        return getFacade().findAll();
    }

    public List
getItemsAvailableSelectOne() {
        return getFacade().findAll();
    }

    @FacesConverter(forClass=Menu.class)
    public static class MenuControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            MenuController controller = (MenuController)facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "menuController");
            return controller.getMenu(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Menu) {
                Menu o = (Menu) object;
                return getStringKey(o.getId());
            } else {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Menu.class.getName()});
                return null;
            }
        }

    }

}














2 comments: