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.umm.radonc.ca_dash.controllers.D3PieChartController.java

public D3PieChartController() {
    endDate = new Date();
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(endDate);/*w  w  w  .ja  va  2s  . c  o m*/
    gc.add(Calendar.MONTH, -1);
    startDate = gc.getTime();
    interval = "1m";
    this.df = new SimpleDateFormat("MM/dd/YYYY");
    this.selectedFacility = new Long(-1);
    this.dstats = new SynchronizedDescriptiveStatistics();
    this.interval = "";
    selectedFilters = new ArrayList<>();
    jsonData = new JSONArray();
}

From source file:com.vmware.appfactory.common.runner.LicenseStatus.java

/**
 * Find out whether license is expired or not using yesterday midnight.
 * Calculate the number of days until expiration.
 *//*from   w  w  w.j  a v  a  2s .c o  m*/
private final void calculateNumDaysToExpiration() {
    final GregorianCalendar gCal = new GregorianCalendar(AfCalendar.LOCAL_TZONE);
    gCal.add(Calendar.DATE, -1);
    final Date yesterdayMidnight = DateUtils.round(gCal.getTime(), Calendar.HOUR);
    setNumDaysToExpiration(
            (_expirationDate.getTime() - yesterdayMidnight.getTime()) / DateUtils.MILLIS_PER_DAY);

    if (getNumDaysToExpiration() <= 0) {
        _isExpired = true;
    } else {
        _isExpired = false;
    }
}

From source file:org.n52.oxf.ui.swing.ChartDialog.java

/**
 * //from  w w w . j  a  v  a2s.  c om
 */
public void actionPerformed(ActionEvent e) {
    try {
        if (e.getSource().equals(applyButton)) {
            paramCon.setParameterValue(Parameter.COMMON_NAME_TIME, timePeriodPanel.getChosenTime());

            OperationResult opRes = adapter.doOperation(
                    descriptor.getOperationsMetadata().getOperationByName(adapter.getResourceOperationName()),
                    paramCon);
            observations = featureStore.unmarshalFeatures(opRes);

            initChartPanel(observations, paramCon);
        }

        else if (e.getSource().equals(nowButton)) {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTimeInMillis(System.currentTimeMillis());
            Date date = calendar.getTime();

            SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            String result = ISO8601FORMAT.format(date);
            //convert into YYYYMMDDTHH:mm:ss+HH:00
            //- note the added colon for the Timezone
            result = result.substring(0, result.length() - 2) + ":" + result.substring(result.length() - 2);

            ITimePosition endPos = new TimePosition(result);
            timePeriodPanel.setEndPosition(endPos);
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

From source file:com.betel.flowers.web.bean.RegistroNacionalBean.java

private String generatedBarcode() {
    GregorianCalendar calendario = new GregorianCalendar();
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyy");
    return "BETEL-RN" + RandomStringUtils.randomNumeric(4) + "-IMG-" + format.format(calendario.getTime());
}

From source file:de.sindzinski.wetter.util.Utility.java

@SuppressLint("StringFormatMatches")
public static String getHourlyDayString(Context context, long timeInMillis, String timeZoneId) {
    // The day string for forecast uses the following logic:
    // For today: "Today, June 8"
    // For tomorrow:  "Tomorrow"
    // For the next 5 days: "Wednesday
    // " (just the day name)
    // For all days after that: "Mon Jun 8"
    TimeZone timeZone;/*w  w w. j  a  v a  2 s  .c  o  m*/
    if (timeZoneId.equals("")) {
        timeZone = TimeZone.getDefault();
    } else {
        timeZone = TimeZone.getTimeZone(timeZoneId);
    }
    GregorianCalendar gregorianCalendar = new GregorianCalendar(timeZone);
    gregorianCalendar.setTimeInMillis(timeInMillis);
    int day = gregorianCalendar.get(Calendar.DAY_OF_MONTH);
    //code for formatting the date
    Calendar calendar = Calendar.getInstance();
    int today = calendar.get(Calendar.DAY_OF_MONTH);
    Date time = gregorianCalendar.getTime();

    //        SimpleDateFormat shortDateFormat = new SimpleDateFormat("EEE MMM dd HH:MM");
    //        shortDateFormat.setTimeZone(timeZone);

    try {
        if (day < today + 1) {
            // If the input date is less than a week in the future, just return the day name.

            SimpleDateFormat shortDateFormat = new SimpleDateFormat("HH:00");
            shortDateFormat.setTimeZone(timeZone);
            String dsorig = shortDateFormat.format(timeInMillis);
            Date dconv = shortDateFormat.parse(dsorig);
            String sconv = shortDateFormat.format(dconv);
            return sconv;

        } else {
            // Otherwise, use the form "Mon Jun 3"
            SimpleDateFormat shortDateFormat = new SimpleDateFormat("EEE HH:00");
            shortDateFormat.setTimeZone(timeZone);
            String dsorig = shortDateFormat.format(timeInMillis);
            Date dconv = shortDateFormat.parse(dsorig);
            String sconv = shortDateFormat.format(dconv);
            return sconv;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}

From source file:msec.org.Tools.java

public static String generateDaysChart(String filename, ArrayList<OneDayValue> data, OneAttrDaysChart chart,
        String title, int duration) {
    if (data.size() == 0) {
        return "data size invalid";
    }//from  w  ww.j a  v  a2 s. c  o m

    int date = Integer.parseInt(data.get(0).getDate());
    GregorianCalendar startgc = new GregorianCalendar(date / 10000, date % 10000 / 100 - 1, date % 100);

    XYDataset xydataset = createDaysDataset(data, startgc, chart);
    JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(title, "time", "", xydataset, true, true, true);

    try {
        XYPlot xyplot = (XYPlot) jfreechart.getPlot();

        //
        DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
        dateaxis.setDateFormatOverride(new SimpleDateFormat("MM/dd"));
        dateaxis.setLabelFont(new Font("", Font.PLAIN, 16)); //
        dateaxis.setLabelPaint(ChartColor.gray);
        dateaxis.setTickLabelFont(new Font("", Font.PLAIN, 16));
        dateaxis.setTickLabelPaint(ChartColor.GRAY);

        dateaxis.setMinimumDate(startgc.getTime());
        GregorianCalendar endgc = (GregorianCalendar) startgc.clone();
        endgc.add(GregorianCalendar.DATE, duration);
        dateaxis.setMaximumDate(endgc.getTime());

        dateaxis.setTickMarksVisible(true);
        dateaxis.setTickMarkInsideLength(5);
        dateaxis.setTickUnit(new DateTickUnit(DateTickUnitType.DAY, 1));
        dateaxis.setVerticalTickLabels(true);
        dateaxis.setLabel("");

        //
        ValueAxis rangeAxis = xyplot.getRangeAxis();//?
        rangeAxis.setLabelFont(new Font("", Font.PLAIN, 16));
        rangeAxis.setLabelPaint(ChartColor.gray);
        rangeAxis.setTickLabelFont(new Font("", Font.PLAIN, 16));
        rangeAxis.setTickLabelPaint(ChartColor.gray);
        rangeAxis.setLowerBound(0);

        //
        jfreechart.getLegend().setItemFont(new Font("", Font.PLAIN, 12));
        jfreechart.getLegend().setItemPaint(ChartColor.gray);
        jfreechart.getLegend().setBorder(0, 0, 0, 0);//

        //
        jfreechart.getTitle().setFont(new Font("", Font.PLAIN, 18));//
        jfreechart.getTitle().setPaint(ChartColor.gray);

        //?
        xyplot.setRangeGridlinePaint(ChartColor.GRAY);
        xyplot.setBackgroundPaint(ChartColor.WHITE);
        xyplot.setOutlinePaint(null);//

        int w = 500;
        int h = 300;

        // ChartUtilities.saveChartAsPNG(new File(filename), jfreechart, w, h);
        ChartUtilities.saveChartAsJPEG(new File(filename), 0.8f, jfreechart, w, h);

        return "success";

    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
}

From source file:org.itracker.web.scheduler.tasks.ReminderNotification.java

/**
 * This method is called by the scheduler to send the reminder
 * notifications.  The arguments can be used to configure which issues
 * and projects are included in the notifications.  The args should
 * include as the first parameter the base url of the server including
 * the scheme, hostname, port, and context.  For example:
 * <br>/*from   w w w  .j  a v  a2  s  .  com*/
 * http://localhost:8080/itracker
 * <br>
 * If no other arguments are supplied it sends reminders to all
 * owners/admins of unresolved issues in all projects that have not been
 * modified in 30 days.  The second element of the array can be a number
 * that represents the number of days to use to check the last modified
 * date.  The third optional element is a number that represents the project
 * id to limit the notifications to. A fourth optional argument is the severity
 * to send the notification for.
 *
 * @param args optional arguments to configure the notification messages
 */
public void performTask(String[] args) {
    final List<Issue> issues;
    final ConfigurationService configurationService = ServletContextUtils.getItrackerServices()
            .getConfigurationService();

    String baseURL = configurationService.getSystemBaseURL();
    int notificationDays = configurationService.getIntegerProperty("reminder_notification_days",
            DEFAULT_ISSUE_AGE);

    int projectId = -1;
    int severity = -1;

    // Process arguments.
    if (args != null) {
        if (args.length > 0 && args[0] != null) {
            baseURL = args[0];
        }

        if (null == baseURL) {
            baseURL = DEFAULT_BASE_URL;
        }
        if (args.length > 1) {
            try {
                notificationDays = Integer.parseInt(args[1]);
            } catch (NumberFormatException nfe) {
                logger.debug("Invalid issue age specified in ReminderNotification task.");
            }
        }
        if (args.length > 2) {
            try {
                projectId = Integer.parseInt(args[2]);
            } catch (NumberFormatException nfe) {
                logger.debug("Invalid projectId specified in ReminderNotification task.");
            }
        }
        if (args.length > 3) {
            try {
                severity = Integer.parseInt(args[3]);
            } catch (NumberFormatException nfe) {
                logger.debug("Invalid severity specified in ReminderNotification task.");
            }
        }
    }
    if (notificationDays < 1) {
        logger.info("Reminder notifications are disabled for project " + projectId);
        return;
    }
    logger.debug("Reminder notifications being sent for project " + projectId + " with issues over "
            + notificationDays + " days old with severity " + severity + ".  Base URL = " + baseURL);

    try {
        IssueService issueService = ServletContextUtils.getItrackerServices().getIssueService();
        NotificationService notificationService = ServletContextUtils.getItrackerServices()
                .getNotificationService();
        GregorianCalendar cal = new GregorianCalendar();
        cal.add(Calendar.DAY_OF_MONTH, 0 - notificationDays);
        Date threshold = cal.getTime();

        if (projectId > 0) {
            issues = issueService.getIssuesByProjectId(projectId, IssueUtilities.STATUS_RESOLVED);
        } else {
            issues = issueService.getIssuesWithStatusLessThan(IssueUtilities.STATUS_RESOLVED);
        }
        if (issues != null && issues.size() > 0) {
            for (Issue issue : issues) {
                if (severity >= 0 && issue.getSeverity() != severity) {
                    continue;
                }
                if (issue.getLastModifiedDate() != null && issue.getLastModifiedDate().before(threshold)) {
                    List<Notification> notifications = notificationService.getPrimaryIssueNotifications(issue);
                    for (Notification notification : notifications) {
                        if (notification.getUser().getEmail() != null
                                && notification.getUser().getEmail().indexOf('@') >= 0) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("Sending reminder notification for issue " + issue.getId() + " to "
                                        + notification.getUser() + " users.");
                            }
                            notificationService.sendReminder(issue, notification.getUser(), baseURL,
                                    notificationDays);

                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error("Error sending reminder notifications. Message: ", e);
        throw new RuntimeException("failed to send reminder notifications.", e);
    }
}

From source file:org.tolven.gen.model.GenMedical.java

/**
* Return a time relative to now/*w  ww .j  a  va  2s . c  om*/
*/
public Date monthsAgo(int months) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(getNow());
    cal.add(GregorianCalendar.MONTH, -months);
    return cal.getTime();
}

From source file:org.squale.squalecommon.enterpriselayer.facade.component.AuditFacade.java

/**
 * Permet de reprogramm un audit sur une application au lendemain. si il s'agit d'un audit de suivi, l'audit dj
 * programm est supprim/*from  w ww . j a  v  a  2s  .c o m*/
 * 
 * @param pAudit AuditDTO dfinissant l'id de l'audit
 * @return l'audit reprogramm
 * @throws JrafEnterpriseException si erreur
 */
public static AuditDTO restartAudit(AuditDTO pAudit) throws JrafEnterpriseException {
    AuditDTO auditDTO = null;
    ISession session = null;
    try {
        // cration d'une session Hibernate
        session = PERSISTENTPROVIDER.getSession();
        AuditDAOImpl auditDAO = AuditDAOImpl.getInstance();
        // On rcupre l'audit dont l'id est renseign par pAudit
        AuditBO failedAudit = (AuditBO) auditDAO.load(session, new Long(pAudit.getID()));
        // On transforme le bo en dto
        auditDTO = AuditTransform.bo2Dto(failedAudit, pAudit.getApplicationId());
        // On change la date pour le lancer le lendemain  0:00
        GregorianCalendar cal = new GregorianCalendar();
        cal.add(GregorianCalendar.HOUR_OF_DAY,
                ApplicationFacade.HOUR_OF_AUDIT - cal.get(GregorianCalendar.HOUR_OF_DAY));
        cal.add(GregorianCalendar.MINUTE,
                ApplicationFacade.MINUTE_OF_AUDIT - cal.get(GregorianCalendar.MINUTE));
        auditDTO.setDate(cal.getTime());
        // Son status sera en attente d'excution
        auditDTO.setStatus(AuditBO.NOT_ATTEMPTED);
        // On insre l'audit avec un traitement diffrent selon le type de l'audit
        if (auditDTO.getType().equals(AuditBO.MILESTONE)) {
            auditDTO = insertAudit(auditDTO);
        } else { // Il s'agit d'un audit de suivi
            auditDTO = restartNormalAudit(auditDTO);
        }
    } catch (JrafDaoException e) {
        FacadeHelper.convertException(e, AuditFacade.class.getName() + ".restartAudit");
    } finally {
        FacadeHelper.closeSession(session, AuditFacade.class.getName() + ".restartAudit");
    }
    return auditDTO;
}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.CpuUsageReport.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 {// w  w w .  jav a 2s.co m
        PreparedStatement cmd = null;
        ResultSet rs = null;
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append("<table class=\"table table-hover\"><tr><th>URI</th><th>Average CPU Usage %</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)
                    && !isPolicyTypeOf(urls.get(i), PolicyType.PROCESS)) {
                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(percentcpu) from rawdatamachineprocess 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.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td></tr>");
            TimeSeries ts = new TimeSeries(url, Millisecond.class);
            try {
                //ok now get the raw data....
                cmd = con.prepareStatement(
                        "select percentcpu,utcdatetime from rawdatamachineprocess 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()) {
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(2));
                    Millisecond m = new Millisecond(gcal.getTime());
                    ts.addOrUpdate(m, rs.getDouble(1));

                }
                col.addSeries(ts);

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

        }
        data.append("</table>");

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

        try {
            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);
    }
}