Example usage for java.util GregorianCalendar set

List of usage examples for java.util GregorianCalendar set

Introduction

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

Prototype

public void set(int field, int value) 

Source Link

Document

Sets the given calendar field to the given value.

Usage

From source file:it.cineca.iris.restclient.main.Command.java

/**
 * Utiliy method/*from  ww  w .j  a va 2  s  .c o  m*/
 * 
 * @param min
 * @param max
 * @return random date as string.
 */
private String getRandomDate(int min, int max) {
    GregorianCalendar gc = new GregorianCalendar();
    int year = randBetween(min, max);
    gc.set(gc.YEAR, year);
    int dayOfYear = randBetween(1, gc.getActualMaximum(gc.DAY_OF_YEAR));
    gc.set(gc.DAY_OF_YEAR, dayOfYear);

    SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
    String dateFormatted = fmt.format(gc.getTime());
    System.out.println("Random Date: " + dateFormatted);

    return dateFormatted;
}

From source file:org.accada.epcis.repository.query.Schedule.java

/**
 * Sets the field of a GregorianCalender to its minimum, which is defined as
 * the minimal possible value according to the calendar type possibly
 * superseded by the defined values in the schedule we have. Returns whether
 * the new value has been set and is valid.
 * /*  ww w  .  java2  s . c o  m*/
 * @param cal
 *            Calendar to adjust.
 * @param field
 *            Field to adjust.
 * @return Returns whether the new value has been set and is valid.
 * @throws ImplementationException
 *             Almost any error.
 */
private boolean setFieldToMinimum(final GregorianCalendar cal, final int field)
        throws ImplementationExceptionResponse {
    int min;
    TreeSet<Integer> values = getValues(field);
    if (values.isEmpty()) {
        min = cal.getActualMinimum(field);
    } else {
        min = Math.max(values.first().intValue(), cal.getActualMinimum(field));
        if (min > cal.getActualMaximum(field)) {
            min = cal.getActualMaximum(field);
            if (!values.contains(Integer.valueOf(min)) || min < cal.getActualMinimum(field)
                    || min > cal.getActualMaximum(field)) {
                return false;
            }
        }
    }
    cal.set(field, min);
    return true;
}

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

private GregorianCalendar stringToGregorianCalendar(String date) {
    String datePart = date;/*  ww  w  .  j ava  2  s . co m*/
    GregorianCalendar calendar = new GregorianCalendar();
    boolean GMT = false;
    String timePart = "";
    if (date.contains("T")) {
        datePart = date.substring(0, date.indexOf("T"));
        timePart = date.substring(date.indexOf("T") + 1);
    } else {
        timePart = "000001";
    }
    if (datePart.length() != 8)
        return null;
    calendar.set(Calendar.YEAR, new Integer(datePart.substring(0, 4)));
    calendar.set(Calendar.MONTH, new Integer(datePart.substring(4, 6)) - 1);
    calendar.set(Calendar.DAY_OF_MONTH, new Integer(datePart.substring(6)));
    if (timePart.endsWith("Z")) {
        GMT = true;
        timePart = timePart.substring(0, timePart.length() - 1);
    }
    timePart = timePart.concat("000000");
    timePart = timePart.substring(0, 6);
    calendar.set(Calendar.HOUR, new Integer(timePart.substring(0, 2)));
    calendar.set(Calendar.MINUTE, new Integer(timePart.substring(2, 4)));
    calendar.set(Calendar.SECOND, new Integer(timePart.substring(4)));
    if (GMT)
        calendar.set(Calendar.ZONE_OFFSET, -1 * (calendar.get(Calendar.ZONE_OFFSET) / (1000 * 60 * 60)));
    return calendar;

}

From source file:org.accada.epcis.repository.query.Schedule.java

/**
 * Sets the specified field of the given callendar to the next scheduled
 * value. Returns whether the new value has been set and is valid.
 * /*from   www .  j  a v  a 2  s .  c om*/
 * @param cal
 *            Calendar to adjust.
 * @param field
 *            Field to adjust.
 * @return Returns whether the new value has been set and is valid.
 * @throws ImplementationException
 *             Almost any error.
 */
private boolean setToNextScheduledValue(final GregorianCalendar cal, final int field)
        throws ImplementationExceptionResponse {
    int next;
    TreeSet<Integer> vals = getValues(field);
    if (vals.isEmpty()) {
        next = cal.get(field) + 1;
    } else {
        try {
            // get next scheduled value which is bigger than current
            int incrValue = cal.get(field) + 1;
            next = vals.tailSet(new Integer(incrValue)).first().intValue();
        } catch (NoSuchElementException nse) {
            // there is no bigger scheduled value
            return false;
        }
    }
    if (next > cal.getActualMaximum(field) || next < cal.getActualMinimum(field)) {
        return false;
    }
    // all is well, set it to next
    cal.set(field, next);
    return true;
}

From source file:xc.mst.manager.record.DefaultRecordService.java

@Override
public long getCount(Date fromDate, Date untilDate, Set set, int formatId, int serviceId)
        throws IndexException {
    Date from; // fromDate, or the minimum value for a Date if fromDate is null
    Date until; // toDate, or now if toDate is null

    // If from is null, set it to the minimum possible value
    // Otherwise set it to the same value as fromDate
    if (fromDate == null) {
        GregorianCalendar c = new GregorianCalendar();
        c.setTime(new Date(0));
        c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY)
                - ((c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)) / (60 * 60 * 1000)));
        from = c.getTime();/* w  w  w .j  a v a 2 s  .c om*/
    } else {
        from = fromDate;
    }

    // If to is null, set it to now
    // Otherwise set it to the same value as toDate
    if (untilDate == null) {
        GregorianCalendar c = new GregorianCalendar();
        c.setTime(new Date());
        c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY)
                - ((c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)) / (60 * 60 * 1000)));

        until = c.getTime();
    } else {
        until = untilDate;
    }

    // True if we're getting the count for a specific set, false if we're getting it for all records
    boolean useSet = (set != null);

    // True if we're getting the count for a specific metadataPrefix, false if we're getting it for all records
    boolean useMetadataPrefix = (formatId > 0);

    DateFormat format = DateFormat.getInstance();

    if (log.isDebugEnabled())
        log.debug("Counting the records updated later than " + format.format(from) + " and earlier than "
                + format.format(until) + (useSet ? " with set ID " + set.getSetSpec() : "")
                + (useMetadataPrefix ? " with format ID " + formatId : ""));

    // Create a query to get the Documents for unprocessed records
    SolrQuery query = new SolrQuery();
    StringBuffer queryBuffer = new StringBuffer();
    queryBuffer.append(FIELD_SERVICE_ID).append(":").append(Integer.toString(serviceId));

    if (useSet)
        queryBuffer.append(" AND ").append(FIELD_SET_SPEC).append(":").append(set.getSetSpec());
    if (useMetadataPrefix)
        queryBuffer.append(" AND ").append(FIELD_FORMAT_ID).append(":").append(Integer.toString(formatId));

    queryBuffer.append(" AND ").append(FIELD_DELETED).append(":").append("false");

    query.setQuery(queryBuffer.toString());

    if (from != null && until != null)
        query.addFilterQuery(
                FIELD_UPDATED_AT + ":[" + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(from))
                        + " TO " + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(until)) + "]");

    // Get the result of the query
    RecordList records = new RecordList(query, 0);

    if (log.isDebugEnabled())
        log.debug("Found " + records.size() + " records updated later than " + format.format(from)
                + " and earlier than " + format.format(until)
                + (useSet ? " with set ID " + set.getSetSpec() : "")
                + (useMetadataPrefix ? " with format ID " + formatId : ""));

    // Return the list of results
    return records.size();
}

From source file:org.openhab.binding.powermax.internal.message.PowerMaxCommDriver.java

/**
 * Send a message to set the alarm time and date using the system time and date
 *
 * @return true if the message was sent or false if not
 *///from  w w  w .  java  2  s. c om
public boolean sendSetTime() {
    logger.debug("sendSetTime()");

    boolean done = false;

    GregorianCalendar cal = new GregorianCalendar();
    if (cal.get(Calendar.YEAR) >= 2000) {
        logger.debug(String.format("sendSetTime(): sync time %02d/%02d/%04d %02d:%02d:%02d",
                cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR),
                cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)));

        byte[] dynPart = new byte[6];
        dynPart[0] = (byte) cal.get(Calendar.SECOND);
        dynPart[1] = (byte) cal.get(Calendar.MINUTE);
        dynPart[2] = (byte) cal.get(Calendar.HOUR_OF_DAY);
        dynPart[3] = (byte) cal.get(Calendar.DAY_OF_MONTH);
        dynPart[4] = (byte) (cal.get(Calendar.MONTH) + 1);
        dynPart[5] = (byte) (cal.get(Calendar.YEAR) - 2000);

        done = sendMessage(new PowerMaxBaseMessage(PowerMaxSendType.SETTIME, dynPart), false, 0);

        cal.set(Calendar.MILLISECOND, 0);
        syncTimeCheck = cal.getTimeInMillis();
    } else {
        logger.warn(
                "PowerMax alarm binding: time not synchronized; please correct the date/time of your openHAB server");
        syncTimeCheck = null;
    }
    return done;
}

From source file:edu.umm.radonc.ca_dash.model.TxInstanceFacade.java

public TreeMap<Date, SynchronizedDescriptiveStatistics> getMonthlySummaryStats(Date startDate, Date endDate,
        Long hospitalser, String filter, boolean includeWeekends, boolean ptflag, boolean scheduledFlag) {
    Calendar cal = new GregorianCalendar();
    TreeMap<Date, SynchronizedDescriptiveStatistics> retval = new TreeMap<>();
    GregorianCalendar oc = new GregorianCalendar();
    List<Object[]> events;

    events = getDailyCounts(startDate, endDate, hospitalser, filter, false, ptflag, scheduledFlag);

    cal.setTime(startDate);//from  w ww .  j  a v  a  2s  .  co m

    int mo = cal.get(Calendar.MONTH);
    int yr = cal.get(Calendar.YEAR);

    int currYr = yr;
    int currMo = mo;
    int prevMo = -1;
    int prevYr = -1;
    SynchronizedDescriptiveStatistics currStats = new SynchronizedDescriptiveStatistics();
    int i = 0;
    while (cal.getTime().before(endDate) && i < events.size()) {

        Object[] event = events.get(i);
        Date d = (Date) event[0];
        Long count = (Long) event[1];

        prevMo = currMo;
        prevYr = currYr;
        cal.setTime(d);
        mo = cal.get(Calendar.MONTH);
        yr = cal.get(Calendar.YEAR);

        currMo = mo;
        currYr = yr;

        if (prevMo != currMo || prevYr != currYr) {
            oc.set(Calendar.MONTH, prevMo);
            oc.set(Calendar.YEAR, prevYr);
            oc.set(Calendar.DAY_OF_MONTH, 1);
            retval.put(oc.getTime(), currStats);
            currStats = new SynchronizedDescriptiveStatistics();
        }

        currStats.addValue(count);
        i++;
    }
    oc.set(Calendar.MONTH, currMo);
    oc.set(Calendar.YEAR, currYr);
    oc.set(Calendar.DAY_OF_MONTH, 1);
    retval.put(oc.getTime(), currStats);

    return retval;
}

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;/*from ww w.  j  a  v a 2s .  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.openhab.binding.powermax.internal.message.PowermaxCommManager.java

/**
 * Send a message to set the alarm time and date using the system time and date
 *
 * @return true if the message was sent or false if not
 *///  ww w.j av a 2 s  . c o m
public boolean sendSetTime() {
    logger.debug("sendSetTime()");

    boolean done = false;

    if (autoSyncTime) {
        GregorianCalendar cal = new GregorianCalendar();
        if (cal.get(Calendar.YEAR) >= 2000) {
            logger.debug("sendSetTime(): sync time {}",
                    String.format("%02d/%02d/%04d %02d:%02d:%02d", cal.get(Calendar.DAY_OF_MONTH),
                            cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), cal.get(Calendar.HOUR_OF_DAY),
                            cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)));

            byte[] dynPart = new byte[6];
            dynPart[0] = (byte) cal.get(Calendar.SECOND);
            dynPart[1] = (byte) cal.get(Calendar.MINUTE);
            dynPart[2] = (byte) cal.get(Calendar.HOUR_OF_DAY);
            dynPart[3] = (byte) cal.get(Calendar.DAY_OF_MONTH);
            dynPart[4] = (byte) (cal.get(Calendar.MONTH) + 1);
            dynPart[5] = (byte) (cal.get(Calendar.YEAR) - 2000);

            done = sendMessage(new PowermaxBaseMessage(PowermaxSendType.SETTIME, dynPart), false, 0);

            cal.set(Calendar.MILLISECOND, 0);
            syncTimeCheck = cal.getTimeInMillis();
        } else {
            logger.info(
                    "Powermax alarm binding: time not synchronized; please correct the date/time of your openHAB server");
            syncTimeCheck = null;
        }
    } else {
        syncTimeCheck = null;
    }
    return done;
}

From source file:weka.server.WekaServer.java

/**
 * Excecute a task//from w ww  .  j  a  v a2 s  .c  o  m
 * 
 * @param entry the task to execute
 */
protected synchronized void executeTask(final WekaTaskEntry entry) {

    final NamedTask task = m_taskMap.getTask(entry);
    if (task == null) {
        System.err.println("[WekaServer] Asked to execute an non-existent task! (" + entry.toString() + ")");
        return;
    }

    String hostToUse = chooseExecutionHost();

    if (task instanceof LogHandler) {
        Logger log = ((LogHandler) task).getLog();
        log.logMessage("Starting task \"" + entry.toString() + "\" (" + hostToUse + ")");
    }

    entry.setServer(hostToUse);
    if (hostToUse.equals(m_hostname + ":" + m_port)) {
        Runnable toRun = new Runnable() {
            @Override
            public void run() {

                Date startTime = new Date();
                GregorianCalendar cal = new GregorianCalendar();
                cal.setTime(startTime);

                // We only use resolution down to the minute level
                cal.set(Calendar.SECOND, 0);
                cal.set(Calendar.MILLISECOND, 0);
                // m_taskMap.setExecutionTime(entry, startTime);
                entry.setLastExecution(cal.getTime());
                if (entry.getCameFromMaster()) {
                    // Talk back to the master - tell it the execution time,
                    // and that the task is now processing
                    sendExecutionTimeToMaster(entry);
                    sendTaskStatusInfoToMaster(entry, TaskStatusInfo.PROCESSING);
                }

                // ask the task to load any resources (if necessary)
                task.loadResources();
                task.execute();

                // save this task so that we have the last execution
                // time recorded
                // if (task instanceof Scheduled) {
                persistTask(entry, task);

                // save memory (if possible)
                task.persistResources();

                // }

                if (entry.getCameFromMaster()) {
                    // Talk back to the master - pass on the actual final execution
                    // status
                    sendTaskStatusInfoToMaster(entry, task.getTaskStatus().getExecutionStatus());
                }
            }
        };

        if (entry.getCameFromMaster()) {
            // Talk back to the master - tell it that this
            // task is pending (WekaTaskMap.WekaTaskEntry.PENDING)
            sendTaskStatusInfoToMaster(entry, WekaTaskMap.WekaTaskEntry.PENDING);
        }
        m_executorPool.execute(toRun);
    } else {
        if (!executeTaskRemote(entry, task, hostToUse)) {
            // failed to hand off to slave for some reason
            System.err.println("[WekaServer] Failed to hand task '" + entry.toString() + "' to slave server ('"
                    + hostToUse + ")");
            System.out.println("[WekaServer] removing '" + hostToUse + "' from " + "list of slaves.");
            m_slaves.remove(hostToUse);
            System.out.println("[WekaServer] Re-trying execution of task '" + entry.toString() + "'");
            executeTask(entry);
        }
    }
}