MapRestView.java 2.46 KB
package fi.codecrew.moya.rest;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import fi.codecrew.moya.beans.PlaceGroupBeanLocal;
import fi.codecrew.moya.beans.PlaceMapBeanLocal;
import fi.codecrew.moya.model.EventMap;
import fi.codecrew.moya.model.Place;
import fi.codecrew.moya.model.PlaceGroup;

@RequestScoped
@Path("/map")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON })
public class MapRestView {

	@EJB
	private PlaceMapBeanLocal placemapbean;
	@EJB
	private PlaceGroupBeanLocal pgbean;

	@GET
	@Path("/dateJson")
	@Produces("text/javascript")
	public String getAllCards() {
		EventMap map = placemapbean.getActiveMap();

		Map<Integer, Map<Integer, Map<Integer, Integer>>> counts = new HashMap<>();

		for (Place p : map.getPlaces()) {
			PlaceGroup pg = p.getGroup();
			if (pg == null) {
				continue;
			}

			Calendar d = pg.getCreated();
			Integer year = d.get(Calendar.YEAR);
			Integer month = d.get(Calendar.MONTH);
			Integer day = d.get(Calendar.DAY_OF_MONTH);

			Map<Integer, Map<Integer, Integer>> yearmap = counts.get(year);
			if (yearmap == null) {
				yearmap = new HashMap<>();
				counts.put(year, yearmap);
			}

			Map<Integer, Integer> monthMap = yearmap.get(month);
			if (monthMap == null) {
				monthMap = new HashMap<>();
				yearmap.put(month, monthMap);
			}
			Integer dayValue = monthMap.get(day);
			if (dayValue == null) {
				dayValue = 0;
			}
			monthMap.put(day, ++dayValue);
		}

		StringBuilder retSb = new StringBuilder("{ data : [\n");
		boolean empty = true;
		for (Entry<Integer, Map<Integer, Map<Integer, Integer>>> ym : counts.entrySet()) {
			Integer year = ym.getKey();
			for (Entry<Integer, Map<Integer, Integer>> mm : ym.getValue().entrySet()) {
				Integer month = mm.getKey();
				for (Entry<Integer, Integer> dm : mm.getValue().entrySet()) {
					Integer day = dm.getKey();
					if (!empty)
					{
						retSb.append(",");
					} else {
						empty = false;
					}

					retSb.append("  [Date.UTC(")
							.append(year).append(",  ")
							.append(month).append(", ")
							.append(day).append("), ")
							.append(dm.getValue()).append(" ] \n");
				}
			}
		}
		retSb.append("\n] }\n");
		return retSb.toString();
	}
}