Controller.BeanUCV.java Source code

Java tutorial

Introduction

Here is the source code for Controller.BeanUCV.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.joda.time.LocalDate;
import org.primefaces.push.PushContext;
import org.primefaces.push.PushContextFactory;

/*
 Copyright 2008-2013 Clement Levallois
 Authors : Clement Levallois <clementlevallois@gmail.com>
 Website : http://www.clementlevallois.net
    
    
 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
    
 Copyright 2013 Clement Levallois. All rights reserved.
    
 The contents of this file are subject to the terms of either the GNU
 General Public License Version 3 only ("GPL") or the Common
 Development and Distribution License("CDDL") (collectively, the
 "License"). You may not use this file except in compliance with the
 License. You can obtain a copy of the License at
 http://gephi.org/about/legal/license-notice/
 or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the
 specific language governing permissions and limitations under the
 License.  When distributing the software, include this License Header
 Notice in each file and include the License files at
 /cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the
 License Header, with the fields enclosed by brackets [] replaced by
 your own identifying information:
 "Portions Copyrighted [year] [name of copyright owner]"
    
 If you wish your version of this file to be governed by only the CDDL
 or only the GPL Version 3, indicate your decision by adding
 "[Contributor] elects to include this software in this distribution
 under the [CDDL or GPL Version 3] license." If you do not indicate a
 single choice of license, a recipient has the option to distribute
 your version of this file under either the CDDL, the GPL Version 3 or
 to extend the choice of license to its licensees as provided above.
 However, if you add GPL Version 3 code and therefore, elected the GPL
 Version 3 license, then the option applies only if the new code is
 made subject to such option by the copyright holder.
    
 Contributor(s): Clement Levallois
    
 */
@ManagedBean
@SessionScoped
public class BeanUCV implements Serializable {

    @ManagedProperty(value = "#{sharedBean}")
    SharedBean sharedBean;
    private String category;
    private Map<String, String> mapIPToCategories;
    private Map<String, Long> mapIPToTime;
    private String elected;
    private Integer groupSize;
    private String sessionCode;
    ExternalContext ec;

    public BeanUCV() {
        //        timer = new Timer(true);
        //        timer.schedule(timerTask, 0, 2 * 1000L);
    }

    public String getSessionCode() {
        return sessionCode;
    }

    public void setSessionCode(String sessionCodeClient) {

        this.sessionCode = sessionCodeClient + "_uc";
        ec = FacesContext.getCurrentInstance().getExternalContext();

        //setting a cookie to remember user on this session IF there is not already a cookie set. Cookies expire after 4 hours or so.
        Map<String, Object> cookies = ec.getRequestCookieMap();
        Cookie cookie = (Cookie) cookies.get(sessionCode);
        if (cookie == null) {
            HttpServletResponse response = (HttpServletResponse) ec.getResponse();
            String uuid = UUID.randomUUID().toString();
            cookie = new Cookie(sessionCode, uuid);
            cookie.setMaxAge(15000); // Expire time. -1 = by end of current session, 0 = immediately expire it, otherwise just the lifetime in seconds.
            response.addCookie(cookie);
        }

        //if this is a new session code, create an entry in the two shared maps
        if (!sharedBean.getMapSessionCodesToDay().containsKey(sessionCode)) {
            sharedBean.getMapSessionCodesToDay().put(sessionCode, new LocalDate());
            sharedBean.getMapSessionCodesToIPsToCategories().put(sessionCode, new HashMap());
            sharedBean.getMapSessionCodesToIPsToTime().put(sessionCode, new HashMap());
        }
        findAndDeleteOldVotes(5);
        findAndDeleteOldSessionCodes();
        setTheGroupSize();

        //find and delete votes that were cast more than 5 minutes ago
        //find and delete session codes older than 1 day in the shared bean.
    }

    public void setSharedBean(SharedBean sharedBean) {
        this.sharedBean = sharedBean;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        if (category.equals("1")) {
            this.category = ":(";
        } else if (category.equals("2")) {
            this.category = ":)";
        } else if (category.equals("3")) {
            this.category = ":|";
        }
    }

    public Integer getGroupSize() {
        return groupSize;
    }

    public void setGroupSize(Integer groupSize) {
        this.groupSize = groupSize;
    }

    public void confirmGrade() {
        try {
            ec = FacesContext.getCurrentInstance().getExternalContext();
            if (ec == null) {
                return;
            }
            Map<String, Object> cookies = ec.getRequestCookieMap();
            if (cookies == null) {
                return;
            }
            Cookie cookie = (Cookie) cookies.get(sessionCode);
            String ipAddress = cookie.getValue();

            if (!category.equals(null) && ipAddress != null) {
                mapIPToCategories = sharedBean.getOneMapIPToCategories(sessionCode);
                mapIPToCategories.put(ipAddress, category);
                mapIPToTime = sharedBean.getOneMapIPToTime(sessionCode);
                mapIPToTime.put(ipAddress, System.currentTimeMillis());
            } else {
                return;
            }

            elected = computeMostVotedCategory();
            pushMostVotedCategoryToClient();

            //            System.out.println("next value in bean is: " + nextValue);
        } catch (NullPointerException e) {
            System.out.println("NPE in confirmGrade(): " + e.getMessage());
        }
    }

    private void findAndDeleteOldSessionCodes() {
        try {
            Iterator<Entry<String, LocalDate>> iterator = sharedBean.getMapSessionCodesToDay().entrySet()
                    .iterator();
            Entry<String, LocalDate> entry;
            while (iterator.hasNext()) {
                entry = iterator.next();
                if (entry.getValue().isBefore(new LocalDate().minusDays(1))) {
                    sharedBean.getMapSessionCodesToIPsToCategories().remove(entry.getKey());
                    sharedBean.getMapSessionCodesToIPsToTime().remove(entry.getKey());
                    iterator.remove();
                }
            }
        } catch (NullPointerException e) {
            System.out.println("NPE in findAndDeleteOldSessionCodes(): " + e.getMessage());
        }

    }

    private void findAndDeleteOldVotes(Integer minutes) {
        try {
            Iterator<Entry<String, Long>> iterator = sharedBean.getOneMapIPToTime(sessionCode).entrySet()
                    .iterator();
            Entry<String, Long> entry;
            Long now = System.currentTimeMillis();

            //deletes IPS and their votes if older than n minutes
            while (iterator.hasNext()) {
                entry = iterator.next();
                if (now - (minutes * 60000) > entry.getValue()) {
                    //                if (now - 10000 > entry.getValue()) {
                    //we do not delete the vote of the last person
                    if (sharedBean.getOneMapIPToGrade(sessionCode).size() > 1) {
                        sharedBean.getOneMapIPToGrade(sessionCode).remove(entry.getKey());
                        iterator.remove();
                    }
                }

            }
        } catch (NullPointerException e) {
            System.out.println("NPE in findAndDeleteOldVotes(): " + e.getMessage());
        }

    }

    private void setTheGroupSize() {
        //set the group size (+1 if the first user has not added a grade yet)
        if (sharedBean.getMapSessionCodesToIPsToCategories().get(sessionCode).isEmpty()) {
            groupSize = 1;
        } else {
            groupSize = sharedBean.getMapSessionCodesToIPsToCategories().get(sessionCode).size();
        }
    }

    //    @PreDestroy
    //    public void sessionDestroyed() {
    //        System.out.println("stopping timer");
    //        timerTask.cancel();
    //        timer.cancel();
    //    }
    private String computeMostVotedCategory() {

        String mostCat = "";
        int mostVotes = 0;
        Multiset<String> setCountVotes = HashMultiset.create();
        setCountVotes.addAll(sharedBean.getOneMapIPToCategories(sessionCode).values());
        for (String cat : setCountVotes) {
            int countCategory = setCountVotes.count(cat);
            if (countCategory > mostVotes) {
                mostVotes = countCategory;
                mostCat = cat;
            }
        }
        return mostCat;
    }

    //    Timer timer;
    //    TimerTask timerTask = new TimerTask() {
    //
    //        @Override
    //        public void run() {
    //            grade = (float) Math.floor(Math.random() * 20);
    //            System.out.println("random grade created in timer: " + grade);
    //            confirmGrade();
    //            pushAverageGradeToClient();
    //
    //        }
    //    };
    private void pushMostVotedCategoryToClient() {
        Multiset<String> setCategories = HashMultiset.create();
        setCategories.addAll(sharedBean.getOneMapIPToCategories(sessionCode).values());
        System.out.println("multiset to string: " + setCategories.toString());

        String stringToPush = elected + "^";
        System.out.println("most voted cat: " + elected);
        stringToPush = stringToPush + setCategories.toString();
        PushContext ctx = PushContextFactory.getDefault().getPushContext();
        if (ctx != null) {
            ctx.push("/pushIsFuckingGreatUC", stringToPush);
        }
    }
}