Skip to content
This repository has been archived by the owner on Mar 13, 2022. It is now read-only.

Commit

Permalink
add review dataInit and fix bug
Browse files Browse the repository at this point in the history
  • Loading branch information
OoiJunHao committed Apr 11, 2021
1 parent b3f5322 commit 8a49566
Show file tree
Hide file tree
Showing 14 changed files with 203 additions and 116 deletions.
2 changes: 1 addition & 1 deletion OTFood-ejb/nbproject/project.properties
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ includes=**
j2ee.compile.on.save=true
j2ee.deploy.on.save=true
j2ee.platform=1.8
j2ee.platform.classpath=
j2ee.platform.classpath=${j2ee.server.home}/modules/bean-validator.jar:${j2ee.server.home}/modules/cdi-api.jar:${j2ee.server.home}/modules/endorsed/grizzly-npn-bootstrap.jar:${j2ee.server.home}/modules/endorsed/jakarta.annotation-api.jar:${j2ee.server.home}/modules/endorsed/jakarta.xml.bind-api.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/javax.batch-api.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/weld-osgi-bundle.jar:${j2ee.server.middleware}/mq/lib/jaxm-api.jar
j2ee.platform.classpath=${j2ee.server.home}/modules/bean-validator.jar:${j2ee.server.home}/modules/cdi-api.jar:${j2ee.server.home}/modules/endorsed/grizzly-npn-bootstrap.jar:${j2ee.server.home}/modules/endorsed/jakarta.annotation-api.jar:${j2ee.server.home}/modules/endorsed/jakarta.xml.bind-api.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/javax.batch-api.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/weld-osgi-bundle.jar:${j2ee.server.middleware}/mq/lib/jaxm-api.jar
j2ee.platform.embeddableejb.classpath=${j2ee.server.home}/lib/embedded/glassfish-embedded-static-shell.jar
j2ee.platform.wscompile.classpath=${j2ee.server.home}/modules/webservices-osgi.jar
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,10 @@ public List<MealEntity> sortMealEntityByRating() {
}

@Override
public List<MealEntity> retrieveTop5MealEntityByRating() {
public List<MealEntity> retrieveTop5MealEntityByRating() { // will just give 6 because of the layout of index.html
List<MealEntity> sortedList = sortMealEntityByRating();
List<MealEntity> top5Meals = new ArrayList<>();
for (int i = 0; i < 5; i++) {
for (int i = 0; i < 6; i++) {
top5Meals.add(sortedList.get(i));
}
return top5Meals;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
import entity.MealEntity;
import entity.OTUserEntity;
import entity.ReviewEntity;
import java.util.ArrayList;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Set;
import javax.ejb.EJB;
Expand Down Expand Up @@ -67,6 +68,10 @@ public Long addReview(ReviewEntity review, Long userId, Long mealId) throws Revi
meal.getReviews().add(review);
review.setUser(user);
review.setMeal(meal);

// refresh the average rating for the meal
meal.setAverageRating(calculateAverageRating(meal)); // there seems to be a problem here haha

em.persist(review);
em.flush();
return review.getReviewId();
Expand All @@ -90,6 +95,17 @@ public Long addReview(ReviewEntity review, Long userId, Long mealId) throws Revi
}
}

private BigDecimal calculateAverageRating(MealEntity meal) {
if (meal.getReviews().isEmpty()) {
return BigDecimal.valueOf(0);
}
BigDecimal sum = BigDecimal.valueOf(0);
for (ReviewEntity review : meal.getReviews()) {
sum = sum.add(BigDecimal.valueOf(review.getRating()));
}
return sum.divide(BigDecimal.valueOf(meal.getReviews().size()), 2, RoundingMode.HALF_UP);
}

private String prepareInputDataValidationErrorsMessage(Set<ConstraintViolation<ReviewEntity>> constraintViolations) {
String msg = "Input data validation error!:";

Expand Down Expand Up @@ -167,9 +183,12 @@ public void deleteReviewByUserId(Long userId, Long reviewId) throws UserNotFound
MealEntity meal = reviewToBeDeleted.getMeal();
meal.getReviews().remove(reviewToBeDeleted);
em.remove(reviewToBeDeleted);
// refresh the average rating for the meal
meal.setAverageRating(calculateAverageRating(meal));
} else {
throw new DeleteReviewException("either user or review cannot be detected!");
}

}

@Override
Expand All @@ -183,22 +202,11 @@ public void editReviewByUserId(Long userId, ReviewEntity review) throws NoReview
throw new UpdateReviewException("No review detected!");
}
}

public List<ReviewEntity> top2ReviewsForTop5Meals() {
List<ReviewEntity> listOfReviews = new ArrayList<>();
List<MealEntity> top5Meals = mealEntitySessionBeanLocal.retrieveTop5MealEntityByRating();
for (MealEntity meal : top5Meals) {
List<ReviewEntity> top2 = retrieveTop2ReviewsOfMeal(meal.getMealId());
listOfReviews.addAll(top2);
}
return listOfReviews;

}

private List<ReviewEntity> retrieveTop2ReviewsOfMeal(long mealId) {
Query query = em.createQuery("SELECT review FROM MealEntity meal JOIN meal.reviews review WHERE meal.mealId = :mealId ORDER BY review.rating DESC");
query.setParameter("mealId", mealId);
query.setMaxResults(2);

@Override
public List<ReviewEntity> retrieveLatestReviews() {
Query query = em.createQuery("SELECT r FROM ReviewEntity r ORDER BY r.reviewDate DESC");
query.setMaxResults(12);
return query.getResultList();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ public interface ReviewEntitySessionBeanLocal {

public void editReviewByUserId(Long userId, ReviewEntity review) throws NoReviewFoundException, UserNotFoundException, UpdateReviewException;

public List<ReviewEntity> top2ReviewsForTop5Meals();

public List<ReviewEntity> retrieveAllReviews();

public List<ReviewEntity> retrieveLatestReviews();

}
1 change: 0 additions & 1 deletion OTFood-ejb/src/java/entity/CreditCardEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
package entity;

import java.io.Serializable;
import java.util.ArrayList;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
Expand Down
14 changes: 8 additions & 6 deletions OTFood-ejb/src/java/entity/MealEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
Expand Down Expand Up @@ -49,10 +50,11 @@ public class MealEntity implements Serializable {
@NotNull
@Min(0)
private Integer calorie;
@Min(0)
@Max(5)
@NotNull
private Integer averageRating;
@Column(nullable = false, precision = 11, scale = 2)
@DecimalMin("0.00")
@DecimalMax("5.00")
private BigDecimal averageRating;
@Lob
@Column(nullable = false)
@Size(min = 0)
Expand Down Expand Up @@ -88,7 +90,7 @@ public MealEntity(String name, BigDecimal price, String description, Integer cal
this.price = price;
this.description = description;
this.calorie = calorie;
this.averageRating = 5;
this.averageRating = BigDecimal.valueOf(0);
this.name = name;
this.image = image;
this.categories = inputCategories;
Expand Down Expand Up @@ -158,11 +160,11 @@ public void setMealId(Long mealId) {
this.mealId = mealId;
}

public Integer getAverageRating() {
public BigDecimal getAverageRating() {
return averageRating;
}

public void setAverageRating(Integer averageRating) {
public void setAverageRating(BigDecimal averageRating) {
this.averageRating = averageRating;
}

Expand Down
3 changes: 2 additions & 1 deletion OTFood-ejb/src/java/entity/PromoCodeEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
Expand Down Expand Up @@ -53,7 +54,7 @@ public class PromoCodeEntity implements Serializable {
private PromoCodeTypeEnum discountCodeTypeEnum;
@Column(nullable = false)
private Boolean isAvailable;
@OneToMany(mappedBy = "promoCode")
@OneToMany(mappedBy = "promoCode", fetch=FetchType.EAGER)
private List<SaleTransactionEntity> saleTransaction;

public PromoCodeEntity() {
Expand Down
37 changes: 13 additions & 24 deletions OTFood-war/src/java/jsf/managedbean/IndexManagedBean.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,26 +30,21 @@ public class IndexManagedBean {

@EJB(name = "MealEntitySessionBeanLocal")
private MealEntitySessionBeanLocal mealEntitySessionBeanLocal;




private List<MealEntity> top5Meals;
private List<ReviewEntity> top2ReviewsForTop5Meals;
private List<ReviewEntity> latestReviews;
private List<RankingMeal> mealsWithRank;



/**
* Creates a new instance of IndexManagedBean
*/
public IndexManagedBean() {
mealsWithRank = new ArrayList<>();
top5Meals = new ArrayList<>();
mealsWithRank = new ArrayList<>();
}

@PostConstruct
public void postConstruct() {
top5Meals = mealEntitySessionBeanLocal.retrieveTop5MealEntityByRating();
top2ReviewsForTop5Meals = reviewEntitySessionBeanLocal.top2ReviewsForTop5Meals();
latestReviews = reviewEntitySessionBeanLocal.retrieveLatestReviews();
for (int i = 0; i < top5Meals.size(); i++) {
mealsWithRank.add(new RankingMeal(top5Meals.get(i), i+1));
}
Expand All @@ -64,14 +59,6 @@ public void setTop5Meals(List<MealEntity> top5Meals) {
this.top5Meals = top5Meals;
}

public List<ReviewEntity> getTop2ReviewsForTop5Meals() {
return top2ReviewsForTop5Meals;
}

public void setTop2ReviewsForTop5Meals(List<ReviewEntity> top2ReviewsForTop5Meals) {
this.top2ReviewsForTop5Meals = top2ReviewsForTop5Meals;
}

public List<RankingMeal> getMealsWithRank() {
return mealsWithRank;
}
Expand All @@ -80,10 +67,12 @@ public void setMealsWithRank(List<RankingMeal> mealsWithRank) {
this.mealsWithRank = mealsWithRank;
}







public List<ReviewEntity> getLatestReviews() {
return latestReviews;
}

public void setLatestReviews(List<ReviewEntity> latestReviews) {
this.latestReviews = latestReviews;
}

}
40 changes: 27 additions & 13 deletions OTFood-war/src/java/jsf/managedbean/ViewBentoManagedBean.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import ejb.session.stateless.MealEntitySessionBeanLocal;
import ejb.session.stateless.ReviewEntitySessionBeanLocal;
import entity.BentoEntity;
import entity.MealEntity;
import entity.OTUserEntity;
import entity.ReviewEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
Expand Down Expand Up @@ -43,7 +45,7 @@ public class ViewBentoManagedBean implements Serializable {

@EJB
private MealEntitySessionBeanLocal mealEntitySessionBeanLocal;

@Inject
private cartManagedBean cartManagedBean;

Expand All @@ -53,9 +55,9 @@ public class ViewBentoManagedBean implements Serializable {
private String selectedCategory;
private BentoEntity selectedBento;
private int selectedBentoQuantity;

private List<ReviewEntity> currentBentoReviews;

private int rating;
private String review;

Expand Down Expand Up @@ -89,36 +91,48 @@ public void refreshListByTabSelected(TabChangeEvent event) {
setSelectedCategory(event.getTab().getTitle());
System.out.println("current category " + getSelectedCategory());
setListOfBentos(mealEntitySessionBeanLocal.retrieveBentosByCategory(currentTabId));
System.out.println("No of Bentos: " + this.listOfBentos.toString());
System.out.println("No of Bentos: " + this.listOfBentos.toString());
}



public void getListOfBentosByCategory(AjaxBehaviorEvent event) {
this.setListOfBentos(mealEntitySessionBeanLocal.retrieveBentosByCategory(getSelectedCategory()));
}

public void addBentoToCart(ActionEvent event) {
cartManagedBean.setAmtToCart(selectedBentoQuantity);
cartManagedBean.addToCart(selectedBento);
selectedBentoQuantity = 1;
PrimeFaces.current().ajax().update("cartForm");
}

public void addSingleBentoToCart(ActionEvent event) {
BentoEntity selectedBento = (BentoEntity) event.getComponent().getAttributes().get("selected");
cartManagedBean.setAmtToCart(1);
cartManagedBean.addToCart(selectedBento);
PrimeFaces.current().ajax().update("cartForm");
}

public void loadBentoReviews() {
currentBentoReviews = new ArrayList<>();
selectedBento.getReviews().size();
currentBentoReviews = selectedBento.getReviews();

class comp implements Comparator<ReviewEntity> {
@Override
public int compare(ReviewEntity o1, ReviewEntity o2) {
if (o1.getReviewDate().after(o2.getReviewDate())) {
return -1;
} else {
return 1;
}
}
}

this.currentBentoReviews.sort(new comp());

System.out.println("reviews: " + currentBentoReviews);
}

public void addReview(ActionEvent event) {
try {
ReviewEntity reviewToAdd = new ReviewEntity(this.rating, this.review, new Date());
Expand All @@ -131,15 +145,15 @@ public void addReview(ActionEvent event) {
System.out.println("CURRENTLTY ON ---> " + this.selectedBento.getName());
System.out.println("HOW MANY REVIEWSS WTFF ---------> " + this.selectedBento.getReviews().size());
System.out.println("HOW MANY REVIEWSS ---------> " + this.currentBentoReviews.size());



FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Review successfully added!", null));
} catch (ReviewExistException | UnknownPersistenceException | UserNotFoundException | InputDataValidationException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error has occured: " + ex.getMessage(), null));
} catch (MealNotFoundException ex) {
Logger.getLogger(ViewBentoManagedBean.class.getName()).log(Level.SEVERE, null, ex);//will never hit this
}
}

/**
* @return the listOfBentos
*/
Expand Down Expand Up @@ -267,4 +281,4 @@ public String getReview() {
public void setReview(String review) {
this.review = review;
}
}
}
5 changes: 3 additions & 2 deletions OTFood-war/web/index.xhtml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
<div>


<p:panel header="Rank #{meal.rank}" style="text-align: center; font-size: 50px; width: 90%;background-size: 100%; font-family: Camphor,Open Sans,Segoe UI,sans-serif;">
<p:panel header="Rank ##{meal.rank}" style="text-align: center; font-size: 50px; width: 90%;background-size: 100%; font-family: Camphor,Open Sans,Segoe UI,sans-serif;">
<h:panelGrid class="gridItems">
<f:facet name='header'>
<p:graphicImage url="/uploadedFiles/bentos/#{meal.meal.image}.jpg" style="text-align: center; height: auto; width:60%;"/>
Expand All @@ -48,8 +48,9 @@
</p:dataView>
</h:form>
<p:separator/>
<h1 style="text-align: center; font-size: 40px; color: white; font-family: Camphor,Open Sans,Segoe UI,sans-serif;">LATEST REVIEWS</h1>
<div id="reviews" class="ui-g-12">
<p:carousel value="#{indexManagedBean.top2ReviewsForTop5Meals}" var="product" responsive="true">
<p:carousel value="#{indexManagedBean.latestReviews}" var="product" responsive="true">
<div class="product">
<div class="product-grid-item p-p-5">
<div class="product-grid-item-top">
Expand Down
2 changes: 1 addition & 1 deletion OTFood-war/web/userPages/checkout.xhtml
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@
</p:dialog>

<h:form id="mealDetails">
<p:dialog header="Edit Purchase Details (#{cartManagedBean.selectedItem.meal.name})" showEffect="fade" closable="true" resizable="false" widgetVar="editItemsDialog" modal="true" closeOnEscape="true" draggable="false">
<p:dialog header="Edit Purchase Details (#{cartManagedBean.selectedItem.meal.name})" showEffect="fade" closable="true" resizable="false" widgetVar="editItemsDialog" closeOnEscape="true" draggable="false">
<p:outputPanel class="ui-fluid">
<p:outputPanel rendered="#{not empty cartManagedBean.selectedItem}">
<br/>
Expand Down
Loading

0 comments on commit 8a49566

Please sign in to comment.