Example usage for java.util GregorianCalendar getTime

List of usage examples for java.util GregorianCalendar getTime

Introduction

In this page you can find the example usage for java.util GregorianCalendar getTime.

Prototype

public final Date getTime() 

Source Link

Document

Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Usage

From source file:edu.duke.cabig.c3pr.web.DashboardController.java

private void getMostEnrolledStudies(HttpServletRequest request) {
    GregorianCalendar cal = new GregorianCalendar();
    Date endDate = new Date(System.currentTimeMillis());
    cal.setTime(endDate);/*  w w  w .j  a va 2s.  c  om*/
    cal.roll(Calendar.DATE, -6);
    Date startDate = new Date(cal.getTime().getTime());

    List<Study> studiesFound = studySubjectDao.getMostEnrolledStudies(startDate, endDate);
    List<Study> studies = new ArrayList<Study>();
    for (int i = 0; i < studiesFound.size() && i < MAX_RESULTS; i++) {
        studies.add(studiesFound.get(i));
    }
    log.debug("Most enrolled studies found: " + studies.size());
    request.setAttribute("aStudies", studies);
}

From source file:org.sipfoundry.sipxconfig.admin.monitoring.RRDToolGraphUpdater.java

private void updateGraph(MRTGTarget target, boolean detailed, long duration, String intervalExt)
        throws Exception {
    String graphExt = intervalExt + MonitoringUtil.GRAPH_EXTENSION;
    if (!graphNeedsUpdate(target, graphExt)) {
        return;/*from  ww  w.  j a  va 2  s  .c o m*/
    }
    String dataFileName = m_dataDirectory + target.getId() + RRD_FILE_EXTENSION;
    // create the graph
    GregorianCalendar c = new GregorianCalendar();
    long currentTimeSeconds = c.getTime().getTime() / 1000;

    List<String> commandVector = new ArrayList<String>();
    commandVector.add(RRD_TOOL_COMMAND);
    commandVector.add(RRD_GRAPH_COMMAND);
    commandVector.add(m_graphDirectory + target.getId() + graphExt);
    commandVector.add("--start");
    commandVector.add(new Long(currentTimeSeconds - duration) + StringUtils.EMPTY);
    commandVector.add("--end");
    commandVector.add(currentTimeSeconds + StringUtils.EMPTY);
    commandVector.add(DASH + C_LETTER);
    commandVector.add("FONT#" + COLOR);
    commandVector.add(DASH + C_LETTER);
    commandVector.add("MGRID#" + COLOR);
    commandVector.add(DASH + C_LETTER);
    commandVector.add("FRAME#" + COLOR);
    commandVector.add(DASH + C_LETTER);
    commandVector.add("BACK#" + BACKGROUND_COLOR);
    commandVector.add(DASH + C_LETTER);
    commandVector.add("ARROW#" + COLOR);

    if (target.getMaxBytes() < Integer.MAX_VALUE) {
        commandVector.add("-u");
        commandVector.add(new Long(target.getMaxBytes()).toString());
    }
    commandVector.add("-l");
    commandVector.add("0");
    commandVector.add("-v");
    commandVector.add(target.getYLegend());

    if (detailed) {
        commandVector.add(DASH + W_LETTER);
        commandVector.add(StringUtils.EMPTY + DETAILED_GRAPH_X_SIZE);
        commandVector.add(DASH + H_LETTER);
        commandVector.add(StringUtils.EMPTY + DETAILED_GRAPH_Y_SIZE);
        if (StringUtils.isNotEmpty(target.getLegend1())) {
            commandVector.add(DEF_IN + dataFileName + DS0_AVERAGE);
            commandVector.add(AREA_IN + AREA_COLOR + MonitoringUtil.COLON + target.getLegend1());
            commandVector.add(PRINT_AVERAGE + target.getLegendI() + LF);
            commandVector.add(PRINT_MAX + target.getLegendI() + LF);
            commandVector.add(PRINT_LAST + target.getLegendI() + LF);
        }
        if (StringUtils.isNotEmpty(target.getLegend2())) {
            commandVector.add(DEF_LINE2 + dataFileName + DS1_AVERAGE);
            commandVector.add(LINE2 + LINE_COLOR + MonitoringUtil.COLON + target.getLegend2());
            commandVector.add(PRINT_AVERAGE_LINE2 + target.getLegendO() + LF);
            commandVector.add(PRINT_MAX_LINE2 + target.getLegendO() + LF);
            commandVector.add(PRINT_LAST_LINE2 + target.getLegendO() + LF);
        }
    } else {
        commandVector.add(DASH + W_LETTER);
        commandVector.add(StringUtils.EMPTY + SUMMARY_GRAPH_X_SIZE);
        commandVector.add(DASH + H_LETTER);
        commandVector.add(StringUtils.EMPTY + SUMMARY_GRAPH_Y_SIZE);
        if (StringUtils.isNotEmpty(target.getLegendI())) {
            commandVector.add(DEF_IN + dataFileName + DS0_AVERAGE);
            commandVector.add(AREA_IN + AREA_COLOR + MonitoringUtil.COLON + target.getLegendI());
        }
        if (StringUtils.isNotEmpty(target.getLegendO())) {
            commandVector.add(DEF_LINE2 + dataFileName + DS1_AVERAGE);
            commandVector.add(LINE2 + LINE_COLOR + MonitoringUtil.COLON + target.getLegendO());
        }
    }
    String[] commandArray = new String[commandVector.size()];
    for (int i = 0; i < commandVector.size(); i++) {
        commandArray[i] = commandVector.get(i);
    }
    executeCommand(target, intervalExt, commandArray);
}

From source file:com.xebialabs.deployit.ci.server.DeployCommand.java

private void checkTaskState(String taskId) {
    TaskState taskState = taskService.getTask(taskId);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    listener.info(format("%s Description   %s", taskId, taskState.getDescription()));
    listener.info(format("%s State         %s %d/%d", taskId, taskState.getState(),
            taskState.getCurrentStepNr(), taskState.getNrSteps()));
    if (taskState.getStartDate() != null) {
        final GregorianCalendar startDate = taskState.getStartDate().toGregorianCalendar();
        listener.info(format("%s Start      %s", taskId, sdf.format(startDate.getTime())));
    }/*  w w w  . j a  v a  2 s .  c  o m*/

    if (taskState.getCompletionDate() != null) {
        final GregorianCalendar completionDate = taskState.getCompletionDate().toGregorianCalendar();
        listener.info(format("%s Completion %s", taskId, sdf.format(completionDate.getTime())));
    }

    StringBuilder sb = new StringBuilder();
    for (int i = 1; i <= taskState.getNrSteps(); i++) {
        final StepState stepInfo = taskService.getStep(taskId, i, null);
        final String description = stepInfo.getDescription();
        final String log = stepInfo.getLog();
        String stepInfoMessage;
        if (StringUtils.isEmpty(log) || description.equals(log)) {
            stepInfoMessage = format("%s step #%d %s\t%s", taskId, i, stepInfo.getState(), description);
        } else {
            stepInfoMessage = format("%s step #%d %s\t%s\n%s", taskId, i, stepInfo.getState(), description,
                    log);
        }

        listener.info(stepInfoMessage);
        if (StepExecutionState.FAILED.equals(stepInfo.getState()))
            sb.append(stepInfoMessage);
    }

    if (taskState.getState().isExecutionHalted())
        throw new DeployitPluginException(format("Errors when executing task %s: %s", taskId, sb));
}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.NetworkIOReport.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {//from   ww w  .  ja va2  s .  com
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;
        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append("This represents the network throughput rates of a machine over time.<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Average Send Rate</th><th>Average Recieve Rate</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            data.append("<tr><td>").append(url).append("</td>");
            double average = 0;
            try {
                cmd = con.prepareStatement(
                        "select avg(sendkbs) from rawdatanic where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td>");
            average = 0;
            try {
                cmd = con.prepareStatement(
                        "select avg(receivekbs) from rawdatanic where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("<td>").append(average + "").append("</td></tr>");

            //ok now get the raw data....
            TimeSeriesContainer tsc = new TimeSeriesContainer();
            try {
                cmd = con.prepareStatement(
                        "select receivekbs, sendkbs, utcdatetime, nicid from rawdatanic where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                while (rs.next()) {

                    TimeSeries ts = tsc.Get(url + " " + rs.getString("nicid") + " RX", Millisecond.class);
                    TimeSeries ts2 = tsc.Get(url + " " + rs.getString("nicid") + " TX", Millisecond.class);
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(3));
                    Millisecond m = new Millisecond(gcal.getTime());
                    ts.addOrUpdate(m, rs.getLong(1));
                    ts2.addOrUpdate(m, rs.getLong(2));
                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            for (int ik = 0; ik < tsc.data.size(); ik++) {
                col.addSeries(tsc.data.get(ik));
            }

        }

        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Rate", col,
                true, false, false);

        data.append("</table>");
        try {
            // if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            // }
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }

}

From source file:io.github.proxyprint.kitchen.models.printshops.RegisterRequest.java

/**
 * From GregoriaCalendar to String./*ww  w  . ja va  2  s.  c  o  m*/
 *
 * @param c, GregorianCalendar instance
 * @return Well formated string for display
 */
private String GregorianCalendarToString(GregorianCalendar c) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
    sdf.setCalendar(c);
    String dateFormatted = sdf.format(c.getTime());
    return dateFormatted;
}

From source file:org.silverpeas.core.workflow.engine.instance.HistoryStepImpl.java

/**
 * Set the today as date when the action has been done
 *//*from w  w  w .  j a  v a2 s  .  co  m*/
private void setTodayAsActionDate() {
    GregorianCalendar calendar = new GregorianCalendar();
    this.actionDate = calendar.getTime();
}

From source file:edu.lternet.pasta.portal.statistics.GrowthStats.java

private ArrayList<Integer> buildFrequencies(GregorianCalendar start, GregorianCalendar end, int scale,
        Long[] list) {//  w  w  w .  jav a2 s. c  o m

    ArrayList<Integer> freqs = new ArrayList<Integer>();

    GregorianCalendar lower = (GregorianCalendar) start.clone();
    GregorianCalendar upper = new GregorianCalendar();

    while (lower.getTimeInMillis() <= end.getTimeInMillis()) {
        upper.setTime(lower.getTime());
        upper.add(scale, 1);

        int freq = 0;

        for (int i = 0; i < list.length; i++) {
            if (lower.getTimeInMillis() <= list[i] && list[i] < upper.getTimeInMillis()) {
                freq++;
                //System.out.printf("%d - %d - %d - %d%n", lower.getTimeInMillis(), list[i], upper.getTimeInMillis(), freq);
            }
        }
        freqs.add(freq);
        lower.setTime(upper.getTime());

    }

    return freqs;

}

From source file:edu.umm.radonc.ca_dash.controllers.D3PieChartController.java

public void onSelectTimePeriod() {
    endDate = new Date();
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(endDate);//  ww w  . j a v  a2 s. co  m

    switch (interval) {
    case "1wk":
        gc.add(Calendar.DATE, -7);
        startDate = gc.getTime();
        break;
    case "1m":
        gc.add(Calendar.MONTH, -1);
        startDate = gc.getTime();
        break;
    case "3m":
        gc.add(Calendar.MONTH, -3);
        startDate = gc.getTime();
        break;
    case "6m":
        gc.add(Calendar.MONTH, -6);
        startDate = gc.getTime();
        break;
    case "1y":
        gc.add(Calendar.YEAR, -1);
        startDate = gc.getTime();
        break;
    case "2y":
        gc.add(Calendar.YEAR, -2);
        startDate = gc.getTime();
        break;
    case "3y":
        gc.add(Calendar.YEAR, -3);
        startDate = gc.getTime();
        break;
    case "Q1":
        gc.setTime(FiscalDate.getQuarter(1));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    case "Q2":
        gc.setTime(FiscalDate.getQuarter(2));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    case "Q3":
        gc.setTime(FiscalDate.getQuarter(3));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    case "Q4":
        gc.setTime(FiscalDate.getQuarter(4));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    }
}

From source file:org.mifos.calendar.CalendarUtils.java

public static DateTime getFirstDayForMonthUsingWeekRankAndWeekday(final DateTime startDate,
        final int calendarWeekOfMonth, final int dayOfWeek) {

    /*/*from   www. j a  v  a 2s.  c  om*/
     * In Joda time MONDAY=1 and SUNDAY=7, so shift these to SUNDAY=1, SATURDAY=7 to match this class
     */
    int calendarDayOfWeek = (dayOfWeek % 7) + 1;

    final GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(startDate.toDate());

    DateTime scheduleDate = null;
    // if current weekday is after the weekday on which schedule has to
    // lie, move to next week
    if (gc.get(Calendar.DAY_OF_WEEK) > calendarDayOfWeek) {
        gc.add(Calendar.WEEK_OF_MONTH, 1);
    }
    // set the weekday on which schedule has to lie
    gc.set(Calendar.DAY_OF_WEEK, calendarDayOfWeek);
    // if week rank is First, Second, Third or Fourth, Set the
    // respective week.
    // if current week rank is after the weekrank on which schedule has
    // to lie, move to next month
    if (!RankOfDay.getRankOfDay(calendarWeekOfMonth).equals(RankOfDay.LAST)) {
        if (gc.get(Calendar.DAY_OF_WEEK_IN_MONTH) > calendarWeekOfMonth) {
            gc.add(GregorianCalendar.MONTH, 1);
            gc.set(GregorianCalendar.DATE, 1);
        }
        // set the weekrank on which schedule has to lie
        gc.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, calendarWeekOfMonth);
        scheduleDate = new DateTime(gc.getTime().getTime());
    } else {// scheduleData.getWeekRank()=Last
        int M1 = gc.get(GregorianCalendar.MONTH);
        // assumption: there are 5 weekdays in the month
        gc.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, 5);
        int M2 = gc.get(GregorianCalendar.MONTH);
        // if assumption fails, it means there exists 4 weekdays in a
        // month, return last weekday date
        // if M1==M2, means there exists 5 weekdays otherwise 4 weekdays
        // in a month
        if (M1 != M2) {
            gc.set(GregorianCalendar.MONTH, gc.get(GregorianCalendar.MONTH) - 1);
            gc.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, 4);
        }
        scheduleDate = new DateTime(gc.getTime().getTime());
    }

    return scheduleDate;
}

From source file:Main.java

/**
 * Given a calendar (possibly containing only a day of the year), returns the earliest possible
 * anniversary of the date that is equal to or after the current point in time if the date
 * does not contain a year, or the date converted to the local time zone (if the date contains
 * a year.//from w  w w .j ava 2  s.co m
 *
 * @param target The date we wish to convert(in the UTC time zone).
 * @return If date does not contain a year (year < 1900), returns the next earliest anniversary
 * that is after the current point in time (in the local time zone). Otherwise, returns the
 * adjusted Date in the local time zone.
 */
public static Date getNextAnnualDate(Calendar target) {
    final Calendar today = Calendar.getInstance();
    today.setTime(new Date());

    // Round the current time to the exact start of today so that when we compare
    // today against the target date, both dates are set to exactly 0000H.
    today.set(Calendar.HOUR_OF_DAY, 0);
    today.set(Calendar.MINUTE, 0);
    today.set(Calendar.SECOND, 0);
    today.set(Calendar.MILLISECOND, 0);

    final boolean isYearSet = isYearSet(target);
    final int targetYear = target.get(Calendar.YEAR);
    final int targetMonth = target.get(Calendar.MONTH);
    final int targetDay = target.get(Calendar.DAY_OF_MONTH);
    final boolean isFeb29 = (targetMonth == Calendar.FEBRUARY && targetDay == 29);
    final GregorianCalendar anniversary = new GregorianCalendar();
    // Convert from the UTC date to the local date. Set the year to today's year if the
    // there is no provided year (targetYear < 1900)
    anniversary.set(!isYearSet ? today.get(Calendar.YEAR) : targetYear, targetMonth, targetDay);
    // If the anniversary's date is before the start of today and there is no year set,
    // increment the year by 1 so that the returned date is always equal to or greater than
    // today. If the day is a leap year, keep going until we get the next leap year anniversary
    // Otherwise if there is already a year set, simply return the exact date.
    if (!isYearSet) {
        int anniversaryYear = today.get(Calendar.YEAR);
        if (anniversary.before(today) || (isFeb29 && !anniversary.isLeapYear(anniversaryYear))) {
            // If the target date is not Feb 29, then set the anniversary to the next year.
            // Otherwise, keep going until we find the next leap year (this is not guaranteed
            // to be in 4 years time).
            do {
                anniversaryYear += 1;
            } while (isFeb29 && !anniversary.isLeapYear(anniversaryYear));
            anniversary.set(anniversaryYear, targetMonth, targetDay);
        }
    }
    return anniversary.getTime();
}