Example usage for java.util Calendar DECEMBER

List of usage examples for java.util Calendar DECEMBER

Introduction

In this page you can find the example usage for java.util Calendar DECEMBER.

Prototype

int DECEMBER

To view the source code for java.util Calendar DECEMBER.

Click Source Link

Document

Value of the #MONTH field indicating the twelfth month of the year in the Gregorian and Julian calendars.

Usage

From source file:com.frey.repo.DateUtil.java

/**
 * ?/*from   w  w  w  . j a  v a 2 s .c  o  m*/
 */
public static int getPassDayOfSeason(Date date) {
    int day = 0;

    Date[] seasonDates = getSeasonDate(date);

    Calendar c = Calendar.getInstance();
    c.setTime(date);
    int month = c.get(Calendar.MONTH);

    if (month == Calendar.JANUARY || month == Calendar.APRIL || month == Calendar.JULY
            || month == Calendar.OCTOBER) {//
        day = getPassDayOfMonth(seasonDates[0]);
    } else if (month == Calendar.FEBRUARY || month == Calendar.MAY || month == Calendar.AUGUST
            || month == Calendar.NOVEMBER) {//
        day = getDayOfMonth(seasonDates[0]) + getPassDayOfMonth(seasonDates[1]);
    } else if (month == Calendar.MARCH || month == Calendar.JUNE || month == Calendar.SEPTEMBER
            || month == Calendar.DECEMBER) {//
        day = getDayOfMonth(seasonDates[0]) + getDayOfMonth(seasonDates[1]) + getPassDayOfMonth(seasonDates[2]);
    }
    return day;
}

From source file:com.frey.repo.DateUtil.java

/**
 * ?/*from  w w  w  .  j a v a 2 s .  c  o  m*/
 */
public static Date[] getSeasonDate(Date date) {
    Date[] season = new Date[3];

    Calendar c = Calendar.getInstance();
    c.setTime(date);

    int nSeason = getSeason(date);
    if (nSeason == 1) {//
        c.set(Calendar.MONTH, Calendar.JANUARY);
        season[0] = c.getTime();
        c.set(Calendar.MONTH, Calendar.FEBRUARY);
        season[1] = c.getTime();
        c.set(Calendar.MONTH, Calendar.MARCH);
        season[2] = c.getTime();
    } else if (nSeason == 2) {//
        c.set(Calendar.MONTH, Calendar.APRIL);
        season[0] = c.getTime();
        c.set(Calendar.MONTH, Calendar.MAY);
        season[1] = c.getTime();
        c.set(Calendar.MONTH, Calendar.JUNE);
        season[2] = c.getTime();
    } else if (nSeason == 3) {//
        c.set(Calendar.MONTH, Calendar.JULY);
        season[0] = c.getTime();
        c.set(Calendar.MONTH, Calendar.AUGUST);
        season[1] = c.getTime();
        c.set(Calendar.MONTH, Calendar.SEPTEMBER);
        season[2] = c.getTime();
    } else if (nSeason == 4) {//
        c.set(Calendar.MONTH, Calendar.OCTOBER);
        season[0] = c.getTime();
        c.set(Calendar.MONTH, Calendar.NOVEMBER);
        season[1] = c.getTime();
        c.set(Calendar.MONTH, Calendar.DECEMBER);
        season[2] = c.getTime();
    }
    return season;
}

From source file:com.alkacon.opencms.v8.calendar.CmsSerialDateWidget.java

/**
 * Returns the HTML for a select box for choosing the month.<p>
 * //from w ww .java  2  s.  c  o m
 * @param name the name of the select box
 * @param parameters optional additional parameters
 * @param messages localized messages for localizing the options
 * @param selectedIndex the selected index of the month
 * @return the HTML for a select box for choosing the month
 */
protected String buildSelectMonth(String name, String parameters, CmsMessages messages, int selectedIndex) {

    SimpleDateFormat df = new SimpleDateFormat("MMMM", messages.getLocale());
    Calendar cal = new GregorianCalendar(messages.getLocale());
    cal.set(2000, Calendar.JANUARY, 1);
    List<String> options = new ArrayList<String>(12);
    List<String> values = new ArrayList<String>(12);
    for (int i = 0; i <= Calendar.DECEMBER; i++) {
        // iterate the months
        values.add(String.valueOf(cal.get(Calendar.MONTH)));
        options.add(df.format(cal.getTime()));
        cal.add(Calendar.MONTH, 1);
    }
    // add the name to the parameters
    if (CmsStringUtil.isNotEmpty(parameters)) {
        parameters += " ";
    }
    parameters += "name=\"" + name + "\"";
    return CmsWorkplace.buildSelect(parameters, options, values, selectedIndex, true);
}

From source file:com.wdullaer.materialdatetimepicker.date.DatePickerDialog.java

@Override
public Calendar getEndDate() {
    if (!selectableDays.isEmpty())
        return selectableDays.last();
    if (mMaxDate != null)
        return mMaxDate;
    Calendar output = Calendar.getInstance(getTimeZone());
    output.set(Calendar.YEAR, mMaxYear);
    output.set(Calendar.DAY_OF_MONTH, 31);
    output.set(Calendar.MONTH, Calendar.DECEMBER);
    return output;
}

From source file:org.exoplatform.addon.pulse.service.ws.RestActivitiesStatistic.java

private ChartData buildStatisticByFilter(String maxColumn, String filter, Date fromDate) throws Exception {

    int totalDataCoulumn = 5;
    try {//  w  w  w  .  j  a v a  2 s . c  o  m
        totalDataCoulumn = Integer.parseInt(maxColumn);
    } catch (Exception e) {
        //do nothing
    }

    if (filter.equalsIgnoreCase(FILTER_BY_DAY)) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(fromDate);
        calendar.add(Calendar.DATE, totalDataCoulumn - 1);
        Date toDate = calendar.getTime();

        List<ActivityStatisticBean> list = service.getListActivityStatisticByDate(fromDate, toDate);
        TreeMap<Date, ActivityStatisticBean> dateData = new TreeMap<Date, ActivityStatisticBean>();
        //init empty-data
        for (int i = 0; i < totalDataCoulumn; i++) {
            calendar.clear();
            calendar.setTime(fromDate);
            calendar.add(Calendar.DATE, i);
            Date nextDate = parseDate(partString(calendar.getTime(), "dd/MM/yyyy"), "dd/MM/yyyy");
            dateData.put(nextDate, null);
        }

        List<String> listTitle = new ArrayList<String>();
        List<Long> newUsersData = new ArrayList<Long>();
        List<Long> loginCountData = new ArrayList<Long>();
        List<Long> forumActiveUsersData = new ArrayList<Long>();
        List<Long> newForumPostsData = new ArrayList<Long>();

        List<Long> userConnectionData = new ArrayList<Long>();
        List<Long> socialPostData = new ArrayList<Long>();
        List<Long> emailNotificationData = new ArrayList<Long>();

        ChartData chartData = new ChartData();

        for (ActivityStatisticBean bean : list) {
            dateData.put(parseDate(partString(bean.getCreatedDate(), "dd/MM/yyyy"), "dd/MM/yyyy"), bean);
        }

        for (Date key : dateData.keySet()) {
            ActivityStatisticBean bean = dateData.get(key);
            if (bean != null) {
                listTitle.add(partString(bean.getCreatedDate(), "dd-MM-yyyy"));
                newUsersData.add(bean.getNewUserToday());
                loginCountData.add(bean.getLoginCountToday());
                forumActiveUsersData.add(bean.getForumActiveUserToday());
                newForumPostsData.add(bean.getForumPostToday());

                userConnectionData.add(bean.getUserConnectionCountToday());
                socialPostData.add(bean.getSocialPostCountToday());
                emailNotificationData.add(bean.getEmailNotificationCountToday());
            } else {
                listTitle.add(partString(key, "dd-MM-yyyy"));
                newUsersData.add(0L);
                loginCountData.add(0L);
                forumActiveUsersData.add(0L);
                newForumPostsData.add(0L);
                userConnectionData.add(0L);
                socialPostData.add(0L);
                emailNotificationData.add(0L);
            }
        }

        chartData.setListTitle(listTitle);
        chartData.setNewUsersData(newUsersData);
        chartData.setLoginCountData(loginCountData);
        chartData.setForumActiveUsersData(forumActiveUsersData);
        chartData.setNewForumPostsData(newForumPostsData);

        chartData.setUserConnectionData(userConnectionData);
        chartData.setSocialPostData(socialPostData);
        chartData.setEmailNotificationData(emailNotificationData);
        return chartData;
    }

    if (filter.equalsIgnoreCase(FILTER_BY_WEEK)) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.setTime(fromDate);
        calendar.add(Calendar.WEEK_OF_YEAR, totalDataCoulumn - 1);
        Date nextFewWeek = calendar.getTime();

        List<ActivityStatisticBean> list = service.getListActivityStatisticByDate(fromDate, nextFewWeek);

        List<String> listTitle = new ArrayList<String>();
        List<Long> newUsersData = new ArrayList<Long>();
        List<Long> loginCountData = new ArrayList<Long>();
        List<Long> forumActiveUsersData = new ArrayList<Long>();
        List<Long> newForumPostsData = new ArrayList<Long>();

        List<Long> userConnectionData = new ArrayList<Long>();
        List<Long> socialPostData = new ArrayList<Long>();
        List<Long> emailNotificationData = new ArrayList<Long>();

        ChartData chartData = new ChartData();

        TreeMap<String, List<ActivityStatisticBean>> weekData = new TreeMap<String, List<ActivityStatisticBean>>();
        //init empty-data
        for (int i = 0; i < totalDataCoulumn; i++) {
            calendar.clear();
            calendar.setTime(fromDate);
            calendar.add(Calendar.WEEK_OF_YEAR, i);
            int weekIndex = calendar.get(Calendar.WEEK_OF_YEAR);
            int monthIndex = calendar.get(Calendar.MONTH);
            if (monthIndex == Calendar.DECEMBER && weekIndex == 1)
                weekIndex = 53;
            int year = calendar.get(Calendar.YEAR);
            //goto begin of week
            calendar.clear();
            calendar.set(Calendar.WEEK_OF_YEAR, weekIndex);
            calendar.set(Calendar.YEAR, year);
            //goto end of week
            calendar.add(Calendar.DATE, 6);

            String week = "";
            if (calendar.get(Calendar.MONTH) == Calendar.DECEMBER && calendar.get(Calendar.WEEK_OF_YEAR) == 1) {
                week = 53 + "-" + calendar.get(Calendar.YEAR);
            } else {
                week = calendar.get(Calendar.WEEK_OF_YEAR) + "-" + calendar.get(Calendar.YEAR);
            }
            week = week.length() < 7 ? calendar.get(Calendar.YEAR) + "-" + "0" + week
                    : calendar.get(Calendar.YEAR) + "-" + week;
            weekData.put(week, new ArrayList<ActivityStatisticBean>());
        }

        for (ActivityStatisticBean bean : list) {
            calendar.clear();
            calendar.setTime(bean.getCreatedDate());

            int weekIndex = calendar.get(Calendar.WEEK_OF_YEAR);
            int monthIndex = calendar.get(Calendar.MONTH);
            if (monthIndex == Calendar.DECEMBER && weekIndex == 1)
                weekIndex = 53;
            int year = calendar.get(Calendar.YEAR);
            //goto begin of week
            calendar.clear();
            calendar.set(Calendar.WEEK_OF_YEAR, weekIndex);
            calendar.set(Calendar.YEAR, year);
            //goto end of week
            calendar.add(Calendar.DATE, 6);

            String week = "";
            if (calendar.get(Calendar.MONTH) == Calendar.DECEMBER && calendar.get(Calendar.WEEK_OF_YEAR) == 1) {
                week = 53 + "-" + calendar.get(Calendar.YEAR);
            } else {
                week = calendar.get(Calendar.WEEK_OF_YEAR) + "-" + calendar.get(Calendar.YEAR);
            }
            week = week.length() < 7 ? calendar.get(Calendar.YEAR) + "-" + "0" + week
                    : calendar.get(Calendar.YEAR) + "-" + week;

            if (weekData.containsKey(week)) {
                List<ActivityStatisticBean> listValueOfNode = weekData.get(week);
                listValueOfNode.add(bean);
            } else {
                List<ActivityStatisticBean> listValueOfNode = new ArrayList<ActivityStatisticBean>();
                listValueOfNode.add(bean);
                weekData.put(week, listValueOfNode);
            }
        }

        for (String key : weekData.keySet()) {
            List<ActivityStatisticBean> listValueOfNode = weekData.get(key);
            Long weekNewUsersValue = 0L;
            Long weekLoginCountValue = 0L;
            Long weekForumActiveUsersValue = 0L;
            Long weekNewForumPostsValue = 0L;

            Long weekUserConnectionValue = 0L;
            Long weekSocialPostsValue = 0L;
            Long weekEmailNotificationValue = 0L;

            for (ActivityStatisticBean obj : listValueOfNode) {
                weekNewUsersValue = weekNewUsersValue + obj.getNewUserToday();
                weekLoginCountValue = weekLoginCountValue + obj.getLoginCountToday();
                weekForumActiveUsersValue = weekForumActiveUsersValue + obj.getForumActiveUserToday();
                weekNewForumPostsValue = weekNewForumPostsValue + obj.getForumPostToday();

                weekUserConnectionValue = weekUserConnectionValue + obj.getUserConnectionCountToday();
                weekSocialPostsValue = weekSocialPostsValue + obj.getSocialPostCountToday();
                weekEmailNotificationValue = weekEmailNotificationValue + obj.getEmailNotificationCountToday();
            }

            String weekTitle = "W" + key.substring(5, key.length());
            listTitle.add(weekTitle);
            newUsersData.add(weekNewUsersValue);
            loginCountData.add(weekLoginCountValue);
            forumActiveUsersData.add(
                    weekForumActiveUsersValue > 0 ? (Long) (weekForumActiveUsersValue / listValueOfNode.size())
                            : 0L);
            newForumPostsData.add(weekNewForumPostsValue);

            userConnectionData.add(weekUserConnectionValue);
            socialPostData.add(weekSocialPostsValue);
            emailNotificationData.add(weekEmailNotificationValue);
        }
        chartData.setListTitle(listTitle);
        chartData.setNewUsersData(newUsersData);
        chartData.setLoginCountData(loginCountData);
        chartData.setForumActiveUsersData(forumActiveUsersData);
        chartData.setNewForumPostsData(newForumPostsData);

        chartData.setUserConnectionData(userConnectionData);
        chartData.setSocialPostData(socialPostData);
        chartData.setEmailNotificationData(emailNotificationData);

        return chartData;
    }

    if (filter.equalsIgnoreCase(FILTER_BY_MONTH)) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.setTime(fromDate);
        calendar.add(Calendar.MONTH, totalDataCoulumn - 1);
        Date nextFewMonth = calendar.getTime();

        List<ActivityStatisticBean> list = service.getListActivityStatisticByDate(fromDate, nextFewMonth);

        List<String> listTitle = new ArrayList<String>();
        List<Long> newUsersData = new ArrayList<Long>();
        List<Long> loginCountData = new ArrayList<Long>();
        List<Long> forumActiveUsersData = new ArrayList<Long>();
        List<Long> newForumPostsData = new ArrayList<Long>();

        List<Long> userConnectionData = new ArrayList<Long>();
        List<Long> socialPostData = new ArrayList<Long>();
        List<Long> emailNotificationData = new ArrayList<Long>();

        ChartData chartData = new ChartData();

        TreeMap<String, List<ActivityStatisticBean>> monthData = new TreeMap<String, List<ActivityStatisticBean>>();

        //init empty-data
        for (int i = 0; i < totalDataCoulumn; i++) {
            calendar.clear();
            calendar.setTime(fromDate);
            calendar.add(Calendar.MONTH, i);
            String month = calendar.get(Calendar.YEAR) + "-" + partString(calendar.getTime(), "MM") + "-"
                    + partString(calendar.getTime(), "MMM") + "-" + calendar.get(Calendar.YEAR); //get name of Month
            monthData.put(month, new ArrayList<ActivityStatisticBean>());
        }

        for (ActivityStatisticBean bean : list) {
            calendar.clear();
            calendar.setTime(bean.getCreatedDate());
            String month = calendar.get(Calendar.YEAR) + "-" + partString(calendar.getTime(), "MM") + "-"
                    + partString(calendar.getTime(), "MMM") + "-" + calendar.get(Calendar.YEAR); //get name of Month

            if (monthData.containsKey(month)) {
                List<ActivityStatisticBean> listValueOfNode = monthData.get(month);
                listValueOfNode.add(bean);
            } else {
                List<ActivityStatisticBean> listValueOfNode = new ArrayList<ActivityStatisticBean>();
                listValueOfNode.add(bean);
                monthData.put(month, listValueOfNode);
            }
        }

        for (String key : monthData.keySet()) {
            List<ActivityStatisticBean> listValueOfNode = monthData.get(key);
            Long monthNewUsersValue = 0L;
            Long monthLoginCountValue = 0L;
            Long monthForumActiveUsersValue = 0L;
            Long monthNewForumPostsValue = 0L;

            Long monthUserConnectionValue = 0L;
            Long monthSocialPostsValue = 0L;
            Long monthEmailNotificationValue = 0L;

            for (ActivityStatisticBean obj : listValueOfNode) {
                monthNewUsersValue = monthNewUsersValue + obj.getNewUserToday();
                monthLoginCountValue = monthLoginCountValue + obj.getLoginCountToday();
                monthForumActiveUsersValue = monthForumActiveUsersValue + obj.getForumActiveUserToday();
                monthNewForumPostsValue = monthNewForumPostsValue + obj.getForumPostToday();

                monthUserConnectionValue = monthUserConnectionValue + obj.getUserConnectionCountToday();
                monthSocialPostsValue = monthSocialPostsValue + obj.getSocialPostCountToday();
                monthEmailNotificationValue = +monthEmailNotificationValue
                        + obj.getEmailNotificationCountToday();
            }

            listTitle.add(key.substring(8, key.length()));
            newUsersData.add(monthNewUsersValue);
            loginCountData.add(monthLoginCountValue);
            forumActiveUsersData.add(monthForumActiveUsersValue > 0
                    ? (Long) (monthForumActiveUsersValue / listValueOfNode.size())
                    : 0L);
            newForumPostsData.add(monthNewForumPostsValue);

            userConnectionData.add(monthUserConnectionValue);
            socialPostData.add(monthSocialPostsValue);
            emailNotificationData.add(monthEmailNotificationValue);
        }
        chartData.setListTitle(listTitle);
        chartData.setNewUsersData(newUsersData);
        chartData.setLoginCountData(loginCountData);
        chartData.setForumActiveUsersData(forumActiveUsersData);
        chartData.setNewForumPostsData(newForumPostsData);

        chartData.setUserConnectionData(userConnectionData);
        chartData.setSocialPostData(socialPostData);
        chartData.setEmailNotificationData(emailNotificationData);

        return chartData;
    }
    return null;
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

private Map<String, Object> createTimeseries(String userPrincipalName, DataSeriesSource dss,
        List<Filter> filters, GroupingImpl group, String timeResolution, Integer prepull,
        String graphTimeSeriesUrl, final Collection<Record> records, final List<Dimension> accumulations,
        final List<Dimension> timeseriesDenominators, String detectorClass, boolean includeDetails,
        boolean displayIntervalEndDate, GraphDataInterface graphData, TimeZone clientTimezone) {

    Map<String, Object> result = new HashMap<String, Object>();
    Map<String, ResolutionHandler> resolutionHandlers = null;
    result.put("success", false);
    try {/*  w w  w  .  j ava  2 s. com*/
        GroupingDimension grpdim = dss.getGroupingDimension(group.getId());
        resolutionHandlers = grpdim.getResolutionsMap();
        String dateFieldName = group.getId();
        Date startDate = null;
        Date endDate = null;
        if (grpdim != null
                && (grpdim.getSqlType() == FieldType.DATE || grpdim.getSqlType() == FieldType.DATE_TIME)) {
            for (Filter f : filters) {
                if (f instanceof OneArgOpFilter) {
                    OneArgOpFilter of = (OneArgOpFilter) f;
                    if (of.getFilterId().equalsIgnoreCase(grpdim.getId())
                            && (of.getSqlSnippet("").contains(">="))) {
                        startDate = (Date) of.getArguments().get(0);
                    } else if (of.getFilterId().equalsIgnoreCase(grpdim.getId())
                            && (of.getSqlSnippet("").contains("<="))) {
                        endDate = (Date) of.getArguments().get(0);
                    }
                }
            }
        }
        //union accumulations to get all results
        List<Dimension> dimensions = new ArrayList<Dimension>(
                ControllerUtils.unionDimensions(accumulations, timeseriesDenominators));

        int timeOffsetMillies = 0;
        String timezoneEnabledString = messageSource.getMessage(TIMEZONE_ENABLED, "false");
        if (timezoneEnabledString.equalsIgnoreCase("true")) {
            timeOffsetMillies = (clientTimezone.getRawOffset() - clientTimezone.getDSTSavings())
                    - (TimeZone.getDefault().getRawOffset() - TimeZone.getDefault().getDSTSavings());
        }
        Calendar startDayCal = Calendar.getInstance(clientTimezone);
        startDayCal.setTime(startDate);
        startDayCal.add(Calendar.MILLISECOND, timeOffsetMillies);

        //get data grouped by group dimension
        List<AccumPoint> points = extractAccumulationPoints(userPrincipalName, dss, records,
                startDayCal.getTime(), endDate, dimensions, group, resolutionHandlers);
        if (points.size() > 0) {
            DateFormat dateFormat = getDateFormat(timeResolution); //dateFormat.setTimeZone(timezone);
            DateFormat tmpDateFormat = (DateFormat) dateFormat.clone();
            tmpDateFormat.setTimeZone(clientTimezone);

            // number format for level
            NumberFormat numFormat3 = NumberFormat.getNumberInstance();
            numFormat3.setMinimumFractionDigits(0);
            numFormat3.setMaximumFractionDigits(3);

            // number format for expected count
            NumberFormat numFormat1 = NumberFormat.getNumberInstance();
            numFormat1.setMinimumFractionDigits(0);
            numFormat1.setMaximumFractionDigits(1);

            Calendar cal = new GregorianCalendar();
            cal.setTime(startDayCal.getTime());
            //offset start date to match prepull offset
            if (timeResolution.equals("weekly")) {
                cal.add(Calendar.DATE, (7 * prepull));
            } else if (timeResolution.equals("daily")) {
                cal.add(Calendar.DATE, prepull);
            }
            Date queryStartDate = cal.getTime();

            //-- Handles Denominator Types -- //
            double[] divisors = new double[points.size()];
            double multiplier = 1.0;
            boolean percentBased = false;
            String yAxisLabel = messageSource.getDataSourceMessage("graph.count", dss);

            boolean isDetectionDetector = !NoDetectorDetector.class.getName().equalsIgnoreCase(detectorClass);

            //if there is a denominator we need to further manipulate the data
            if (timeseriesDenominators != null && !timeseriesDenominators.isEmpty()) {
                // divisor is the sum of timeseriesDenominators
                divisors = totalSeriesValues(points, timeseriesDenominators);
                multiplier = 100.0;
                percentBased = true;
                yAxisLabel = messageSource.getDataSourceMessage("graph.percent", dss);
            } else {
                //the query is for total counts
                Arrays.fill(divisors, 1.0);
            }

            double[][] allCounts = new double[accumulations.size()][];
            int[][] allColors = new int[accumulations.size()][];
            String[][] allAltTexts = new String[accumulations.size()][];
            String[] dates = new String[] { "" };
            double[][] allExpecteds = new double[accumulations.size()][];
            double[][] allLevels = new double[accumulations.size()][];
            String[][] allLineSetURLs = new String[accumulations.size()][];
            String[][] allSwitchInfo = new String[accumulations.size()][];
            String[] lineSetLabels = new String[accumulations.size()];
            boolean[] displayAlerts = new boolean[accumulations.size()];

            //get all results
            Collection<Dimension> dims = new ArrayList<Dimension>(dss.getResultDimensions());
            Collection<String> dimIds = ControllerUtils.getDimensionIdsFromCollection(dims);
            Collection<String> accIds = ControllerUtils.getDimensionIdsFromCollection(dss.getAccumulations());
            //remove extra accumulations in the result set using string ids
            dimIds.removeAll(accIds);

            //for each accumulation we run detection and gather results
            int aIndex = 0;
            for (Dimension accumulation : accumulations) {
                String accumId = accumulation.getId();

                // use display name if it has one, otherwise translate its ID
                String accumIdTranslated = accumulation.getDisplayName();
                if (accumIdTranslated == null) {
                    accumIdTranslated = messageSource.getDataSourceMessage(accumulation.getId(), dss);
                }

                TemporalDetectorInterface TDI = (TemporalDetectorInterface) DetectorHelper
                        .createObject(detectorClass);
                TemporalDetectorSimpleDataObject TDDO = new TemporalDetectorSimpleDataObject();

                int[] colors;
                double[] counts;
                String[] altTexts;
                double[] expecteds;
                double[] levels;
                String[] switchInfo;
                String[] urls;

                //pull the counts from the accum array points
                double[] seriesDoubleArray = generateSeriesValues(points, accumId);

                //run divisor before detection
                for (int i = 0; i < seriesDoubleArray.length; i++) {
                    double div = divisors[i];
                    if (div == 0) {
                        seriesDoubleArray[i] = 0.0;
                    } else {
                        seriesDoubleArray[i] = (seriesDoubleArray[i] / div) * multiplier;
                    }
                }

                //run detection
                TDDO.setCounts(seriesDoubleArray);
                TDDO.setStartDate(startDate);
                TDDO.setTimeResolution(timeResolution);

                try {
                    TDI.runDetector(TDDO);
                } catch (Exception e) {
                    String errorMessage = "Failure to create Timeseries";
                    if (e.getMessage() != null) {
                        errorMessage = errorMessage + ":<BR>" + e.getMessage();
                    }
                    result.put("message", errorMessage);
                    result.put("success", false);
                    return result;
                }

                TDDO.cropStartup(prepull);
                counts = TDDO.getCounts();
                int tddoLength = counts.length;

                if (!DAILY.equalsIgnoreCase(timeResolution)) {
                    //toggle between start date and end date
                    //TDDO.setDates(getOurDates(startDate, endDate, tddoLength, timeResolution));
                    TDDO.setDates(getOurDates(queryStartDate, endDate, tddoLength, timeResolution,
                            displayIntervalEndDate));
                }
                double[] tcolors = TDDO.getColors();

                Date[] tdates = TDDO.getDates();
                altTexts = TDDO.getAltTexts();
                expecteds = TDDO.getExpecteds();
                levels = TDDO.getLevels();
                switchInfo = TDDO.getSwitchInfo();
                colors = new int[tddoLength];
                dates = new String[tddoLength];
                urls = new String[tddoLength];

                //add the accumId for the current series
                dimIds.add(accumId);

                StringBuilder jsCall = new StringBuilder();
                jsCall.append("javascript:OE.report.datasource.showDetails({");
                jsCall.append("dsId:'").append(dss.getClass().getName()).append("'");
                //specify results
                jsCall.append(",results:[")
                        .append(StringUtils.collectionToDelimitedString(dimIds, ",", "'", "'")).append(']');
                //specify accumId
                jsCall.append(",accumId:'").append(accumId).append("'");

                addJavaScriptFilters(jsCall, filters, dateFieldName);

                //this builds urls and hover texts
                int startDay = getWeekStartDay(resolutionHandlers);

                Calendar c = Calendar.getInstance(clientTimezone);

                //               Calendar curr = Calendar.getInstance();
                for (int i = 0; i < tddoLength; i++) {
                    colors[i] = (int) tcolors[i];

                    // For a time series data point, set time to be current server time
                    // This will allow us to convert this data point date object to be request timezone date
                    c.setTime(tdates[i]);
                    c.add(Calendar.MILLISECOND, timeOffsetMillies);

                    if (timeResolution.equals(WEEKLY)) {
                        dates[i] = dateFormatWeekPart.format(tdates[i]) + "-W"
                                + PgSqlDateHelper.getWeekOfYear(startDay, c) + "-"
                                + PgSqlDateHelper.getYear(startDay, c);
                    } else {
                        dates[i] = tmpDateFormat.format(c.getTime());
                    }

                    altTexts[i] = "(" + accumIdTranslated + ") " + // Accum
                            "Date: " + dates[i] + // Date
                            ", Level: " + numFormat3.format(levels[i]) + // Level
                            ", Count: " + ((int) counts[i]) + // Count
                            ", Expected: " + numFormat1.format(expecteds[i]); // Expected

                    if (switchInfo != null) {
                        altTexts[i] += ", Switch: " + switchInfo[i] + ", ";
                    }

                    // build the click through url
                    StringBuilder tmp = new StringBuilder(jsCall.toString());

                    // add the date field with start and end dates from the data point
                    if (!DAILY.equalsIgnoreCase(timeResolution)) {
                        Calendar timeSet = Calendar.getInstance(clientTimezone);
                        timeSet.setTime(tdates[i]);

                        if (WEEKLY.equalsIgnoreCase(timeResolution)) {
                            timeSet.set(Calendar.DAY_OF_WEEK, startDay + 1);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            timeSet.add(Calendar.DAY_OF_YEAR, 6);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        } else if (MONTHLY.equalsIgnoreCase(timeResolution)) {
                            // Compute last day of month
                            timeSet.set(Calendar.DAY_OF_MONTH, 1);
                            timeSet.add(Calendar.MONTH, 1);
                            timeSet.add(Calendar.DAY_OF_YEAR, -1);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            // set first day of month
                            timeSet.set(Calendar.DAY_OF_MONTH, 1);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        } else if (YEARLY.equalsIgnoreCase(timeResolution)) {
                            // Compute last day of month
                            timeSet.set(Calendar.DATE, 31);
                            timeSet.add(Calendar.MONTH, Calendar.DECEMBER);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            timeSet.set(Calendar.DATE, 1);
                            timeSet.add(Calendar.MONTH, Calendar.JANUARY);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        }
                    } else {
                        // compute end date for individual data points based on the selected resolution
                        //                     detailsPointEndDate = computeEndDate(tdates[i],timeResolution);
                        // add the date field with start and end dates from the data point
                        tmp.append(",").append(dateFieldName).append("_start:'").append(tdates[i].getTime())
                                .append("'");
                        tmp.append(",").append(dateFieldName).append("_end:'").append(tdates[i].getTime())
                                .append("'");
                    }
                    tmp.append("});");
                    urls[i] = tmp.toString();
                }

                allCounts[aIndex] = counts;
                allColors[aIndex] = colors;
                allAltTexts[aIndex] = altTexts;
                allExpecteds[aIndex] = expecteds;
                allLevels[aIndex] = levels;
                allLineSetURLs[aIndex] = urls;
                allSwitchInfo[aIndex] = switchInfo;
                lineSetLabels[aIndex] = accumIdTranslated;
                displayAlerts[aIndex] = isDetectionDetector;
                aIndex++;

                //remove the accumId for the next series
                dimIds.remove(accumId);
            }

            GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir);
            GraphController gc = getGraphController(null, hndl, userPrincipalName);
            //TODO figure out why I (hodancj1) added this to be accumulation size ~Feb 2012
            // gc.setMaxLegendItems(accumulations.size());

            graphData.setShowSingleAlertLegends(isDetectionDetector);
            graphData.setCounts(allCounts);
            graphData.setColors(allColors);
            graphData.setAltTexts(allAltTexts);
            graphData.setXLabels(dates);
            graphData.setExpecteds(allExpecteds);
            graphData.setLevels(allLevels);
            graphData.setLineSetURLs(allLineSetURLs);
            graphData.setLineSetLabels(lineSetLabels);
            graphData.setDisplayAlerts(displayAlerts);
            // graphData.setDisplaySeverityAlerts(displayAlerts);
            graphData.setPercentBased(percentBased);

            graphData.setXAxisLabel(messageSource.getDataSourceMessage(group.getResolution(), dss));
            graphData.setYAxisLabel(yAxisLabel);

            int maxLabels = graphData.getGraphWidth() / 30;
            graphData.setMaxLabeledCategoryTicks(Math.min(maxLabels, allCounts[0].length));

            StringBuffer sb = new StringBuffer();
            GraphObject graph = gc.writeTimeSeriesGraph(sb, graphData, true, true, false, graphTimeSeriesUrl);

            result.put("html", sb.toString());

            //added to build method calls from javascript
            Map<String, Object> graphConfig = new HashMap<String, Object>();
            graphConfig.put("address", graphTimeSeriesUrl);
            graphConfig.put("graphDataId", graph.getGraphDataId());
            graphConfig.put("imageMapName", graph.getImageMapName());

            graphConfig.put("graphTitle", graphData.getGraphTitle());
            graphConfig.put("xAxisLabel", graphData.getXAxisLabel());
            graphConfig.put("yAxisLabel", graphData.getYAxisLabel());
            graphConfig.put("xLabels", graphData.getXLabels());
            graphConfig.put("graphWidth", graphData.getGraphWidth());
            graphConfig.put("graphHeight", graphData.getGraphHeight());

            graphConfig.put("yAxisMin", graph.getYAxisMin());
            graphConfig.put("yAxisMax", graph.getYAxisMax());

            // fix invalid JSON coming from GraphController
            String dataSeriesJson = graph.getDataSeriesJSON().replaceFirst("\\{", "")
                    // remove trailing "}"
                    .substring(0, graph.getDataSeriesJSON().length() - 2);

            // read malformed JSON
            ObjectMapper mapper = new ObjectMapper();
            JsonFactory jsonFactory = mapper.getJsonFactory()
                    .configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
                    .configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            JsonParser jsonParser = jsonFactory.createJsonParser(dataSeriesJson);

            // array of String -> Object maps
            TypeReference<Map<String, Object>[]> dataSeriesType = new TypeReference<Map<String, Object>[]>() {
            };

            // write JSON as Map so that it can be serialized properly back to JSON
            Map<String, Object>[] seriesMap = mapper.readValue(jsonParser, dataSeriesType);
            graphConfig.put("dataSeriesJSON", seriesMap);

            if (includeDetails) {
                int totalPoints = 0;
                List<HashMap<String, Object>> details = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> detail;
                for (int i = 0; i < allCounts.length; i++) {
                    for (int j = 0; j < allCounts[i].length; j++) {
                        totalPoints++;
                        detail = new HashMap<String, Object>();
                        detail.put("Date", dates[j]);
                        detail.put("Series", lineSetLabels[i]);
                        detail.put("Level", allLevels[i][j]);
                        detail.put("Count", allCounts[i][j]);
                        if (!ArrayUtils.isEmpty(allExpecteds[i])) {
                            detail.put("Expected", allExpecteds[i][j]);
                        }
                        if (!ArrayUtils.isEmpty(allSwitchInfo[i])) {
                            detail.put("Switch", allSwitchInfo[i][j]);
                        }
                        detail.put("Color", allColors[i][j]);
                        details.add(detail);
                    }
                }
                result.put("detailsTotalRows", totalPoints);
                result.put("details", details);
            }
            result.put("graphConfiguration", graphConfig);
            result.put("success", true);
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append("<h2>" + messageSource.getDataSourceMessage("graph.nodataline1", dss) + "</h2>");
            sb.append("<p>" + messageSource.getDataSourceMessage("graph.nodataline2", dss) + "</p>");
            result.put("html", sb.toString());
            result.put("success", true);
        }
    } catch (Exception e) {
        log.error("Failure to create Timeseries", e);
    }
    return result;
}

From source file:com.mb.framework.util.DateTimeUtil.java

/**
 * This method is used for converting to date to last day of year from given
 * year./* w  w w .  ja v  a 2  s  . c  o m*/
 * 
 * @param year
 * @param date
 * @return
 * @throws ParseException
 */
public static long convertLastDayInMilli(int year) throws ParseException {
    long d = 0;
    Calendar c = Calendar.getInstance();
    c.set(year, Calendar.DECEMBER, 31, 11, 59, 59);
    d = c.getTimeInMillis();

    return d;
}

From source file:org.exist.xquery.modules.mail.SendEmailFunction.java

/**
 * Returns the current date and time in an RFC822 format, suitable for an email Date Header
 *
 * @return      RFC822 formated date and time as a String
 *///from  ww w .  jav a 2 s . co m
private String getDateRFC822() {

    String dateString = new String();
    final Calendar rightNow = Calendar.getInstance();

    //Day of the week
    switch (rightNow.get(Calendar.DAY_OF_WEEK)) {
    case Calendar.MONDAY:
        dateString = "Mon";
        break;

    case Calendar.TUESDAY:
        dateString = "Tue";
        break;

    case Calendar.WEDNESDAY:
        dateString = "Wed";
        break;

    case Calendar.THURSDAY:
        dateString = "Thu";
        break;

    case Calendar.FRIDAY:
        dateString = "Fri";
        break;

    case Calendar.SATURDAY:
        dateString = "Sat";
        break;

    case Calendar.SUNDAY:
        dateString = "Sun";
        break;
    }

    dateString += ", ";

    //Date
    dateString += rightNow.get(Calendar.DAY_OF_MONTH);
    dateString += " ";

    //Month
    switch (rightNow.get(Calendar.MONTH)) {
    case Calendar.JANUARY:
        dateString += "Jan";
        break;

    case Calendar.FEBRUARY:
        dateString += "Feb";
        break;

    case Calendar.MARCH:
        dateString += "Mar";
        break;

    case Calendar.APRIL:
        dateString += "Apr";
        break;

    case Calendar.MAY:
        dateString += "May";
        break;

    case Calendar.JUNE:
        dateString += "Jun";
        break;

    case Calendar.JULY:
        dateString += "Jul";
        break;

    case Calendar.AUGUST:
        dateString += "Aug";
        break;

    case Calendar.SEPTEMBER:
        dateString += "Sep";
        break;

    case Calendar.OCTOBER:
        dateString += "Oct";
        break;

    case Calendar.NOVEMBER:
        dateString += "Nov";
        break;

    case Calendar.DECEMBER:
        dateString += "Dec";
        break;
    }
    dateString += " ";

    //Year
    dateString += rightNow.get(Calendar.YEAR);
    dateString += " ";

    //Time
    String tHour = Integer.toString(rightNow.get(Calendar.HOUR_OF_DAY));
    if (tHour.length() == 1) {
        tHour = "0" + tHour;
    }

    String tMinute = Integer.toString(rightNow.get(Calendar.MINUTE));
    if (tMinute.length() == 1) {
        tMinute = "0" + tMinute;
    }

    String tSecond = Integer.toString(rightNow.get(Calendar.SECOND));
    if (tSecond.length() == 1) {
        tSecond = "0" + tSecond;
    }

    dateString += tHour + ":" + tMinute + ":" + tSecond + " ";

    //TimeZone Correction
    String tzSign = new String();
    String tzHours = new String();
    String tzMinutes = new String();

    final TimeZone thisTZ = rightNow.getTimeZone();
    int tzOffset = thisTZ.getOffset(rightNow.getTime().getTime()); //get timezone offset in milliseconds
    tzOffset = (tzOffset / 1000); //convert to seconds
    tzOffset = (tzOffset / 60); //convert to minutes

    //Sign
    if (tzOffset > 1) {
        tzSign = "+";
    } else {
        tzSign = "-";
        tzOffset *= -1;
    }

    //Calc Hours and Minutes?
    if (tzOffset >= 60) {
        //Minutes and Hours
        tzHours += (tzOffset / 60); //hours

        // do we need to prepend a 0
        if (tzHours.length() == 1) {
            tzHours = "0" + tzHours;
        }

        tzMinutes += (tzOffset % 60); //minutes

        // do we need to prepend a 0
        if (tzMinutes.length() == 1) {
            tzMinutes = "0" + tzMinutes;
        }
    } else {
        //Just Minutes
        tzHours = "00";
        tzMinutes += tzOffset;
        // do we need to prepend a 0
        if (tzMinutes.length() == 1) {
            tzMinutes = "0" + tzMinutes;
        }
    }

    dateString += tzSign + tzHours + tzMinutes;

    return dateString;
}

From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java

private Map<Integer, String> getMonthNamesMap() {
    monthNamesMap = new HashMap<Integer, String>();
    monthNamesMap.put(Calendar.JANUARY, msgs.getString("mo_jan"));
    monthNamesMap.put(Calendar.FEBRUARY, msgs.getString("mo_feb"));
    monthNamesMap.put(Calendar.MARCH, msgs.getString("mo_mar"));
    monthNamesMap.put(Calendar.APRIL, msgs.getString("mo_apr"));
    monthNamesMap.put(Calendar.MAY, msgs.getString("mo_may"));
    monthNamesMap.put(Calendar.JUNE, msgs.getString("mo_jun"));
    monthNamesMap.put(Calendar.JULY, msgs.getString("mo_jul"));
    monthNamesMap.put(Calendar.AUGUST, msgs.getString("mo_ago"));
    monthNamesMap.put(Calendar.SEPTEMBER, msgs.getString("mo_sep"));
    monthNamesMap.put(Calendar.OCTOBER, msgs.getString("mo_oct"));
    monthNamesMap.put(Calendar.NOVEMBER, msgs.getString("mo_nov"));
    monthNamesMap.put(Calendar.DECEMBER, msgs.getString("mo_dec"));
    return monthNamesMap;
}

From source file:org.apache.myfaces.custom.calendar.HtmlCalendarRenderer.java

public static String[] mapMonths(DateFormatSymbols symbols) {
    String[] months = new String[12];

    String[] localeMonths = symbols.getMonths();

    months[0] = localeMonths[Calendar.JANUARY];
    months[1] = localeMonths[Calendar.FEBRUARY];
    months[2] = localeMonths[Calendar.MARCH];
    months[3] = localeMonths[Calendar.APRIL];
    months[4] = localeMonths[Calendar.MAY];
    months[5] = localeMonths[Calendar.JUNE];
    months[6] = localeMonths[Calendar.JULY];
    months[7] = localeMonths[Calendar.AUGUST];
    months[8] = localeMonths[Calendar.SEPTEMBER];
    months[9] = localeMonths[Calendar.OCTOBER];
    months[10] = localeMonths[Calendar.NOVEMBER];
    months[11] = localeMonths[Calendar.DECEMBER];

    return months;
}