Example usage for org.joda.time DateMidnight plusDays

List of usage examples for org.joda.time DateMidnight plusDays

Introduction

In this page you can find the example usage for org.joda.time DateMidnight plusDays.

Prototype

public DateMidnight plusDays(int days) 

Source Link

Document

Returns a copy of this date plus the specified number of days.

Usage

From source file:org.filteredpush.qc.date.DateUtils.java

License:Apache License

/**
 * Given a string that may be a date or a date range, extract a interval of
 * dates from that date range (ignoring time (thus the duration for the 
 * interval will be from one date midnight to another).
 * /*ww w  . j  a  v a 2s  .  c om*/
 * This probably is not the method you want - given 1950-01-05, it returns an
 * interval from midnight as the start of the 5th to midnight on the start of the 6th,
 * simply grabbing start end days from this interval will return 5 and 6, which
 * probably isn't what you are expecting.  
 * 
 * @see DateUtils#extractInterval(String) which is probably the method you want.
 * 
 * @param eventDate a string containing a dwc:eventDate from which to extract an interval.
 * @return An interval from one DateMidnight to another DateMidnight, null if no interval can be extracted.
 */
public static Interval extractDateInterval(String eventDate) {
    Interval result = null;
    DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM").getParser(),
            DateTimeFormat.forPattern("yyyy").getParser(),
            ISODateTimeFormat.dateOptionalTimeParser().getParser() };
    DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
    if (eventDate != null && eventDate.contains("/") && isRange(eventDate)) {
        String[] dateBits = eventDate.split("/");
        try {
            // must be at least a 4 digit year.
            if (dateBits[0].length() > 3 && dateBits[1].length() > 3) {
                DateMidnight startDate = DateMidnight.parse(dateBits[0], formatter);
                DateMidnight endDate = DateMidnight.parse(dateBits[1], formatter);
                if (dateBits[1].length() == 4) {
                    result = new Interval(startDate, endDate.plusMonths(12).minusDays(1));
                } else if (dateBits[1].length() == 7) {
                    result = new Interval(startDate, endDate.plusMonths(1).minusDays(1));
                } else {
                    result = new Interval(startDate, endDate);
                }
            }
        } catch (Exception e) {
            // not a date range
            logger.error(e.getMessage());
        }
    } else {
        try {
            DateMidnight startDate = DateMidnight.parse(eventDate, formatter);
            logger.debug(eventDate);
            logger.debug(startDate);
            if (eventDate.length() == 4) {
                result = new Interval(startDate, startDate.plusMonths(12).minusDays(1));
            } else if (eventDate.length() == 7) {
                result = new Interval(startDate, startDate.plusMonths(1).minusDays(1));
            } else {
                result = new Interval(startDate, startDate.plusDays(1));
            }
        } catch (IllegalFieldValueException ex) {
            // can parse as a date but some token has an out of range value
            logger.debug(ex);
        } catch (Exception e) {
            // not a date
            logger.error(e.getMessage(), e);
        }
    }
    return result;
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

License:Apache License

public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  www  . j  a  v  a2  s.  c o  m*/
        printRequest(request);

        sessionId.set(request.getSession().getId());
        String dataSource = request.getParameter("_dataSource");

        // List grid export
        if ("export".equals(request.getParameter("_operationType"))) {
            exportData(dataSource, response);
            return;
        }

        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "-1");

        if ("getMenu".equals(dataSource)) {
            response.getWriter().write(listServices());
        } else if ("userInfo".equals(dataSource)) {
            ServiceContext ctx = ServiceContextStore.get();
            PrintWriter out = response.getWriter();
            out.print(ctx.getUserId());
            for (String role : ctx.getRoles()) {
                out.print(",");
                out.print(role);
            }
            out.flush();
        } else if ("createDataSource".equals(dataSource)) {
            HashMap<String, String> classToServiceName = new HashMap<String, String>();
            for (ServiceDescription serviceDesc : getServiceDescription()) {
                log.log(Level.INFO, "Service translation from {0} to {1}",
                        new Object[] { serviceDesc.getExpectedClass().getName(), serviceDesc.getName() });
                classToServiceName.put(serviceDesc.getExpectedClass().getName(), serviceDesc.getName());
            }
            GuiDataSourceService dataSourceService = getGuiDataSourceService();
            dataSourceService.setServiceMapping(ServiceContextStore.get(), classToServiceName);

            StringBuilder output = new StringBuilder();
            output.append("dataSources###");
            List<GuiDataSource> allDataSources = dataSourceService.findAll(ServiceContextStore.get());
            for (GuiDataSource dataSourceDef : allDataSources) {
                ds2Ref.put(dataSourceDef.getBaseClass(), dataSourceDef.getTitleField());
                dataSourceDef.setBaseClass(null);
                log.log(Level.INFO, "Entity def for {0}", dataSourceDef.getXxxID());
                dataSourceDef.setDataURL(getServiceUrl(request));

                output.append("$wnd.isc.RestDataSource.create(")
                        .append(mapObjToOutput(dataSourceDef, 6, new Stack<Object>(), true, false))
                        .append(");\n");
            }

            ListSettingsService listInstance = (ListSettingsService) findService(LIST_SETTINGS_SERVICE)
                    .getInstance();
            List<ListSettings> guiList = listInstance.findUserSettings(ServiceContextStore.get());
            for (ListSettings listSettings : guiList) {
                output.append("\n###").append(listSettings.getListID()).append("###")
                        .append(listSettings.getSettings());
            }

            log.log(Level.INFO, "Create datasource {0}", output.toString());
            response.getWriter().append(output);

        } else if (findService(dataSource) != null) {
            ServiceDescription serviceDesc = findService(dataSource);
            String operationType = request.getParameter("_operationType");
            String methodName = request.getParameter("_operationId");

            if (methodName != null && !methodName.endsWith("_fetch")) {
                log.log(Level.FINER, "Executing method '" + dataSource + "." + methodName + "'");
                MethodDescription methodDescription = serviceDesc.getOtherMethods().get(methodName);
                if (methodDescription != null) {
                    Object valObj = null;
                    HashMap<String, Object> jsData = unifyRequest(request);
                    Object[] params = prepareMethodParam(jsData, true, methodDescription.parameterNames,
                            methodDescription.method.getParameterTypes());
                    // Resolve "ids" for iterations
                    int iterate = -1;
                    if (jsData.get("ids") != null) {
                        Class<?>[] paramTypes = methodDescription.method.getParameterTypes();
                        for (int i = 0; i < paramTypes.length; i++) {
                            if (Long.class.equals(paramTypes[i]) || paramTypes[i].equals(Long.TYPE)
                                    && methodDescription.parameterNames[i].equals("id") && params[i] == null) {
                                iterate = i;
                                break;
                            } else if (Collection.class.isAssignableFrom(paramTypes[i])
                                    && methodDescription.parameterNames[i].equals("ids") && params[i] == null) {
                                List<Long> longList = new ArrayList<Long>();
                                String ids = (String) jsData.get("ids");
                                String[] idSplit = ids.split(",");
                                for (int k = 0; k < idSplit.length; k++) {
                                    if (idSplit[i].length() > 0) {
                                        longList.add(Long.parseLong(idSplit[i]));
                                    }
                                }
                                params[i] = longList;
                                break;
                            }
                        }
                    }

                    if (iterate != -1) {
                        if (log.isLoggable(Level.FINER)) {
                            for (int j = 0; j < params.length; j++) {
                                log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                            }
                        }
                        String ids = (String) jsData.get("ids");
                        String[] idSplit = ids.split(",");
                        ArrayList<Object> listResult = new ArrayList<Object>();
                        valObj = listResult;
                        for (int i = 0; i < idSplit.length; i++) {
                            if (idSplit[i].length() > 0) {
                                params[iterate] = Long.parseLong(idSplit[i]);
                                Object subValObj = methodDescription.method.invoke(serviceDesc.getInstance(),
                                        params);
                                if (subValObj != null && subValObj instanceof Collection) {
                                    listResult.addAll((Collection) subValObj);
                                } else if (subValObj != null) {
                                    listResult.add(subValObj);
                                }
                            }
                        }
                        log.info("Return value: " + valObj);
                    } else if (params != null) {
                        if (log.isLoggable(Level.FINER)) {
                            for (int j = 0; j < params.length; j++) {
                                log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                            }
                        }
                        valObj = methodDescription.method.invoke(serviceDesc.getInstance(), params);
                        log.info("Return value: " + valObj);
                    }
                    Collection<Object> collResult;
                    PagedResult<?> pagedResult = null;
                    if (valObj == null) {
                        collResult = new ArrayList<Object>();
                        for (int i = 0; i < params.length; i++) {
                            if (params[i] != null
                                    && params[i].getClass().equals(serviceDesc.getExpectedClass())) {
                                collResult.add(params[i]);
                                break;
                            }
                        }
                    } else if (valObj instanceof Collection) {
                        collResult = (Collection) valObj;
                    } else if (valObj instanceof PagedResult) {
                        collResult = null;
                        pagedResult = (PagedResult) valObj;
                    } else {
                        ArrayList<Object> serviceResultArray = new ArrayList<Object>();
                        serviceResultArray.add(valObj);
                        collResult = serviceResultArray;
                    }
                    if (collResult != null) {
                        sendResponse(response.getWriter(), 0, collResult.size(), collResult);
                    } else if (pagedResult != null) {
                        sendResponse(response.getWriter(), pagedResult);
                    }
                } else {
                    throw new IllegalArgumentException(
                            "No " + methodName + " operation available on " + dataSource);
                }
            } else if (operationType == null) {
                throw makeApplicationException("Unsupported operation", "ERR9001", "NULL");
            } else if (operationType.equals("fetch") && request.getParameter("id") != null) {
                Long idVal = Long.parseLong(request.getParameter("id"));
                if (serviceDesc.getFindById() != null) {
                    Object serviceResult = serviceDesc.getFindById().invoke(serviceDesc.getInstance(),
                            ServiceContextStore.get(), idVal);
                    ArrayList<Object> serviceResultArray = new ArrayList<Object>();
                    serviceResultArray.add(serviceResult);

                    sendResponse(response.getWriter(), 0, 1, serviceResultArray);
                } else {
                    throw new IllegalArgumentException("No fetch operation available");
                }
            } else if (operationType.equals("fetch")) {
                List<?> serviceResult;
                PagedResult<?> pagedServiceResult = null;

                String sRow = request.getParameter("_startRow");
                int startRow = sRow == null ? 0 : Integer.parseInt(sRow);
                String eRow = request.getParameter("_endRow");
                int endRow = eRow == null ? 0 : Integer.parseInt(eRow);

                ArrayList<String> queryParams = new ArrayList();
                Enumeration pNames = request.getParameterNames();
                while (pNames.hasMoreElements()) {
                    String paramName = (String) pNames.nextElement();
                    if (!paramName.startsWith("_")) {
                        queryParams.add(paramName);
                    } else if ("_sortBy".equals(paramName)) {
                        queryParams.add("sortBy");
                    }
                }

                if (queryParams.size() > 0) {
                    Collection<MethodDescription> methods = serviceDesc.getOtherMethods().values();
                    MethodDescription matchedMethod = null;
                    int matchLength = 1000;
                    for (MethodDescription method : methods) {
                        String[] methodParamNames = method.parameterNames;
                        if (methodParamNames != null && methodParamNames.length >= queryParams.size()
                                && (List.class.isAssignableFrom(method.method.getReturnType())
                                        || PagedResult.class.isAssignableFrom(method.method.getReturnType()))) {
                            boolean matchParam = false;
                            for (String queryParam : queryParams) {
                                matchParam = false;
                                for (String methodParamName : methodParamNames) {
                                    if (queryParam.equals(methodParamName)) {
                                        matchParam = true;
                                        break;
                                    }
                                }
                                if (!matchParam) {
                                    break;
                                }
                            }
                            if (matchParam && method.parameterNames.length < matchLength) {
                                matchedMethod = method;
                                matchLength = method.parameterNames.length;
                            }
                        }
                    }

                    Object[] params = null;
                    if (matchedMethod != null) {
                        HashMap<String, Object> jsData = unifyRequest(request);
                        params = prepareMethodParam(jsData, true, matchedMethod.parameterNames,
                                matchedMethod.method.getParameterTypes());
                    } else {
                        List<ConditionalCriteria> conditions = new ArrayList();
                        for (MethodDescription method : methods) {
                            if (method.getMethodName().equals("findByCondition")) {
                                Class<?>[] parameterTypes = method.method.getParameterTypes();
                                if (List.class.isAssignableFrom(parameterTypes[0])) {
                                    params = new Object[] { conditions };
                                    matchedMethod = method;
                                    break;
                                } else if (parameterTypes.length == 3
                                        && ServiceContext.class.isAssignableFrom(parameterTypes[0])
                                        && List.class.isAssignableFrom(parameterTypes[1])
                                        && PagingParameter.class.isAssignableFrom(parameterTypes[2])) {
                                    endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow;
                                    PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow,
                                            LOOK_AHEAD);
                                    params = new Object[] { ServiceContextStore.get(), conditions,
                                            pagingParam };
                                    matchedMethod = method;
                                    break;
                                } else if (parameterTypes.length == 2
                                        && ServiceContext.class.isAssignableFrom(parameterTypes[0])
                                        && List.class.isAssignableFrom(parameterTypes[1])) {
                                    params = new Object[] { ServiceContextStore.get(), conditions };
                                    matchedMethod = method;
                                    break;
                                }
                            }
                        }
                        if (matchedMethod != null) {
                            for (String queryParam : queryParams) {
                                LeafProperty<?> queryProp = new LeafProperty(queryParam, ScServlet.class);
                                String matchStyle = request.getParameter("_textMatchStyle");
                                String queryValue = request.getParameter(queryParam);
                                if (queryParam.equals("sortBy")) {
                                    queryValue = normalizeAssoc(serviceDesc, request.getParameter("_sortBy"));
                                    if (queryValue.startsWith("+")) {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1),
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderAsc(sortProp));
                                    } else if (queryValue.startsWith("-")) {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1),
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderDesc(sortProp));
                                    } else {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue,
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderAsc(sortProp));
                                    }
                                } else if (queryValue.indexOf('%') != -1) {
                                    conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                            request.getParameter(queryParam) + "%"));
                                } else {
                                    String[] queryParamSplit = queryParam.split("\\.");
                                    Class watchClass = serviceDesc.getExpectedClass();
                                    Object otherEqVal = null;
                                    boolean isString = false;
                                    for (String queryParamPart : queryParamSplit) {
                                        try {
                                            Method method = watchClass.getMethod(
                                                    makeGetMethodName(queryParamPart), (Class[]) null);
                                            watchClass = method.getReturnType();
                                            if (Collection.class.isAssignableFrom(watchClass)) {
                                                // TODO look deeper into class of collection
                                                break;
                                            } else if (Enum.class.isAssignableFrom(watchClass)) {
                                                otherEqVal = Enum.valueOf(watchClass, queryValue);
                                                break;
                                            } else if (String.class.equals(watchClass)) {
                                                isString = true;
                                                break;
                                            } else if (Long.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Long.parseLong(queryValue);
                                                break;
                                            } else if (Integer.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Integer.parseInt(queryValue);
                                                break;
                                            } else if (Double.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Double.parseDouble(queryValue);
                                                break;
                                            } else if (Date.class.equals(watchClass)) {
                                                otherEqVal = dateFormat.parse(queryValue);
                                                break;
                                            } else if (findServiceByClassName(watchClass.getName()) != null
                                                    && "null".equals(queryValue)) {
                                                otherEqVal = "null";
                                                break;
                                            } else if (findServiceByClassName(watchClass.getName()) != null
                                                    && findServiceByClassName(watchClass.getName())
                                                            .getFindById() != null) {
                                                ServiceDescription srvc = findServiceByClassName(
                                                        watchClass.getName());
                                                otherEqVal = srvc.getFindById().invoke(srvc.getInstance(),
                                                        ServiceContextStore.get(), Long.parseLong(queryValue));
                                            }
                                        } catch (NoSuchMethodException nsme) {
                                            // Ignore error, isString will stay false
                                            break;
                                        }
                                    }
                                    boolean isLike = "substring".equals(matchStyle)
                                            || "startsWith".equals(matchStyle);
                                    if ("null".equals(otherEqVal)) {
                                        conditions.add(ConditionalCriteria.isNull(queryProp));
                                    } else if (otherEqVal instanceof Date) {
                                        DateMidnight start = (new DateTime(otherEqVal)).toDateMidnight();
                                        DateMidnight stop = start.plusDays(1);
                                        conditions.add(ConditionalCriteria.between(queryProp, start.toDate(),
                                                stop.toDate()));
                                    } else if (isString && otherEqVal != null && isLike) {
                                        conditions.add(ConditionalCriteria.like(queryProp, otherEqVal));
                                    } else if (isString && "substring".equals(matchStyle)) {
                                        conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                                "%" + request.getParameter(queryParam) + "%"));
                                    } else if (isString && "startsWith".equals(matchStyle)) {
                                        conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                                request.getParameter(queryParam) + "%"));
                                    } else if (otherEqVal != null) {
                                        conditions.add(ConditionalCriteria.equal(queryProp, otherEqVal));
                                    } else {
                                        conditions.add(ConditionalCriteria.equal(queryProp, queryValue));
                                    }
                                }
                            }
                        }
                    }

                    if (matchedMethod != null && params != null) {
                        for (int j = 0; j < params.length; j++) {
                            log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                        }
                        if (matchedMethod.method.getReturnType().equals(PagedResult.class)) {
                            serviceResult = null;
                            pagedServiceResult = (PagedResult) matchedMethod.method
                                    .invoke(serviceDesc.getInstance(), params);
                        } else {
                            serviceResult = (List<?>) matchedMethod.method.invoke(serviceDesc.getInstance(),
                                    params);
                        }
                    } else {
                        throw makeApplicationException("You can''t filter with such condition.", "ERR9015",
                                (Serializable[]) null);
                    }
                } else if (queryParams.size() == 0 && serviceDesc.getFindAll() != null) {
                    Class<?>[] paramTypes = serviceDesc.getFindAll().getParameterTypes();
                    if (paramTypes.length == 2 && paramTypes[0].equals(ServiceContext.class)
                            && paramTypes[1].equals(PagingParameter.class)
                            && serviceDesc.getFindAll().getReturnType().equals(PagedResult.class)) {
                        endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow;
                        PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow, LOOK_AHEAD);
                        pagedServiceResult = (PagedResult<?>) serviceDesc.getFindAll()
                                .invoke(serviceDesc.getInstance(), ServiceContextStore.get(), pagingParam);
                        serviceResult = null;
                    } else if (paramTypes.length == 1 && paramTypes[0].equals(ServiceContext.class)) {
                        serviceResult = (List<? extends Object>) serviceDesc.getFindAll()
                                .invoke(serviceDesc.getInstance(), ServiceContextStore.get());
                    } else {
                        serviceResult = null;
                    }
                } else {
                    throw new ApplicationException("", "No fetch operation available");
                }

                if (pagedServiceResult != null) {
                    sendResponse(response.getWriter(), pagedServiceResult);
                } else {
                    int resultSize = serviceResult == null ? 0 : serviceResult.size();
                    endRow = (endRow == 0 ? resultSize : endRow);
                    sendResponse(response.getWriter(), startRow, endRow < resultSize ? endRow : resultSize,
                            serviceResult);
                }
            } else if (operationType.equals("update") && request.getParameter("id") != null) {
                Object val = serviceDesc.getFindById().invoke(serviceDesc.getInstance(),
                        ServiceContextStore.get(), Long.parseLong(request.getParameter("id")));
                HashMap<String, Object> reqData = unifyRequest(request);
                mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val);
                serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(),
                        ServiceContextStore.get(), val);
                ArrayList<Object> list = new ArrayList<Object>();
                list.add(val);
                sendResponse(response.getWriter(), 0, 1, list);
            } else if ((operationType.equals("add") || operationType.equals("update"))
                    && request.getParameter("id") == null) {
                HashMap<String, Object> reqData = unifyRequest(request);
                Object val = makeNewInstance(serviceDesc.getExpectedClass(), reqData);
                if (val != null) {
                    mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val);
                    serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(),
                            ServiceContextStore.get(), val);
                    ArrayList<Object> list = new ArrayList<Object>();
                    list.add(val);
                    sendResponse(response.getWriter(), 0, 1, list);
                } else {
                    throw makeApplicationException("Can't create new instance", "ERR9003",
                            serviceDesc.getExpectedClass().getName());
                }
            } else {
                throw makeApplicationException("Unsupported operation", "ERR9001", operationType);
            }
        } else {
            throw makeApplicationException("Wrong datasource name", "ERR9002", dataSource);
        }
    } catch (Throwable ex) {
        // Find most relevant exception in embedded exceptions
        ApplicationException appException = null;
        Throwable relevantException = ex;
        while (ex != null) {
            relevantException = ex;
            if (ex instanceof ApplicationException) {
                appException = (ApplicationException) ex;
                break;
            }
            if (ex instanceof ValidationException) {
                break;
            }

            ex = ex.getCause();
        }

        // Prepare message
        String msg = null;
        if (appException != null) {
            msg = translate(appException.getMessage());
            Serializable[] msgParams = appException.getMessageParameters();
            if (msgParams != null) {
                Object[] params = new Object[msgParams.length];
                for (int i = 0; i < msgParams.length; i++) {
                    if (msgParams[i] instanceof Translatable) {
                        params[i] = translate(((Translatable) msgParams[i]).getContent());
                    } else {
                        params[i] = msgParams[i];
                    }
                }
                msg = MessageFormat.format(msg, params);
            }
        } else if (relevantException instanceof ValidationException) {
            StringBuilder b = new StringBuilder();
            for (InvalidValue iv : ((ValidationException) relevantException).getInvalidValues()) {
                b.append("<b>").append(translate(iv.getPropertyName()) + ":</b> " + iv.getMessage())
                        .append("<br/>");
            }
            msg = b.toString();
        } else {
            msg = translate("ERR9000");
            msg = MessageFormat.format(msg,
                    new Object[] { relevantException.getClass().getName(), relevantException.getMessage() });
        }

        // Print stack trace
        log.log(Level.WARNING, "Relevant exception", relevantException);

        if (msg != null) {
            log.log(Level.WARNING, "SENDING BACK ERROR '" + msg + "'");
            response.getWriter()
                    .write("{response:{ status:-1, data:\""
                            + msg.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"")
                            + "\", startRow:0, endRow:0, totalRows:0}}");
        }
        response.flushBuffer();
        // response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        throw new ServletException(msg);
    }
    response.flushBuffer();
}

From source file:org.jasig.portal.events.aggr.PortalEventAggregationManagerImpl.java

License:Apache License

void doPopulateDateDimensions(final DateMidnight start, final DateMidnight end) {
    logger.info("Populating DateDimensions between {} and {}", start, end);

    final List<QuarterDetail> quartersDetails = this.eventAggregationManagementDao.getQuartersDetails();
    final List<AcademicTermDetail> academicTermDetails = this.eventAggregationManagementDao
            .getAcademicTermDetails();/*w  w w .ja  v a2  s . c  o  m*/

    final List<DateDimension> dateDimensions = this.dateDimensionDao.getDateDimensionsBetween(start, end);

    DateMidnight nextDate = start;
    for (final DateDimension dateDimension : dateDimensions) {
        DateMidnight dimensionDate = dateDimension.getDate();
        if (nextDate.isBefore(dimensionDate)) {
            do {
                createDateDimension(quartersDetails, academicTermDetails, nextDate);
                nextDate = nextDate.plusDays(1);
            } while (nextDate.isBefore(dimensionDate));
        } else if (nextDate.isAfter(dimensionDate)) {
            do {
                createDateDimension(quartersDetails, academicTermDetails, dimensionDate);
                dimensionDate = dimensionDate.plusDays(1);
            } while (nextDate.isAfter(dimensionDate));
        }

        nextDate = dimensionDate.plusDays(1);
    }

    //Add any missing dates from the tail
    while (nextDate.isBefore(end)) {
        createDateDimension(quartersDetails, academicTermDetails, nextDate);
        nextDate = nextDate.plusDays(1);
    }
}

From source file:org.jasig.portal.portlets.statistics.BaseStatisticsReportController.java

License:Apache License

/**
 * Build the aggregation {@link DataTable}
 *///from  ww w  .j  av a 2s  .com
protected final DataTable buildAggregationReport(F form) throws TypeMismatchException {
    //Pull data out of form for per-group fetching
    final AggregationInterval interval = form.getInterval();
    final DateMidnight start = form.getStart();
    final DateMidnight end = form.getEnd();

    final DateTime startDateTime = start.toDateTime();
    //Use a query end of the end date at 23:59:59
    final DateTime endDateTime = end.plusDays(1).toDateTime().minusSeconds(1);

    //Get the list of DateTimes used on the X axis in the report
    final List<DateTime> reportTimes = this.intervalHelper.getIntervalStartDateTimesBetween(interval,
            startDateTime, endDateTime, maxIntervals);

    final Map<D, SortedSet<T>> groupedAggregations = createColumnDiscriminatorMap(form);

    //Determine the ValueType of the date/time column. Use the most specific column type possible
    final ValueType dateTimeColumnType;
    if (interval.isHasTimePart()) {
        //If start/end are the same day just display the time
        if (startDateTime.toDateMidnight().equals(endDateTime.toDateMidnight())) {
            dateTimeColumnType = ValueType.TIMEOFDAY;
        }
        //interval has time data and start/end are on different days, show full date time
        else {
            dateTimeColumnType = ValueType.DATETIME;
        }
    }
    //interval is date only
    else {
        dateTimeColumnType = ValueType.DATE;
    }

    //Setup the date/time column description
    final ColumnDescription dateTimeColumn;
    switch (dateTimeColumnType) {
    case TIMEOFDAY: {
        dateTimeColumn = new ColumnDescription("time", dateTimeColumnType, "Time");
        break;
    }
    default: {
        dateTimeColumn = new ColumnDescription("date", dateTimeColumnType, "Date");
    }
    }

    final DataTable table = new JsonDataTable();
    table.addColumn(dateTimeColumn);

    //Setup columns in the DataTable 
    final Set<D> columnGroups = groupedAggregations.keySet();
    for (final D columnMapping : columnGroups) {
        final Collection<ColumnDescription> columnDescriptions = this.getColumnDescriptions(columnMapping,
                form);
        table.addColumns(columnDescriptions);
    }

    //Query for all aggregation data in the time range for all groups.  Only the
    //interval and discriminator data is used from the keys.
    final Set<K> keys = createAggregationsQueryKeyset(columnGroups, form);
    final BaseAggregationDao<T, K> baseAggregationDao = this.getBaseAggregationDao();
    final Collection<T> aggregations = baseAggregationDao.getAggregations(startDateTime, endDateTime, keys,
            extractGroupsArray(columnGroups));

    //Organize the results by group and sort them chronologically by adding them to the sorted set
    for (final T aggregation : aggregations) {
        final D discriminator = aggregation.getAggregationDiscriminator();
        final SortedSet<T> results = groupedAggregations.get(discriminator);
        results.add(aggregation);
    }

    //Build Map from discriminator column mapping to result iterator to allow putting results into
    //the correct column AND the correct time slot in the column
    Comparator<? super D> comparator = getDiscriminatorComparator();
    final Map<D, PeekingIterator<T>> groupedAggregationIterators = new TreeMap<D, PeekingIterator<T>>(
            (comparator));
    for (final Entry<D, SortedSet<T>> groupedAggregationEntry : groupedAggregations.entrySet()) {
        groupedAggregationIterators.put(groupedAggregationEntry.getKey(),
                Iterators.peekingIterator(groupedAggregationEntry.getValue().iterator()));
    }

    /*
     * populate the data, filling in blank spots. The full list of interval DateTimes is used to create every row in the
     * query range. Then the iterator
     */
    for (final DateTime rowTime : reportTimes) {
        // create the row
        final TableRow row = new TableRow();

        // add the date to the first cell
        final Value dateTimeValue;
        switch (dateTimeColumnType) {
        case DATE: {
            dateTimeValue = new DateValue(rowTime.getYear(), rowTime.getMonthOfYear() - 1,
                    rowTime.getDayOfMonth());
            break;
        }
        case TIMEOFDAY: {
            dateTimeValue = new TimeOfDayValue(rowTime.getHourOfDay(), rowTime.getMinuteOfHour(), 0);
            break;
        }
        default: {
            dateTimeValue = new DateTimeValue(rowTime.getYear(), rowTime.getMonthOfYear() - 1,
                    rowTime.getDayOfMonth(), rowTime.getHourOfDay(), rowTime.getMinuteOfHour(), 0, 0);
            break;
        }
        }
        row.addCell(new TableCell(dateTimeValue));

        for (final PeekingIterator<T> groupedAggregationIteratorEntry : groupedAggregationIterators.values()) {
            List<Value> values = null;

            if (groupedAggregationIteratorEntry.hasNext()) {
                final T aggr = groupedAggregationIteratorEntry.peek();
                if (rowTime.equals(aggr.getDateTime())) {
                    //Data is for the correct time slot, advance the iterator
                    groupedAggregationIteratorEntry.next();

                    values = createRowValues(aggr, form);
                }
            }

            //Gap in the data, fill it in using a null aggregation
            if (values == null) {
                values = createRowValues(null, form);
            }

            //Add the values to the row
            for (final Value value : values) {
                row.addCell(value);
            }
        }

        table.addRow(row);
    }

    return table;
}

From source file:org.jasig.portlet.calendar.adapter.CalendarEventsDao.java

License:Apache License

/**
 * Get a JSON-appropriate representation of each recurrence of an event
 * within the specified time period.//  w  ww. j  av  a 2 s. com
 *
 * @param e
 * @param interval
 * @param usersConfiguredDateTimeZone
 * @return
 * @throws IOException
 * @throws URISyntaxException
 * @throws ParseException
 */
protected Set<CalendarDisplayEvent> getDisplayEvents(VEvent e, Interval interval, Locale locale,
        DateTimeZone usersConfiguredDateTimeZone) throws IOException, URISyntaxException, ParseException {

    final VEvent event = (VEvent) e.copy();

    DateTime eventStart;
    DateTime eventEnd = null;

    if (event.getStartDate().getTimeZone() == null && !event.getStartDate().isUtc()) {
        if (log.isDebugEnabled()) {
            log.debug("Identified event " + event.getSummary() + " as a floating event");
        }

        int offset = usersConfiguredDateTimeZone.getOffset(event.getStartDate().getDate().getTime());
        eventStart = new DateTime(event.getStartDate().getDate().getTime() - offset,
                usersConfiguredDateTimeZone);
        if (event.getEndDate() != null) {
            eventEnd = new DateTime(event.getEndDate().getDate().getTime() - offset,
                    usersConfiguredDateTimeZone);
        }

    } else {
        eventStart = new DateTime(event.getStartDate().getDate(), usersConfiguredDateTimeZone);
        if (event.getEndDate() != null) {
            eventEnd = new DateTime(event.getEndDate().getDate(), usersConfiguredDateTimeZone);
        }
    }

    if (eventEnd == null) {
        eventEnd = eventStart;
    }

    // Multi-day events may begin in the past;  make sure to choose a date in range for the first pass...
    final Date firstDayToProcess = interval.contains(event.getStartDate().getDate().getTime())
            ? event.getStartDate().getDate()
            : interval.getStart().toDate();

    DateMidnight startOfTheSpecificDay = new DateMidnight(firstDayToProcess, usersConfiguredDateTimeZone);
    DateMidnight endOfTheSpecificDay = startOfTheSpecificDay.plusDays(1);

    final DateTimeFormatter df = getDateFormatter(locale, usersConfiguredDateTimeZone);
    final DateTimeFormatter tf = getTimeFormatter(locale, usersConfiguredDateTimeZone);
    final Set<CalendarDisplayEvent> events = new HashSet<CalendarDisplayEvent>();
    final Interval eventInterval = new Interval(eventStart, eventEnd);

    do {
        final Interval theSpecificDay = new Interval(startOfTheSpecificDay.getMillis(),
                endOfTheSpecificDay.getMillis(), usersConfiguredDateTimeZone);

        /*
         * Test if the event interval abuts the start of the day or is within the day.
         * This start time check is needed for the corner case where a zero duration interval
         * is set for midnight.
         * The start times are tested directly as opposed to using abuts() because that method
         * also returns true if the intervals abut at the end of the day. We want to associate
         * instant events that start at midnight with the starting day, not the ending day.
         */
        if (theSpecificDay.getStart().isEqual(eventStart) || theSpecificDay.overlaps(eventInterval)) {
            final CalendarDisplayEvent json = new CalendarDisplayEvent(event, eventInterval, theSpecificDay, df,
                    tf);
            events.add(json);
        }

        startOfTheSpecificDay = startOfTheSpecificDay.plusDays(1);
        endOfTheSpecificDay = endOfTheSpecificDay.plusDays(1);

    } while (!startOfTheSpecificDay.isAfter(eventEnd) && interval.contains(startOfTheSpecificDay));

    return events;
}

From source file:org.jasig.portlet.calendar.mvc.controller.AjaxCalendarController.java

License:Apache License

@ResourceMapping
public ModelAndView getEventList(ResourceRequest request, ResourceResponse response) throws Exception {

    // Pull parameters out of the resourceId
    final String resourceId = request.getResourceID();
    final String[] resourceIdTokens = resourceId.split("-");
    final String startDate = resourceIdTokens[0];
    final int days = Integer.parseInt(resourceIdTokens[1]);

    final long startTime = System.currentTimeMillis();
    final List<String> errors = new ArrayList<String>();
    final Map<String, Object> model = new HashMap<String, Object>();
    final PortletSession session = request.getPortletSession();
    // get the user's configured time zone
    final String timezone = (String) session.getAttribute("timezone");
    final DateTimeZone tz = DateTimeZone.forID(timezone);

    // get the period for this request
    final Interval interval = DateUtil.getInterval(startDate, days, request);

    final Set<CalendarDisplayEvent> calendarEvents = helper.getEventList(errors, interval, request);

    int index = 0;
    final Set<JsonCalendarEventWrapper> events = new TreeSet<JsonCalendarEventWrapper>();
    for (CalendarDisplayEvent e : calendarEvents) {
        events.add(new JsonCalendarEventWrapper(e, index++));
    }//from  w  w  w.  j  av  a2 s. c  o  m

    /*
     * Transform the event set into a map keyed by day.  This code is
     * designed to separate events by day according to the user's configured
     * time zone.  This ensures that we keep complicated time-zone handling
     * logic out of the JavaScript.
     *
     * Events are keyed by a string uniquely representing the date that is
     * still orderable.  So that we can display a more user-friendly date
     * name, we also create a map representing date display names for each
     * date keyed in this response.
     */

    // define a DateFormat object that uniquely identifies dates in a way
    // that can easily be ordered
    DateTimeFormatter orderableDf = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd").toFormatter()
            .withZone(tz);

    // define a DateFormat object that can produce user-facing display
    // as user-facing get it from i18N
    final String displayPattern = this.applicationContext.getMessage("date.formatter.display", null,
            "EEE MMM d", request.getLocale());
    // names for dates
    DateTimeFormatter displayDf = new DateTimeFormatterBuilder().appendPattern(displayPattern).toFormatter()
            .withZone(tz);

    // define "today" and "tomorrow" so we can display these specially in the user interface
    DateMidnight now = new DateMidnight(tz);
    String today = orderableDf.print(now);
    String tomorrow = orderableDf.print(now.plusDays(1));

    Map<String, String> dateDisplayNames = new HashMap<String, String>();
    Map<String, List<JsonCalendarEventWrapper>> eventsByDay = new LinkedHashMap<String, List<JsonCalendarEventWrapper>>();
    for (JsonCalendarEventWrapper event : events) {
        String day = orderableDf.print(event.getEvent().getDayStart());

        // if we haven't seen this day before, add entries to the event and date name maps
        if (!eventsByDay.containsKey(day)) {

            // add a list for this day to the eventsByDay map
            eventsByDay.put(day, new ArrayList<JsonCalendarEventWrapper>());

            // Add an appropriate day name for this date to the date names map.
            // If the day appears to be today or tomorrow display a special string value.
            // Otherwise, use the user-facing date format object.
            if (today.equals(day)) {
                dateDisplayNames.put(day,
                        applicationContext.getMessage("today", null, "Today", request.getLocale()));
            } else if (tomorrow.equals(day)) {
                dateDisplayNames.put(day,
                        this.applicationContext.getMessage("tomorrow", null, "Tomorrow", request.getLocale()));
            } else {
                dateDisplayNames.put(day, displayDf.print(event.getEvent().getDayStart()));
            }
        }

        // add the event to the by-day map
        eventsByDay.get(day).add(event);
    }

    log.trace("Prepared the following eventsByDay collection for user {}: {}", request.getRemoteUser(),
            eventsByDay);

    model.put("dateMap", eventsByDay);
    model.put("dateNames", dateDisplayNames);
    model.put("viewName", "jsonView");
    model.put("errors", errors);

    // eTag processing, see https://wiki.jasig.org/display/UPM41/Portlet+Caching
    String etag = String.valueOf(model.hashCode());
    String requestEtag = request.getETag();
    // if the request ETag matches the hash for this response, send back
    // an empty response indicating that cached content should be used
    if (etag.equals(requestEtag)) {
        log.debug("Sending an empty response (due to matched ETag {} for user {})'", requestEtag,
                request.getRemoteUser());

        // Must communicate new expiration time > 0 per Portlet Spec 22.2
        response.getCacheControl().setExpirationTime(1);
        response.getCacheControl().setUseCachedContent(true); // Portal will return cached content or HTTP 304
        // Return null so response is not committed before portal decides to return HTTP 304 or cached response.
        return null;
    }

    log.trace("Sending a full response for user {}", request.getRemoteUser());

    // create new content with new validation tag
    response.getCacheControl().setETag(etag);
    // Must have expiration time > 0 to use response.getCacheControl().setUseCachedContent(true)
    response.getCacheControl().setExpirationTime(1);

    long overallTime = System.currentTimeMillis() - startTime;
    log.debug("AjaxCalendarController took {} ms to produce JSON model", overallTime);

    return new ModelAndView("json", model);
}

From source file:org.jasig.portlet.calendar.mvc.controller.CalendarController.java

License:Apache License

@RequestMapping
public ModelAndView getCalendar(@RequestParam(required = false, value = "interval") String intervalString,
        RenderRequest request) {/*www . j  av  a 2  s . com*/

    PortletSession session = request.getPortletSession(true);

    PortletPreferences prefs = request.getPreferences();

    Map<String, Object> model = new HashMap<String, Object>();

    // get the list of hidden calendars
    @SuppressWarnings("unchecked")
    HashMap<Long, String> hiddenCalendars = (HashMap<Long, String>) session.getAttribute("hiddenCalendars");

    // indicate if the current user is a guest (unauthenticated) user
    model.put("guest", request.getRemoteUser() == null);

    /**
     * Add and remove calendars from the hidden list.  Hidden calendars
     * will be fetched, but rendered invisible in the view.
     */

    // check the request parameters to see if we need to add any
    // calendars to the list of hidden calendars
    String hideCalendar = request.getParameter("hideCalendar");
    if (hideCalendar != null) {
        hiddenCalendars.put(Long.valueOf(hideCalendar), "true");
        session.setAttribute("hiddenCalendars", hiddenCalendars);
    }

    // check the request parameters to see if we need to remove
    // any calendars from the list of hidden calendars
    String showCalendar = request.getParameter("showCalendar");
    if (showCalendar != null) {
        hiddenCalendars.remove(Long.valueOf(showCalendar));
        session.setAttribute("hiddenCalendars", hiddenCalendars);
    }

    // See if we're configured to show or hide the jQueryUI DatePicker.
    // By default, we assume we are to show the DatePicker because that's
    // the classic behavior.
    String showDatePicker = prefs.getValue("showDatePicker", "true");
    model.put("showDatePicker", showDatePicker);

    /**
     * Find our desired starting and ending dates.
     */

    Interval interval = null;

    if (!StringUtils.isEmpty(intervalString)) {
        interval = Interval.parse(intervalString);
        model.put("startDate", new DateMidnight(interval.getStart()).toDate());
        model.put("days", interval.toDuration().getStandardDays());
        model.put("endDate", new DateMidnight(interval.getEnd()));
    } else {
        //StartDate can only be changed via an AJAX request
        DateMidnight startDate = (DateMidnight) session.getAttribute("startDate");
        log.debug("startDate from session is: " + startDate);
        model.put("startDate", startDate.toDate());

        // find how many days into the future we should display events
        int days = (Integer) session.getAttribute("days");
        model.put("days", days);

        // set the end date based on our desired time period
        DateMidnight endDate = startDate.plusDays(days);
        model.put("endDate", endDate.toDate());

        interval = new Interval(startDate, endDate);
    }

    // define "today" and "tomorrow" so we can display these specially in the
    // user interface
    // get the user's configured time zone
    String timezone = (String) session.getAttribute("timezone");
    DateMidnight today = new DateMidnight(DateTimeZone.forID(timezone));
    model.put("today", today.toDate());
    model.put("tomorrow", today.plusDays(1).toDate());

    /**
     * retrieve the calendars defined for this portlet instance
     */

    CalendarSet<?> set = calendarSetDao.getCalendarSet(request);
    List<CalendarConfiguration> calendars = new ArrayList<CalendarConfiguration>();
    calendars.addAll(set.getConfigurations());
    Collections.sort(calendars, new CalendarConfigurationByNameComparator());
    model.put("calendars", calendars);

    Map<Long, Integer> colors = new HashMap<Long, Integer>();
    Map<Long, String> links = new HashMap<Long, String>();
    int index = 0;
    for (CalendarConfiguration callisting : calendars) {

        // don't bother to fetch hidden calendars
        if (hiddenCalendars.get(callisting.getId()) == null) {

            try {

                // get an instance of the adapter for this calendar
                ICalendarAdapter adapter = (ICalendarAdapter) applicationContext
                        .getBean(callisting.getCalendarDefinition().getClassName());

                //get hyperlink to calendar
                String link = adapter.getLink(callisting, interval, request);
                if (link != null) {
                    links.put(callisting.getId(), link);
                }

            } catch (NoSuchBeanDefinitionException ex) {
                log.error("Calendar class instance could not be found: " + ex.getMessage());
            } catch (CalendarLinkException linkEx) {
                // Not an error. Ignore
            } catch (Exception ex) {
                log.error(ex);
            }
        }

        // add this calendar's id to the color map
        colors.put(callisting.getId(), index);
        index++;

    }

    model.put("timezone", session.getAttribute("timezone"));
    model.put("colors", colors);
    model.put("links", links);
    model.put("hiddenCalendars", hiddenCalendars);

    /*
     * Check if we need to disable either the preferences and/or administration links
     */

    Boolean disablePrefs = Boolean.valueOf(prefs.getValue(PREFERENCE_DISABLE_PREFERENCES, "false"));
    model.put(PREFERENCE_DISABLE_PREFERENCES, disablePrefs);
    Boolean disableAdmin = Boolean.valueOf(prefs.getValue(PREFERENCE_DISABLE_ADMINISTRATION, "false"));
    model.put(PREFERENCE_DISABLE_ADMINISTRATION, disableAdmin);

    return new ModelAndView(viewSelector.getCalendarViewName(request), "model", model);
}

From source file:org.jasig.portlet.calendar.util.DateUtil.java

License:Apache License

public static Interval getInterval(DateMidnight start, int days) {
    Interval interval = new Interval(start, start.plusDays(days));
    return interval;

}

From source file:org.jasig.portlet.campuslife.dining.mvc.portlet.MainController.java

License:Apache License

@RenderMapping
public ModelAndView showMainView(final RenderRequest request, String date) {

    // determine if the request represents a mobile browser and set the
    // view name accordingly
    final boolean isMobile = viewSelector.isMobile(request);
    final String viewName = isMobile ? "main-jQM" : "main";
    final ModelAndView mav = new ModelAndView("dining/".concat(viewName));

    if (logger.isDebugEnabled()) {
        logger.debug("Using view name " + viewName + " for main view");
    }// w w  w. ja v  a2  s.  co m

    DateMidnight d;
    if (date == null) {
        d = new DateMidnight();
    } else {
        d = paramFormat.parseLocalDate(date).toDateMidnight();
    }
    final List<DiningHall> halls = menuDao.getDiningHalls(d, request);

    if (halls != null && halls.size() == 1) {
        return showDiningHallView(request, halls.get(0).getKey(), paramFormat.print(d));
    }

    else {
        mav.addObject("diningHalls", menuDao.getDiningHalls(d, request));
        mav.addObject("displayDate", displayFormat.print(d));
        mav.addObject("date", paramFormat.print(d));
        mav.addObject("prev", paramFormat.print(d.minusDays(1)));
        mav.addObject("next", paramFormat.print(d.plusDays(1)));
        return mav;
    }

}

From source file:org.jasig.portlet.campuslife.dining.mvc.portlet.MainController.java

License:Apache License

@RenderMapping(params = "action=diningHall")
public ModelAndView showDiningHallView(final RenderRequest request, final String diningHall,
        final String date) {

    // determine if the request represents a mobile browser and set the
    // view name accordingly
    final boolean isMobile = viewSelector.isMobile(request);
    final String viewName = isMobile ? "diningHall-jQM" : "diningHall";
    final ModelAndView mav = new ModelAndView("dining/".concat(viewName));

    if (logger.isDebugEnabled()) {
        logger.debug("Using view name " + viewName + " for dining hall view");
    }//from  w w  w .j  a va  2  s  .c  om

    final DateMidnight d = paramFormat.parseLocalDate(date).toDateMidnight();
    final DiningHall dh = menuDao.getDiningHall(d, diningHall);
    mav.addObject("diningHall", dh);

    if (dh.getLocationCode() != null) {
        final String url = urlService.getLocationUrl(dh.getLocationCode(), request);
        mav.addObject("locationUrl", url);
    }

    final List<DiningHall> halls = menuDao.getDiningHalls(d, request);
    mav.addObject("hasMultipleLocations", halls.size() > 1);
    mav.addObject("date", paramFormat.print(d));
    mav.addObject("prev", paramFormat.print(d.minusDays(1)));
    mav.addObject("next", paramFormat.print(d.plusDays(1)));
    mav.addObject("displayDate", displayFormat.print(d));

    return mav;

}