mysql – import CSV


Internet resources

  • @see exemple
  • Objectives

    import a csv file in an existing table

    Implementation

  • using mysql studio
  • SQL request
  • Implementation example

    LOAD DATA INFILE 'D:/Java/mydata/mysql/object.csv'
    INTO TABLE object
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
    IGNORE 1 ROWS;
    SELECT * FROM instance.object;
    	

    Tips

  • see code example
  • no installation
  • easy to implement
  • Next steps

  • none
  • Java – BigDecimal management


    Internet resources

  • @see Oracle reference
  • Objectives

    management of the decimal numbers

    Implementation

  • Rounding
  • BigDecimal.ROUND_HALF_UP
    Rounding mode to round towards « nearest neighbor » unless both neighbors are equidistant, in which case round up. Behaves as for ROUND_UP if the discarded fraction is ≥ 0.5; otherwise, behaves as for ROUND_DOWN. Note that this is the rounding mode that most of us were taught in grade school.

  • Cast int to BigDecimal
  • Divide
  • Implementation example

    Rounding

    
        static final int ROUNDING_OUTPUT  = 2;
        static final int ROUNDING_TYPE    = BigDecimal.ROUND_HALF_UP;
    
       /**
         * rounding BigDecimal value
         * 
         * @param value
         * @return rounded value
         */
        public BigDecimal rounding( BigDecimal value ) {
            BigDecimal result = value.setScale( ROUNDING_OUTPUT, ROUNDING_TYPE );
            return result;
        }
    	

    cast int to BigDecimal

    int -1 is casted to bigdecimal

             BigDecimal result = new BigDecimal( (double) -1 );
    
    	

    Divide

    
        static final int ROUNDING_COMPUTE = 5;
        static final int ROUNDING_TYPE    = BigDecimal.ROUND_HALF_UP;
    
        /**
         * Divide BigDecimal numbers
         * 
         * @param value
         * @param divisor
         * @return result
         */
        public BigDecimal divide( BigDecimal value, BigDecimal divisor ) {
            BigDecimal result = new BigDecimal( (double) -1 );
            int workingValue = value.compareTo( Z );
    
            /*
             * Protect from zero divide
             */
            if ( workingValue != 0 ) {
                result = value.divide( divisor, ROUNDING_COMPUTE, ROUNDING_TYPE );
                // logger.debug( "Result(" + result + ")" );
            }
            return result;
        }
    	

    Tips

  • see code example
  • no installation
  • easy to implement
  • Next steps

  • none
  • Date management – joda time


    Internet resources

  • @see Joda time
  • Objectives

    simplify the date management

    Implementation

  • Dowload Joda jar from Joda website
  • Copy Joda jar in web-inf/lib directory
  • Implementation example

  • Joda time convert to java.util.date and reverse
  • Calculate the number of months between to dates
  • Calculate the end period date from a date and a period in month
  • oda time convert to java.util.date and reverse

    
    	

    Number of months between to dates

       /*
         * compute #months between first and last util.date
         */
        public int monthsBetweenDates( Date first, Date last ) {
    
            DateTime start = new DateTime( first );
            DateTime end = new DateTime( last );
    
            Months months = Months.monthsBetween( start, end );
            logger.debug( "d1-d2=gap(" + first.toString() + ")(" + last.toString() + ")(" +
                    months.getMonths() + ")" );
            return months.getMonths();
    
        }
    	

    end period date from a date and a period in month

       /**
         * Calculate a end of period from a date and a period in months 
         * @param startDate
         * @param month
         * @return
         */
        public Date endPeriod( Date startDate, int month ) {
            // Duration
            Duration duration = new Duration( 0 );
    
            // calc will equal end
            DateTime start = new DateTime( startDate );
            DateTime calc = start.plusMonths( month );
            Date endDate = calc.toDate();
            logger.debug( "Start(" + startDate + ") month(" + month + ") End(" + endDate + ")" );
            return endDate;
        }
    	

    Tips

  • see code example
  • easy to install
  • easy to implement
  • Next steps

  • none
  • Polymorphism


    Internet resources

  • @see Oracle Java Tutorial
  • @see Java Polymorphism
  • @see heritage and polymorphism (French)
  • @see Heritage en Java (French)
  • @see Abstract and Interface (French)
  • Implementation model

    Polymorphism/Interface/Inheritance model
    interface Humanable
        see
        eat
        walk
        run
        rest
        rip
    
    interface Doctor
        heal
    
    interface Warrior
        fight
    
    Interface Warlock
        cast
    
    Abstract Superman implements interface Human, Doctor, Warrior, Warlock
        Human
            see ="Everything"
            eat="Never"
            walk = return "run"
            run = return "flash run "
            rest = return "never"
            rip = return "never"
        Doctor
            heal = return "Surgeon"
        Warrior
            fight = return "Marine"
        Warlock
            cast = return "Fireball"
    
    Class Somebody extends Superman
        Human h = new Human
            h.see="Blind"
            h.eat="allways"
            h.walk = "walk"
            h.run = "run"
            h.rest = "every night"
            h.rip = return "80 years"
        Doctor d = new Doctor
            d.heal="cannot heal"
        Warrior w1 = new Warrior
            w1.figth="cannot fight"
        Warlock w2 = New Warlock
            w2.cast="cannot cast"
    

    Tips

  • Interfaces (abstract) are used for defining object behaviour. the behaviour can be understood and noted as ‘object’ followed by ‘able’ like ‘Serializable’, if you cannot say ‘object’able you should not create an interface, but an object. (abstract or POJO)
  • Super class are used for defining the « standard behavior » of objects
  • An object is defined by its class, once the object exists the object can be manipulated by any super.class without loosing its own properties. (a sub-class bears its own properties which add properties of the existing properties of its super class).
  • Java.lang.IllegalArgumentException: NamedQuery of name: InstantMessage.findAll not found

    Glassfish error log

    Caused by: java.lang.IllegalArgumentException: NamedQuery of name: InstantMessage.findAll not found.
    	at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:350)
    	at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:1107)
    	at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:1127)
    	at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createNamedQuery(EntityManagerWrapper.java:545)
    	at com.netricite.dao.InstantMessageDao.findAll2(InstantMessageDao.java:62)
    

    Reason

    the NamedQuery is not found by the entitymanager.

    Mispelling check

    • check persistence.xml (declare the class injecting the entity manager)
    • check link between @PersistenceContext and persitence.xml (persistence_unit value)
    • check the name given in the createNamedQuery statement and the name given in the @entity/@NamedQuery

    Conflict check

    • Check conflict between various persistence.xml used in the project, including embedded jars. (ie persistence unit value cannot be the same in different persistence.xml)

    JSF – Web Fragment Project configuration

    Internet resources

    Objectives

    A web fragment is a logical partitioning of the web application in such a way that the frameworks being used within the web application can define all the artifacts without requiring you to edit or add information in the web.xml.

    Implementation

    According to BalusC (@see above), using Eclipse:

    • 1.create a « Dynamic Web Project »
    • 1.create a « Web Fragment Project »
    • 2.add a JSF 2.0 compatible /META-INF/faces-config.xml file in the source folder of « Web Fragment Project ».
    • 3.add the « web Fragment Project » to the Deployment Assembly list in the dynamic web project’s properties).

    That’s it: Once JSF finds a JAR in /WEB-INF/lib with a JSF 2.0 compatible /META-INF/faces-config.xml, then JSF will automatically scan the entire JAR for JSF artifacts.

    Implementation example

    JSF 2.0 compatible /META-INF/faces-config.xml file

     <?xml version="1.0" encoding="UTF-8"?>
    <faces-config
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
        version="2.0">
         
    </faces-config>

    Components

    Configuration components:
              ear = rbacEARv3
    	  dynamic web app = rbacWEBv1 (http://localhost:8080/rbacWEBv1/webpages/a.xhtml)
    	  web fragment = rbacWEBim (@ManagedBean  name="aBean")
    	  faces.config.xml in rbacWEBv1/META-INF and rbacWEBim/META-INF
    	  xhtml view = a.xhtml 	           
                  <h:inputTextarea id="newMessage" value="#{aBean.entity.message} />"
    
    After EAR publishing into glassfish4:
    	  jar rbacWEBim.jar is located in \glassfish4\...\domain1\eclipseApps\rbacEARv3\rbacWEBv1_war\WEB-INF\lib
              class aBean is located in \glassfish4\...\domain1\eclipseApps\rbacEARv3\lib\rbacWEBim_jar
    	  there is no faces-config in \glassfish4\...\domain1\eclipseApps\rbacEARv3\lib\rbacWEBim_jar\META-INF
                    but only MANIFEST.MF and webfragment.xml
    

    Troubleshooting

    • Context: JSF injection : javax.el.PropertyNotFoundException

    Exception display

        javax.el.PropertyNotFoundException: 
    	           /webpages/a/a.xhtml @58,95 
    	           value="#{aBean.entity.message}": Target Unreachable, identifier 'aBean' resolved to null
        at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
    	at org.primefaces.util.ComponentUtils.getConverter(ComponentUtils.java:128)
    	at org.primefaces.renderkit.InputRenderer.getConvertedValue(InputRenderer.java:171)
    	at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1046)
    	at javax.faces.component.UIInput.validate(UIInput.java:976)
    	at javax.faces.component.UIInput.executeValidate(UIInput.java:1249)
    	at javax.faces.component.UIInput.processValidators(UIInput.java:712)
    	at javax.faces.component.UIForm.processValidators(UIForm.java:253)
    	at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    	at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    	at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    	at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    	at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    	at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
    	at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
    	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    	at com.netricite.bundle.UserSessionFilter.doFilter(UserSessionFilter.java:88)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    	at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    	at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    	at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    	at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    	at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    	at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    	at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    	at java.lang.Thread.run(Thread.java:745)
    

    Tips

    • CDI supports Web Fragment Project, migrate from JSF injection (@ManagedBean/@ManagedProperty) to CDI (@Named/@inject)

    Next steps

    • Migrate all web applications from JSF injection to CDI (Context dependency Injection)

    Primefaces – Datatable Lazy loading

    Internet resources

    Implementation

    to make the lazy loading works with Primefaces, you need the following components:

    • xhtml view (…Lazy.xhtml): for displaying the p:dataTable lazy= »true »
    • a bean, (…LazyBean.java) called by the xhtml view for building the datatable
    • a class, (…LazyDataModel.java) inherited from Primefaces/LazyDataModel, called by primefaces datatable for managing the lazy loadin
    • a bean interfacing the stateless ejb (…Bean.java)
    • a stateless ejb, (…dao.java) for accessing the database and providing the data

    Implementation example

    xhtml view (…Lazy.xhtml)

     <ui:fragment>
                <h:form id="formMessage">
                   <p:growl id="messages" showDetail="true"/>
                </h:form>
                <p:accordionPanel id="crudPanel">
                   <p:tab title="Objects Traceability(Lazy loading)">
                      <h:form id="formTraceability">
                         
                         <p:dataTable id="logTable" var="log" 
                            value="#{applicationLogLazyBean.lazyModel}" editable="false" 
                            paginatorTemplate="{RowsPerPageDropdown} {CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} "
                            paginator="true" rows="20" rowsPerPageTemplate="5,20,50" lazy="true"
                            tableStyle="width:auto"
                            >
                            
                            <p:column sortBy="#{log.applicationlog.statusDate}" headerText="Date" >
                               <h:outputText value="#{log.applicationlog.statusDate}" >
                                  <f:convertDateTime dateStyle="medium" timeZone="Europe/Paris" type="both" />
                               </h:outputText>
                            </p:column>
                            <p:column sortBy="#{log.applicationlog.eventTitle}" headerText="Event">
                               <h:outputText value="#{log.applicationlog.eventTitle}" />
                            </p:column>
                            <p:column sortBy="#{log.applicationlog.ownerCode}" headerText="User">
                               <h:outputText value="#{log.applicationlog.ownerCode}" />
                            </p:column>
                            <p:column sortBy="#{log.applicationlog.applicationName}" headerText="Appl">
                               <h:outputText value="#{log.applicationlog.applicationName}" />
                            </p:column>
                            <p:column  headerText="Id">
                               <h:outputText value="#{log.webuser.id}" />
                            </p:column>
                            <p:column  headerText="Shortname">
                               <h:outputText value="#{log.webuser.shortname}" filterBy="#{log.webuser.shortname}"/>
                            </p:column>
                            <p:column  headerText="Name">
                               <h:outputText value="#{log.webuser.name}" filterBy="#{log.webuser.name}"/>
                            </p:column>
                            <p:column headerText="Status">
                               <h:outputText value="#{log.webuser.status}" />
                            </p:column>
                            <p:column headerText="Date">
                               <h:outputText value="#{log.webuser.statusdate}" />
                            </p:column>
                            <p:column headerText="Company">
                               <h:outputText value="#{log.webuser.companyid}" />
                            </p:column>
                            <p:column headerText="Type">
                               <h:outputText value="#{log.webuser.type}" />
                            </p:column>
                            <p:column headerText="Unit">
                               <h:outputText value="#{log.webuser.unitid}" />
                            </p:column>
                            <p:column headerText="Function">
                               <h:outputText value="#{log.webuser.function.code}" />
                            </p:column>
                            <p:column headerText="Lang.">
                               <h:outputText value="#{log.webuser.language}" />
                            </p:column>
                            <p:column  headerText="Comment">
                               <h:outputText value="#{log.webuser.comment}" />
                            </p:column>
                            <f:facet name="footer">
                               <p:commandButton value="Refresh" update="logTable" actionListener="#{applicationLogBean.refresh}" icon="ui-icon-refresh">
                                  <f:ajax execute="@form" render="@form" />
                                  Number of selected events #{applicationLogBean.getTableCount()}.   
                               </p:commandButton>
                            </f:facet>
                         </p:dataTable>
                      </h:form>
                   </p:tab>
                </p:accordionPanel>
             </ui:fragment>

    Bean called by the xhtml view (…LazyBean.java)

     package com.netricite.rbac.beans;
    
    import java.io.Serializable;
    
    import javax.annotation.PostConstruct;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.ManagedProperty;
    import javax.faces.bean.ViewScoped;
    
    import org.apache.log4j.Logger;
    import org.primefaces.model.LazyDataModel;
    
    @ManagedBean
    @ViewScoped
    public class ApplicationLogLazyBean implements Serializable {
        /**
         * 
         */
        private static final long             serialVersionUID = -8419133227508082027L;
        private static final Logger           logger           = Logger.getLogger( ApplicationLogLazyBean.class );
    
        private LazyDataModel<WebuserLogView> lazyModel;
    
        private WebuserLogView                selectedEntity;
    
        @ManagedProperty( "#{applicationLogBean}" )
        private ApplicationLogBean            applicationlogbean;
    
        /**
         * @return the applicationlogbean
         */
        public ApplicationLogBean getApplicationlogbean() {
            return applicationlogbean;
        }
    
        /**
         * @param applicationlogbean
         *            the applicationlogbean to set
         */
        public void setApplicationlogbean( ApplicationLogBean applicationlogbean ) {
            this.applicationlogbean = applicationlogbean;
        }
    
        @PostConstruct
        public void init() {
            logger.trace( "init" );
            lazyModel = new ApplicationLogLazyDataModel( applicationlogbean );
            logger.trace( "init, LazyModel created" );
        }
    
        public LazyDataModel<WebuserLogView> getLazyModel() {
            return lazyModel;
        }
    
        public WebuserLogView getSelectedEntity() {
            return selectedEntity;
        }
    
        public void setSelectedEntity( WebuserLogView selectedEntity ) {
            this.selectedEntity = selectedEntity;
        }
    
    }

    Class inherited from LazyDataModel, (…LazyDataModel.java)

    package com.netricite.rbac.beans;
    
    import java.util.List;
    import java.util.Map;
    
    import org.apache.log4j.Logger;
    import org.primefaces.model.LazyDataModel;
    import org.primefaces.model.SortOrder;
    
    public class ApplicationLogLazyDataModel extends LazyDataModel<WebuserLogView> {
    
        /**
         * 
         */
        private static final long        serialVersionUID = 7723480065915105372L;
        private static final Logger      logger           = Logger.getLogger( ApplicationLogLazyDataModel.class );
    
        private List<WebuserLogView>     datasource;
    
        // public ApplicationLogLazyDataModel( List<WebuserLogView> datasource ) {
        // this.datasource = datasource;
        // }
        private final ApplicationLogBean daoService;
    
        public ApplicationLogLazyDataModel( ApplicationLogBean daoService ) {
            this.daoService = daoService;
        }
    
        @Override
        public WebuserLogView getRowData( String rowKey ) {
            for ( WebuserLogView event : datasource ) {
                if ( event.getApplicationlog().getShortName().equals( rowKey ) ) {
                    return event;
                }
            }
    
            return null;
        }
    
        @Override
        public Object getRowKey( WebuserLogView event ) {
            return event.getApplicationlog().getShortName();
        }
    
        @Override
        public List<WebuserLogView> load( int first, int pageSize, String sortField, SortOrder sortOrder,
                Map<String, Object> filters ) {
            logger.trace( "load" );
            daoService.refresh( first, pageSize );
            datasource = daoService.refresh( daoService.getEntities() );
            setRowCount( daoService.getTableCount() );
            return datasource;
        }
    }
    
    

    Bean for interfacing the stateless ejb(dao) (…Bean.xhtml)

    Refresh the data used for creating the datasource of the lazyDataModel

       /*
         * refresh the datable bean
         */
        public void refresh( int rowPosition_arg, int pageSize_arg ) {
            logger.trace( "Refresh/Entities position(" + getRowPosition() + ")" );
            entities = entitydao.findAll( rowPosition_arg, pageSize_arg );
            listlength = entities.size();
            logger.trace( "Refresh/#Entities(" + listlength + ")" );
    
            logs = refresh( entities );
        }
    
    

    Refresh the data to be stored in the datasource object of the …LazyModel

       /*
         * Create a list of events relative to the selected objects
         */
        public List refresh(
                List entities_arg ) {
            List events = new ArrayList();
            // Load list of events (applicationLog + Associated webuser)
            for ( ApplicationLog applicationlog : entities_arg ) {
                WebuserLogView obj = new WebuserLogView( applicationlog );
                if ( obj.getWebuser() != null ) {
                    events.add( obj );
                }
            }
            listlength = events.size();
            logger.trace( "Refresh/#logs(" + listlength + ")" );
            return events;
        }
    

    Stateless ejb for accessing the database (…DAO.java)

      /**
         * SELECT COUNT(*) FOR applicationlog;
         * 
         * @return count
         */
        public int countAll() {
            Query query = entitymanager.createNamedQuery( "ApplicationLog.countAll" );
            Number count = 0;
            try {
                count = (Number) query.getSingleResult();
            } catch ( Exception e ) {
                throw new DAOexception( e );
            }
            return count.intValue();
        }
    
       /**
         * SELECT * FROM table SORTED BY code
         * 
         * @return list of entity
         */
        public List<ApplicationLog> findAll( int rowPosition_arg, int pageSize_arg ) throws DAOexception {
            TypedQuery<ApplicationLog> query =
                    entitymanager.createNamedQuery( "ApplicationLog.findAll", ApplicationLog.class )
                            .setMaxResults( pageSize_arg );
            query.setFirstResult( rowPosition_arg );
            return query.getResultList();
        }

    Tips

    • see code example and internet link resources
    • easy to implement, nevertheless the documention related to connection pool is weak, see my implementation
    • The main issue is to get the required datasource and count in the …LazyDataModel which is specific to your ownn implementation
      • the …LazyDataModel constructor is used to provide the reference of the object which is in charge of accessing the database
      • Tehn everything is straigth forward, you just need to access the data based on the previous object

    Next steps

    • none

    JSF – Navigation issue

    Error message

    Glassfish error log

    JSF1064: Unable to find or serve resource, /webpages/rbac/index.xhtml

    Ajax error

    Unable to find matching navigation case with from-view-id ‘/webpages/rbac/webuser.xhtml’
    for action ‘#{webuserBean.eventLog}’
    with outcome ‘index.xhtml?faces-redirect=true’

    Stack trace

    none

    Bug fixes

    the final code

  • in the calling page
  •   <p:commandButton value="#{msg['button.history']}" action="#{webuserBean.eventLog}" 
                         id="btn_submitHistory" update=":formMessage:messages">
                         <f:ajax execute="@form" render="@form" />
                         </p:commandButton>
  • in the bean
  • /*
         * redirect to eventLog page
         */
        public String eventLog() {
            logger.trace( "Redirect to Eventlog page" );
            String nextPage = "/webpages/applicationLog/log.xhtml?faces-redirect=true";
            return nextPage;
        }
    
    

    What was wrong in the initial coding

  • 1)in the calling xhtml page, the ‘update’ and the ajax directives were missing
  • 2)the webpage was not in the correct location, by default the webpage location is in the current directory
  • Related reference

    ejb.system_exception

    Error message

  • [2014-10-10T17:04:55.640+0200] [glassfish 4.0] [WARNING] [ejb.system_exception] [javax.enterprise.system.container.ejb.com.sun.ejb.containers] [tid: _ThreadID=20 _ThreadName=http-listener-1(3)] [timeMillis: 1412953495640] [levelValue: 900] [[
    EJB5184:A system exception occurred during an invocation on EJB ApplicationLogDAO, method: public java.util.List com.netricite.applicationservice.dao.ApplicationLogDAO.findAll() throws com.netricite.applicationservice.dao.DAOexception]]

    [2014-10-10T17:04:55.640+0200] [glassfish 4.0] [WARNING] [] [javax.enterprise.system.container.ejb.com.sun.ejb.containers] [tid: _ThreadID=20 _ThreadName=http-listener-1(3)] [timeMillis: 1412953495640] [levelValue: 900] [[

    javax.ejb.EJBException

  • Stack trace

    [2014-10-10T17:04:55.640+0200] [glassfish 4.0] [WARNING] [ejb.system_exception] [javax.enterprise.system.container.ejb.com.sun.ejb.containers] [tid: _ThreadID=20 _ThreadName=http-listener-1(3)] [timeMillis: 1412953495640] [levelValue: 900] [[
      EJB5184:A system exception occurred during an invocation on EJB ApplicationLogDAO, method: public java.util.List com.netricite.applicationservice.dao.ApplicationLogDAO.findAll() throws com.netricite.applicationservice.dao.DAOexception]]
    
    [2014-10-10T17:04:55.640+0200] [glassfish 4.0] [WARNING] [] [javax.enterprise.system.container.ejb.com.sun.ejb.containers] [tid: _ThreadID=20 _ThreadName=http-listener-1(3)] [timeMillis: 1412953495640] [levelValue: 900] [[
      
    javax.ejb.EJBException
    	at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
    	at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
    	at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
    	at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4475)
    	at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2009)
    	at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1979)
    	at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
    	at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    	at com.sun.proxy.$Proxy400.findAll(Unknown Source)
    	at com.netricite.applicationservice.dao.__EJB31_Generated__ApplicationLogDAO__Intf____Bean__.findAll(Unknown Source)
    	at com.netricite.rbac.beans.ApplicationLogBean.refresh(ApplicationLogBean.java:206)
    	at com.netricite.rbac.beans.ApplicationLogBean.init(ApplicationLogBean.java:129)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:606)
    	at org.glassfish.faces.integration.GlassFishInjectionProvider$2.run(GlassFishInjectionProvider.java:382)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at org.glassfish.faces.integration.GlassFishInjectionProvider.invokeLifecycleMethod(GlassFishInjectionProvider.java:376)
    	at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:306)
    	at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:229)
    	at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:221)
    	at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:103)
    	at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    	at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    	at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
    	at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
    	at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    	at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    	at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:116)
    	at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
    	at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    	at com.sun.faces.mgbean.BeanBuilder$Expression.evaluate(BeanBuilder.java:561)
    	at com.sun.faces.mgbean.ManagedBeanBuilder$BakedBeanProperty.set(ManagedBeanBuilder.java:606)
    	at com.sun.faces.mgbean.ManagedBeanBuilder.buildBean(ManagedBeanBuilder.java:133)
    	at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
    	at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    	at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    	at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
    	at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
    	at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    	at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    	at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:116)
    	at com.sun.el.parser.AstValue.getBase(AstValue.java:151)
    	at com.sun.el.parser.AstValue.getValue(AstValue.java:200)
    	at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
    	at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    	at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    	at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    	at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    	at javax.faces.component.UIOutput.getValue(UIOutput.java:174)
    	at javax.faces.component.UIInput.getValue(UIInput.java:291)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:606)
    	at com.sun.faces.facelets.util.DevTools.writeAttributes(DevTools.java:380)
    	at com.sun.faces.facelets.util.DevTools.writeStart(DevTools.java:433)
    	at com.sun.faces.facelets.util.DevTools.writeComponent(DevTools.java:250)
    	at com.sun.faces.facelets.util.DevTools.writeComponent(DevTools.java:269)
    	at com.sun.faces.facelets.util.DevTools.writeComponent(DevTools.java:269)
    	at com.sun.faces.facelets.util.DevTools.writeComponent(DevTools.java:269)
    	at com.sun.faces.facelets.util.DevTools.writeComponent(DevTools.java:269)
    	at com.sun.faces.facelets.util.DevTools.writeComponent(DevTools.java:269)
    	at com.sun.faces.facelets.util.DevTools.writeComponent(DevTools.java:269)
    	at com.sun.faces.facelets.util.DevTools.debugHtml(DevTools.java:131)
    	at com.sun.faces.renderkit.RenderKitUtils.renderHtmlErrorPage(RenderKitUtils.java:1206)
    	at com.sun.faces.context.ExceptionHandlerImpl.throwIt(ExceptionHandlerImpl.java:272)
    	at com.sun.faces.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:141)
    	at javax.faces.context.ExceptionHandlerWrapper.handle(ExceptionHandlerWrapper.java:100)
    	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
    	at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    	at com.netricite.bundle.UserSessionFilter.doFilter(UserSessionFilter.java:88)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    	at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    	at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    	at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    	at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    	at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    	at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    	at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    	at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    	at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName netricite_PU
    	at com.sun.enterprise.container.common.impl.EntityManagerWrapper.init(EntityManagerWrapper.java:138)
    	at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:171)
    	at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createNamedQuery(EntityManagerWrapper.java:544)
    	at com.netricite.applicationservice.dao.ApplicationLogDAO.findAll(ApplicationLogDAO.java:121)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:606)
    	at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    	at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    	at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
    	at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
    	at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    	at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
    	at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    	at sun.reflect.GeneratedMethodAccessor791.invoke(Unknown Source)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:606)
    	at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    	at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    	at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
    	at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    	at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:606)
    	at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    	at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    	at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    	at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
    	at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
    	at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    	... 98 more
    ]]
    	

    Stack trace analysis

  • It appears the error is issued because the EntityManagerFactory cannot be retrieved for a backing bean
  • Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName netricite_PU
    	
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    
    	at com.sun.faces.mgbean.ManagedBeanBuilder$BakedBeanProperty.set(ManagedBeanBuilder.java:606)
    	at com.sun.faces.mgbean.ManagedBeanBuilder.buildBean(ManagedBeanBuilder.java:133)
    
    at org.glassfish.faces.integration.GlassFishInjectionProvider$2.run(GlassFishInjectionProvider.java:382)
    

    Bug fixes

  • the injected bean was missing in the persistence.xml file
  • once added everything went right
  • object serialization/deserialization

    Internet resources

    Implementation

    • Serialize the object using ‘ObjectOutputStream’
    • the object can be transformed in string or byte[]
    • Republish the application
    • Objective: use the new dataexoprter feature

    Implementation example

     public byte[] serializeEntity( Webuser entity_arg ) {
            try {
                //serialization
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream( bos );
    
                oos.writeObject( entity_arg );
                oos.flush();
                oos.close();
                bos.close();
    
                byte[] data = bos.toByteArray();
                logger.trace( "Object serialized(Byte)(" + data.toString().getBytes() + ")" );
                logger.trace( "Object serialized(String)(" + bos.toString() + ")" );
                
                //Deserialization
                ByteArrayInputStream bis = new ByteArrayInputStream( data );
                ObjectInputStream sis = new ObjectInputStream( bis );
                Webuser obj = (Webuser) sis.readObject();
                // the properties of the object have been 
                logger.trace( "Object deserialized(id)(" + obj.getId() + ")" );
                logger.trace( "Object deserialized(name)(" + obj.getName() + ")" );
    
                return data;
            } catch ( Exception e ) {
                System.out.println( e.getMessage() );
                System.out.println( e.toString() );
                e.printStackTrace();
                FacesMessage msg = new FacesMessage( "Entity cannot be serialized" );
                FacesContext.getCurrentInstance().addMessage( null, msg );
                return null;
            }
        }

    Tips

    • see code example
    • the serialized object can be stored in any database table as ‘string’ or ‘byte[]’

    Next steps

    • none