jeudi 19 avril 2018

JSF2.2 Create a comment from a postsController

That's the situation, I have a web application (blog) JSF2.2. I'm having a problem with the oneToMany relationship between the Comment and Post table .... I have a post view that contains the article and a form to post a comment in the same page -> /posts/View.xhtml . I generated via netbean8.2 the entities, the facades and the controllers.

This is where I have a little trouble ... I have a CommentsController and a PostsController, they allow both to do the CRUD but separately ... I would like to be able to create a comment from the page posts / view.xhtml without having to enter the id of the post and then my controller redirects me to my page posts / view.xhtml.

My setup : Netbean8.2 and glassfish5.0

CommentsController :

package ch.hearc.controllers;

import ch.hearc.entities.Comments;
import ch.hearc.controllers.util.JsfUtil;
import ch.hearc.controllers.util.PaginationHelper;
import ch.hearc.facades.CommentsFacade;

import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
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 javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@Named("commentsController")
@SessionScoped
public class CommentsController implements Serializable {

    private Comments current;
    private DataModel items = null;
    @EJB
    private ch.hearc.facades.CommentsFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    public CommentsController() {
    }

    public Comments getSelected() {
        if (current == null) {
            current = new Comments();
            selectedItemIndex = -1;
        }
        return current;
    }

    private CommentsFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {

        current = (Comments) getItems().getRowData();
        System.out.println(current);
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Comments();

        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CommentsCreated"));
            return "/posts/View.xhtml";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Comments) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CommentsUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Comments) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CommentsDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public Comments getComments(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    @FacesConverter(forClass = Comments.class)
    public static class CommentsControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CommentsController controller = (CommentsController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "commentsController");
            return controller.getComments(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 Comments) {
                Comments o = (Comments) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Comments.class.getName());
            }
        }

    }

}

PostsController :

package ch.hearc.controllers;

import ch.hearc.entities.Posts;
import ch.hearc.controllers.util.JsfUtil;
import ch.hearc.controllers.util.PaginationHelper;
import ch.hearc.facades.PostsFacade;

import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
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 javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@Named("postsController")
@RequestScoped
public class PostsController implements Serializable {

    private Posts current;
    private DataModel items = null;
    @EJB
    private ch.hearc.facades.PostsFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    public PostsController() {
    }

    public Posts getSelected() {
        if (current == null) {
            current = new Posts();
            selectedItemIndex = -1;
        }
        return current;
    }

    private PostsFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Posts) getItems().getRowData();
        System.out.println(current);
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Posts();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PostsCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Posts) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PostsUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Posts) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PostsDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public Posts getPosts(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    @FacesConverter(forClass = Posts.class)
    public static class PostsControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            PostsController controller = (PostsController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "postsController");
            return controller.getPosts(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 Posts) {
                Posts o = (Posts) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Posts.class.getName());
            }
        }
    }
}

Posts/View.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">

    <ui:composition template="/template_main.xhtml">
        <ui:define name="title">
            <h:outputText value="#{bundle.ViewPostsTitle}"></h:outputText>
        </ui:define>
        <ui:define name="body">
            <div class="jumbotron">
                <h1 class="display-4">#{postsController.selected.title}</h1>
                <p class="lead">#{postsController.selected.body}</p>
                <hr class="my-4"/>
                <small>
                    <h4> By #{postsController.selected.userId.firstname} #{postsController.selected.userId.lastname}</h4>
                       Posted the <h:outputText value="#{postsController.selected.pubDate}">
                        <f:convertDateTime pattern="d-M-yyyy" />
                    </h:outputText>
                </small>
                <p>If this post you help you can vote by clicking the button below</p>
                <a class="btn btn-primary btn-lg" href="#" role="button">Was this helpful?</a>
          </div>


          <form class="card p-2">
            <div class="input-group">
              <textarea class="form-control" placeholder="Post your opinion!" type="text"/>
              <div class="input-group-append">
                <button type="submit" class="btn btn-secondary">Post</button>
              </div>
            </div>
          </form>

          <hr/>

          <h4 class="d-flex justify-content-between align-items-center mb-3">
            <span class="text-muted">Comments</span>
            <span class="badge badge-secondary badge-pill">#{postsController.selected.commentsCollection.size()}</span>
          </h4>
          <ul class="list-group mb-3">
              <ui:repeat value="#{postsController.selected.commentsCollection}" var="comment">
                <li class="list-group-item d-flex justify-content-between lh-condensed">
                 <div>
                     <h6 class="my-0">#{comment.body}</h6>
                     <small class="text-muted">Posted by #{comment.usersId.firstname} #{comment.usersId.lastname}</small>
                 </div>
                    <span class="text-muted"></span>
               </li>             
              </ui:repeat>
          </ul>


            <h:form>
                <h:panelGrid columns="2">
                    <h:outputLabel value="#{bundle.CreateCommentsLabel_body}" for="body" />
                    <h:inputText id="body" value="#{commentsController.selected.body}" title="#{bundle.CreateCommentsTitle_body}" />
                    <h:outputLabel value="#{bundle.CreateCommentsLabel_rate}" for="rate" />
                    <h:inputText id="rate" value="#{commentsController.selected.rate}" title="#{bundle.CreateCommentsTitle_rate}" />
                    <h:outputLabel value="#{bundle.CreateCommentsLabel_postId}" for="postId" />
                    <h:selectOneMenu id="postId" value="#{commentsController.selected.postId}" title="#{bundle.CreateCommentsTitle_postId}" required="true" requiredMessage="#{bundle.CreateCommentsRequiredMessage_postId}">
                        <f:selectItems value="#{postsController.itemsAvailableSelectOne}"/>
                    </h:selectOneMenu>
                    <h:outputLabel value="#{bundle.CreateCommentsLabel_usersId}" for="usersId" />
                    <h:selectOneMenu id="usersId" value="#{commentsController.selected.usersId}" title="#{bundle.CreateCommentsTitle_usersId}" required="true" requiredMessage="#{bundle.CreateCommentsRequiredMessage_usersId}">
                        <f:selectItems value="#{usersController.itemsAvailableSelectOne}"/>
                    </h:selectOneMenu>
                </h:panelGrid>
                <br />
                <h:commandLink action="#{commentsController.create}" value="#{bundle.CreateCommentsSaveLink}">
                </h:commandLink>
                <br />
                <br />
                <h:commandLink action="#{commentsController.prepareList}" value="#{bundle.CreateCommentsShowAllLink}" immediate="true"/>
                <br />
                <br />
                <h:link outcome="/index" value="#{bundle.CreateCommentsIndexLink}"/>
            </h:form>
        </ui:define>
    </ui:composition>

</html>

Aucun commentaire:

Enregistrer un commentaire