Example usage for java.util Calendar JANUARY

List of usage examples for java.util Calendar JANUARY

Introduction

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

Prototype

int JANUARY

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

Click Source Link

Document

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

Usage

From source file:com.rogchen.common.xml.UtilDateTime.java

public static Timestamp getYearStart(Timestamp stamp, int daysLater, int monthsLater, int yearsLater,
        TimeZone timeZone, Locale locale) {
    Calendar tempCal = toCalendar(stamp, timeZone, locale);
    tempCal.set(tempCal.get(Calendar.YEAR), Calendar.JANUARY, 1, 0, 0, 0);
    tempCal.add(Calendar.YEAR, yearsLater);
    tempCal.add(Calendar.MONTH, monthsLater);
    tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
    Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
    retStamp.setNanos(0);//from  w  w  w.  j  a  va 2  s.  c o  m
    return retStamp;
}

From source file:com.nextgis.ngm_clink_monitoring.activities.MainActivity.java

void testUpdate() {
    //test sync//  w w  w . j av  a2 s  . c om
    IGISApplication application = (IGISApplication) getApplication();
    MapBase map = application.getMap();
    NGWVectorLayer ngwVectorLayer = null;
    for (int i = 0; i < map.getLayerCount(); i++) {
        ILayer layer = map.getLayer(i);
        if (layer instanceof NGWVectorLayer) {
            ngwVectorLayer = (NGWVectorLayer) layer;
        }
    }
    if (null != ngwVectorLayer) {
        Uri uri = Uri.parse(
                "content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + ngwVectorLayer.getPath().getName());
        Uri updateUri = ContentUris.withAppendedId(uri, 29);
        ContentValues values = new ContentValues();
        values.put("width", 4);
        values.put("azimuth", 8.0);
        values.put("status", "test4");
        values.put("temperatur", -10);
        values.put("name", "xxx");

        Calendar calendar = new GregorianCalendar(2014, Calendar.JANUARY, 23);
        values.put("datetime", calendar.getTimeInMillis());
        try {
            GeoPoint pt = new GeoPoint(67, 65);
            pt.setCRS(CRS_WGS84);
            pt.project(CRS_WEB_MERCATOR);
            GeoMultiPoint mpt = new GeoMultiPoint();
            mpt.add(pt);
            values.put(FIELD_GEOM, mpt.toBlob());
        } catch (IOException e) {
            e.printStackTrace();
        }
        int result = getContentResolver().update(updateUri, values, null, null);
        if (result == 0) {
            Log.d(TAG, "update failed");
        } else {
            Log.d(TAG, "" + result);
        }
    }
}

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.  j  a  v a2s.  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.rogchen.common.xml.UtilDateTime.java

/**
 * Returns a List of month name Strings - suitable for calendar headings.
 *
 * @param locale/*w  w  w . ja va2 s  .  com*/
 * @return List of month name Strings
 */
public static List<String> getMonthNames(Locale locale) {
    Calendar tempCal = Calendar.getInstance(locale);
    tempCal.set(Calendar.MONTH, Calendar.JANUARY);
    SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM", locale);
    List<String> resultList = new ArrayList<String>();
    for (int i = Calendar.JANUARY; i <= tempCal.getActualMaximum(Calendar.MONTH); i++) {
        resultList.add(dateFormat.format(tempCal.getTime()));
        tempCal.roll(Calendar.MONTH, 1);
    }
    return resultList;
}

From source file:cx.fbn.nevernote.sql.REnSearch.java

public int dateCheck(String date, long noteDate) throws java.lang.NumberFormatException {
    int offset = 0;
    boolean found = false;
    GregorianCalendar calendar = new GregorianCalendar();

    if (date.contains("-")) {
        String modifier = date.substring(date.indexOf("-") + 1);
        offset = new Integer(modifier);
        offset = 0 - offset;/* w  w w.jav a 2  s . c o  m*/
        date = date.substring(0, date.indexOf("-"));
    }

    if (date.contains("+")) {
        String modifier = date.substring(date.indexOf("+") + 1);
        offset = new Integer(modifier);
        date = date.substring(0, date.indexOf("+"));
    }

    if (date.equalsIgnoreCase("today")) {
        calendar.add(Calendar.DATE, offset);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 1);
        found = true;
    }

    if (date.equalsIgnoreCase("month")) {
        calendar.add(Calendar.MONTH, offset);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 1);
        found = true;
    }

    if (date.equalsIgnoreCase("year")) {
        calendar.add(Calendar.YEAR, offset);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 1);
        found = true;
    }

    if (date.equalsIgnoreCase("week")) {
        calendar.add(Calendar.DATE, 0 - calendar.get(Calendar.DAY_OF_WEEK) + 1);
        calendar.add(Calendar.DATE, (offset * 7));
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 1);

        found = true;
    }

    // If nothing was found, then we have a date number
    if (!found) {
        calendar = stringToGregorianCalendar(date);
    }

    String dateTimeFormat = new String("yyyyMMdd-HHmmss");
    SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
    StringBuilder creationDate = new StringBuilder(simple.format(noteDate));
    GregorianCalendar nCalendar = stringToGregorianCalendar(creationDate.toString().replace("-", "T"));
    if (calendar == null || nCalendar == null) // If we have something invalid, it automatically fails
        return 1;
    return calendar.compareTo(nCalendar);
}

From source file:org.apache.zeppelin.zeppelin_spark_monitoring.SparkMonitoringInterpreter.java

private InterpreterResult getJobStatistic(String[] urlItems, List<SparkMonitoringJob> lsJob) {
    StringBuffer result = new StringBuffer();
    String command = urlItems[1];
    //get statistic time range, if existed
    String time1 = null;/* w w  w  . j  a  va2s. c  o  m*/
    String time2 = null;
    if (urlItems.length >= 3) {
        time1 = urlItems[2];
    }
    if (urlItems.length >= 4) {
        time2 = urlItems[3];
    }
    Long statStartTime = 0L;
    Long statEndTime = 0L;
    Calendar cal = Calendar.getInstance();
    if ("hour".equalsIgnoreCase(command)) {
        //default is 00:00:00
        int startHour = 0;
        if (time1 != null) {
            try {
                startHour = Integer.parseInt(time1);
            } catch (NumberFormatException e) {
                startHour = 0;
            }
        }
        statStartTime = getTimeFromPattern(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                cal.get(Calendar.DATE), startHour, 0, 0);

        //default is current hour
        int endHour = cal.get(Calendar.HOUR_OF_DAY);
        if (time2 != null) {
            try {
                endHour = Integer.parseInt(time2);
            } catch (NumberFormatException e) {
                //keep endHour
            }
        }
        statEndTime = getTimeFromPattern(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                cal.get(Calendar.DATE), endHour, 0, 0);
        if (time2 == null) {
            //time1 is the period of start time before end time
            statStartTime = statEndTime - startHour * 3600 * 1000;
        }
    } else if ("day".equalsIgnoreCase(command)) {
        //default is first day of month
        int startDay = 1;
        if (time1 != null) {
            try {
                startDay = Integer.parseInt(time1);
            } catch (NumberFormatException e) {
                startDay = 1;
            }
        }
        statStartTime = getTimeFromPattern(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), startDay, 0, 0, 0);

        //default is current date
        int endDay = cal.get(Calendar.DATE);
        if (time2 != null) {
            try {
                endDay = Integer.parseInt(time2);
            } catch (NumberFormatException e) {
                //keep endDay
            }
        }
        statEndTime = getTimeFromPattern(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), endDay, 23, 59, 59);
        if (time2 == null) {
            //time1 is the period of start time before end time
            statStartTime = statEndTime - startDay * 24 * 3600 * 1000;
        }
    } else if ("month".equalsIgnoreCase(command)) {
        //default is first month of year
        int startMonth = Calendar.JANUARY;
        if (time1 != null) {
            try {
                startMonth = Integer.parseInt(time1);
            } catch (NumberFormatException e) {
                startMonth = Calendar.JANUARY;
            }
        }
        statStartTime = getTimeFromPattern(cal.get(Calendar.YEAR), startMonth, 1, 0, 0, 0);

        //default is current month
        int endMonth = cal.get(Calendar.MONTH);
        if (time2 != null) {
            try {
                endMonth = Integer.parseInt(time2);
            } catch (NumberFormatException e) {
                //keep endMonth
            }
        }
        //to get the last day of current month
        //let the first time of next month
        statEndTime = getTimeFromPattern(cal.get(Calendar.YEAR), endMonth + 1, 1, 0, 0, 0);
        //minus to 1 second
        statEndTime = statEndTime - 1 * 1000;

        if (time2 == null) {
            //time1 is the period of start time before end time
            statStartTime = statEndTime - startMonth * 30 * 24 * 3600 * 1000;
        }
    } else if ("year".equalsIgnoreCase(command)) {
        //default is first year
        int startYear = 1;
        if (time1 != null) {
            try {
                startYear = Integer.parseInt(time1);
            } catch (NumberFormatException e) {
                startYear = 1;
            }
        }
        statStartTime = getTimeFromPattern(startYear, 1, 1, 0, 0, 0);

        //default is current year
        int endYear = cal.get(Calendar.YEAR);
        if (time2 != null) {
            try {
                endYear = Integer.parseInt(time2);
            } catch (NumberFormatException e) {
                //keep endYear
            }
        }
        statEndTime = getTimeFromPattern(endYear, 12, 31, 23, 59, 59);

        if (time2 == null) {
            //time1 is the period of start time before end time
            statStartTime = statEndTime - startYear * 365 * 24 * 3600 * 1000;
        }
    }
    // get statistic of number jobs by range of time
    // total_jobs, total_running, total_completed, total_failed
    int totalJob = 0;
    int totalRunning = 0;
    int totalCompleted = 0;
    int totalFailed = 0;
    for (SparkMonitoringJob job : lsJob) {
        Long startTime = job.getSubmisstionTimeMilis();
        if (startTime >= statStartTime && startTime <= statEndTime) {
            totalJob++;
            String jobStatus = job.getStatus();
            if ("RUNNING".equals(jobStatus)) {
                totalRunning++;
            } else if ("SUCCEEDED".equals(jobStatus)) {
                totalCompleted++;
            } else if ("FAILED".equals(jobStatus)) {
                totalFailed++;
            }
        }
    }
    //add to result
    result.append("Total jobs\tRunning\tSucceeded\tFailed");
    result.append("\n");
    result.append(totalJob).append("\t").append(totalRunning);
    result.append("\t").append(totalCompleted).append("\t").append(totalFailed);

    return new InterpreterResult(InterpreterResult.Code.SUCCESS, InterpreterResult.Type.TABLE,
            result.toString());
}

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

@Override
public Calendar getStartDate() {
    if (!selectableDays.isEmpty())
        return selectableDays.first();
    if (mMinDate != null)
        return mMinDate;
    Calendar output = Calendar.getInstance(getTimeZone());
    output.set(Calendar.YEAR, mMinYear);
    output.set(Calendar.DAY_OF_MONTH, 1);
    output.set(Calendar.MONTH, Calendar.JANUARY);
    return output;
}

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 {/*from w w w.ja v a2s . co  m*/
        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.silverpeas.mailinglist.service.model.dao.TestMessageDao.java

@Test
public void testListActivities() {
    MessageDao messageDao = getMessageDAO();
    Calendar sentDate = Calendar.getInstance();
    sentDate.set(Calendar.MILLISECOND, 0);
    sentDate.set(Calendar.SECOND, 10);
    sentDate.set(Calendar.MINUTE, 3);
    sentDate.set(Calendar.HOUR, 10);
    sentDate.set(Calendar.DAY_OF_MONTH, 22);
    sentDate.set(Calendar.MONTH, Calendar.FEBRUARY);
    sentDate.set(Calendar.YEAR, 2008);
    Message message = new Message();
    message.setBody(textEmailContent);//from  w ww  .j  av  a 2  s.com
    message.setComponentId("componentId");
    message.setModerated(true);
    message.setSummary(textEmailContent.substring(0, 200));
    message.setSender("bart.simpson@ilverpeas.com");
    message.setMessageId("0000001747b40c22");
    Date message1SentDate = sentDate.getTime();
    message.setSentDate(message1SentDate);
    message.setTitle("Simple text message");
    Attachment attachment = new Attachment();
    attachment.setPath(attachmentPath + "lemonde.html");
    attachment.setFileName("lemonde.html");
    attachment.setSize(10000);
    message.getAttachments().add(attachment);
    attachment = new Attachment();
    attachment.setPath(attachmentPath + "lemonde2.html");
    attachment.setFileName("lemonde2.html");
    attachment.setSize(20000);
    message.getAttachments().add(attachment);
    messageDao.saveMessage(message);

    message = new Message();
    message.setBody(textEmailContent);
    message.setComponentId("componentId");
    message.setModerated(true);
    message.setSummary(textEmailContent.substring(0, 200));
    message.setSender("bart.simpson@ilverpeas.com");
    message.setMessageId("0000001747b40c23");
    sentDate.add(Calendar.MONTH, -1);
    Date message2SentDate = sentDate.getTime();
    message.setSentDate(message2SentDate);
    message.setTitle("Simple text message 2");
    messageDao.saveMessage(message);

    message = new Message();
    message.setBody(textEmailContent);
    message.setComponentId("componentId");
    message.setModerated(true);
    message.setSummary(textEmailContent.substring(0, 200));
    message.setSender("bart.simpson@ilverpeas.com");
    message.setMessageId("0000001747b40c24");
    sentDate.add(Calendar.DAY_OF_MONTH, -1);
    Date message3SentDate = sentDate.getTime();
    message.setSentDate(message3SentDate);
    message.setTitle("Simple text message 3");
    messageDao.saveMessage(message);

    message = new Message();
    message.setBody(textEmailContent);
    message.setComponentId("componentId");
    message.setModerated(false);
    message.setSummary(textEmailContent.substring(0, 200));
    message.setSender("bart.simpson@ilverpeas.com");
    message.setMessageId("0000001747b40c25");
    sentDate.add(Calendar.DAY_OF_MONTH, -1);
    message.setSentDate(message3SentDate);
    message.setTitle("Simple text message 4");
    messageDao.saveMessage(message);
    List activities = messageDao.listActivity("componentId");
    assertNotNull(activities);
    assertEquals(2, activities.size());
    Iterator iter = activities.iterator();
    while (iter.hasNext()) {
        Activity activity = (Activity) iter.next();
        assertEquals(activity.getYear(), 2008);
        if (activity.getMonth() == Calendar.FEBRUARY) {
            assertEquals(1, activity.getNbMessages());
        } else {
            assertEquals(Calendar.JANUARY, activity.getMonth());
            assertEquals(2, activity.getNbMessages());
        }
    }
}

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

/**
 * This method is used for converting to date to 1st day of year from given
 * year./*from w  w w .  j  a  va  2 s . c  o  m*/
 * 
 * @param year
 * @param date
 * @return
 * @throws ParseException
 */
public static long convertFirstDayInMilli(int year) throws ParseException {
    long d = 0;
    Calendar c = Calendar.getInstance();
    c.set(year, Calendar.JANUARY, 1, 00, 00, 00);
    d = c.getTimeInMillis();

    return d;
}