Example usage for java.util Calendar HOUR

List of usage examples for java.util Calendar HOUR

Introduction

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

Prototype

int HOUR

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

Click Source Link

Document

Field number for get and set indicating the hour of the morning or afternoon.

Usage

From source file:net.firejack.platform.core.utils.DateUtils.java

/**
 * Increments the date to round it on week level
 * @param date - date to be incremented/*from   w  ww.  ja  v  a  2  s .  co m*/
 * @return incremented date
 */
public static Date ceilDateToWeek(Date date) {
    date = addWeeks(date, 1);
    Calendar cal = new GregorianCalendar();
    cal.setTime(date);
    while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
        cal.add(Calendar.DAY_OF_MONTH, -1);
    }
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return addMinutes(cal.getTime(), -1);
}

From source file:org.starfishrespect.myconsumption.server.business.sensors.SensorsDataRetriever.java

/**
 * Retrieves and stores the data for one user
 *
 * @param onlyThisSensorId retrieve only data for one sensor with this id
 * @return false if something goes wrong; true otherwise
 *//*  w ww. j ava 2s.  c  o m*/
public boolean retrieve(List<Sensor> sensors, String onlyThisSensorId) {
    boolean allSuccessful = true;
    for (Sensor sensor : sensors) {
        System.out.println("Retrieve data for sensor " + sensor.getId());
        try {
            valuesRepository.setSensor(sensor.getId());
            valuesRepository.init();
            if (onlyThisSensorId != null) {
                if (!sensor.getId().equals(onlyThisSensorId)) {
                    continue;
                }
            }
            HashMap<Integer, HashMap<Integer, Integer>> sortedValues = new HashMap<Integer, HashMap<Integer, Integer>>();
            Date lastValue = sensor.getLastValue();
            SensorRetriever retriever = null;
            if (sensor instanceof FluksoSensor) {
                retriever = new FluksoRetriever((FluksoSensor) sensor);
            }
            if (retriever == null) {
                System.out.println("This sensor type has not been found!");
                continue;
            }
            TreeMap<Integer, Integer> data = retriever.getDataSince(lastValue).getData();
            if (data.size() != 0) {
                for (int key : data.keySet()) {
                    int hour = key - key % 3600;
                    HashMap<Integer, Integer> hourData = sortedValues.get(hour);
                    if (hourData == null) {
                        hourData = new HashMap<Integer, Integer>();
                        sortedValues.put(hour, hourData);
                    }
                    hourData.put(key % 3600, data.get(key));
                }

                for (int key : sortedValues.keySet()) {
                    Date dateKey = new Date(key * 1000L);
                    SensorDataset newValue = new SensorDataset(dateKey);
                    newValue.addAllValues(sortedValues.get(key));
                    valuesRepository.insertOrUpdate(newValue);
                }
                if (sensor.getLastValue().before(new Date(data.lastKey() * 1000L))) {
                    sensor.setLastValue(new Date(data.lastKey() * 1000L));
                }
                if (sensor.getFirstValue().after(new Date(data.firstKey() * 1000L))
                        || sensor.getFirstValue().getTime() == 0) {
                    sensor.setFirstValue(new Date(data.firstKey() * 1000L));
                }
                // sync operation, this avoid to insert a sensor who would have been deleted
                // while retrieving its data
                int currentUsageCount = sensorRepository.getUsageCount(sensor.getId());
                if (currentUsageCount > -1) {
                    // update, the field may have been incremented during retrieving
                    sensor.setUsageCount(currentUsageCount);
                    sensor.setDead(false);
                    sensorRepository.updateSensor(sensor);
                }
                System.out.println("Retrieve successful");
            } else {
                System.out.println("No values retrieved for this sensor");
                if (!sensor.isDead()) {
                    // test if sensor is dead ?
                    Calendar cal = new GregorianCalendar();
                    cal.add(Calendar.HOUR, -6);
                    if (sensor.getLastValue().before(new Date(cal.getTimeInMillis()))) {
                        System.out.println(
                                "Sensor has not sent anything in the last 6 hours! Set its status as dead.");
                        sensor.setDead(true);
                        sensorRepository.updateSensor(sensor);
                    }
                } else {
                    System.out.println("Sensor is still dead");
                }
            }
        } catch (RetrieveException | DaoException e) {
            System.err.println(e.getMessage());
            allSuccessful = false;
        }
    }

    return allSuccessful;
}

From source file:com.hyron.poscafe.CashRegister.java

public Date getAccountDate() {
    if (accountDate == null) {
        // If accountDate not set, return system date.
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    } else {/*from w  w w  .  j av a 2 s  .  c o  m*/
        return accountDate;
    }
}

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

/**
 * ??2009-08-07//from   w w  w  .j  av a2s .  c  o m
 */
public static String yesterdayDate2() {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.add(Calendar.DATE, -1);
    return convertDate2String5(cal.getTime());
}

From source file:com.ec2box.manage.action.UploadAndPushAction.java

@Action(value = "/admin/push", results = { @Result(name = "success", location = "/admin/upload_result.jsp") })
public String push() {

    Long userId = AuthUtil.getUserId(servletRequest.getSession());
    Long sessionId = AuthUtil.getSessionId(servletRequest.getSession());
    try {/*from   w  ww.  j  a  va  2 s .  c  o  m*/

        //get next pending system
        pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);
        if (pendingSystemStatus != null) {
            //get session for system
            SchSession session = null;
            for (Integer instanceId : SecureShellAction.getUserSchSessionMap().get(sessionId).getSchSessionMap()
                    .keySet()) {

                //if host system id matches pending system then upload
                if (pendingSystemStatus.getId().equals(SecureShellAction.getUserSchSessionMap().get(sessionId)
                        .getSchSessionMap().get(instanceId).getHostSystem().getId())) {
                    session = SecureShellAction.getUserSchSessionMap().get(sessionId).getSchSessionMap()
                            .get(instanceId);
                }
            }

            if (session != null) {

                //push upload to system
                currentSystemStatus = SSHUtil.pushUpload(pendingSystemStatus, session.getSession(),
                        UPLOAD_PATH + "/" + uploadFileName, pushDir + "/" + uploadFileName);

                //update system status
                SystemStatusDB.updateSystemStatus(currentSystemStatus, userId);

                pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);
            }

        }

        //if push has finished to all servers then delete uploaded file
        if (pendingSystemStatus == null) {
            File delFile = new File(UPLOAD_PATH, uploadFileName);
            FileUtils.deleteQuietly(delFile);

            //delete all expired files in upload path
            File delDir = new File(UPLOAD_PATH);
            if (delDir.isDirectory()) {

                //set expire time to delete all files older than 48 hrs
                Calendar expireTime = Calendar.getInstance();
                expireTime.add(Calendar.HOUR, -48);

                Iterator<File> filesToDelete = FileUtils.iterateFiles(delDir,
                        new AgeFileFilter(expireTime.getTime()), TrueFileFilter.TRUE);
                while (filesToDelete.hasNext()) {
                    delFile = filesToDelete.next();
                    delFile.delete();
                }

            }

        }
        hostSystemList = SystemStatusDB.getAllSystemStatus(userId);

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

    return SUCCESS;
}

From source file:strat.mining.multipool.stats.service.impl.DonationServiceImpl.java

/**
 * Return the value of all transactions of the previous month.
 * //  w ww.  jav a 2s .  c  om
 * @return
 */
private Float getLastMonthDonationsValue() {
    Calendar start = new GregorianCalendar();
    start.add(Calendar.MONTH, -1);
    start.set(Calendar.DAY_OF_MONTH, 1);
    start.set(Calendar.HOUR, 0);
    start.set(Calendar.MINUTE, 0);
    start.set(Calendar.SECOND, 0);
    start.set(Calendar.MILLISECOND, 0);
    List<Transaction> transactions = donationTransactionDao.getTransactionsBetween(start.getTime(),
            getFirstDayOfMonthDate());

    Float result = 0f;
    if (CollectionUtils.isNotEmpty(transactions)) {
        for (Transaction transaction : transactions) {
            result += transaction.getAmount();
        }
    }

    return result;
}

From source file:com.appeligo.search.messenger.Messenger.java

/**
 * /*from w ww  .j  a  v  a  2 s.c o m*/
 * @param messages
 */
public int send(com.appeligo.search.entity.Message... messages) {
    int sent = 0;
    if (messages == null) {
        return 0;
    }
    for (com.appeligo.search.entity.Message message : messages) {
        User user = message.getUser();
        if (user != null) {
            boolean changed = false;
            boolean abort = false;
            if ((!user.isEnabled()) || (!user.isRegistrationComplete())
                    || (message.isSms() && (!user.isSmsValid()))) {
                abort = true;
                if (message.getExpires() == null) {
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.HOUR, 24);
                    message.setExpires(new Timestamp(cal.getTimeInMillis()));
                    changed = true;
                }
            }
            if (message.isSms() && user.isSmsValid() && (!user.isSmsOKNow())) {

                Calendar now = Calendar.getInstance(user.getTimeZone());
                now.set(Calendar.MILLISECOND, 0);
                now.set(Calendar.SECOND, 0);

                Calendar nextWindow = Calendar.getInstance(user.getTimeZone());
                nextWindow.setTime(user.getEarliestSmsTime());
                nextWindow.set(Calendar.MILLISECOND, 0);
                nextWindow.set(Calendar.SECOND, 0);
                nextWindow.add(Calendar.MINUTE, 1); // compensate for zeroing out millis, seconds

                nextWindow.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE));

                int nowMinutes = (now.get(Calendar.HOUR) * 60) + now.get(Calendar.MINUTE);
                int nextMinutes = (nextWindow.get(Calendar.HOUR) * 60) + nextWindow.get(Calendar.MINUTE);
                if (nowMinutes > nextMinutes) {
                    nextWindow.add(Calendar.HOUR, 24);
                }
                message.setDeferUntil(new Timestamp(nextWindow.getTimeInMillis()));
                changed = true;
                abort = true;
            }
            if (changed) {
                message.save();
            }
            if (abort) {
                continue;
            }
        }
        String to = message.getTo();
        String from = message.getFrom();
        String subject = message.getSubject();
        String body = message.getBody();
        String contentType = message.getMimeType();
        try {

            Properties props = new Properties();

            //Specify the desired SMTP server
            props.put("mail.smtp.host", mailHost);
            props.put("mail.smtp.port", Integer.toString(port));
            // create a new Session object
            Session session = null;
            if (password != null) {
                props.put("mail.smtp.auth", "true");
                session = Session.getInstance(props, new SMTPAuthenticator(smtpUser, password));
            } else {
                session = Session.getInstance(props, null);
            }
            session.setDebug(debug);

            // create a new MimeMessage object (using the Session created above)
            Message mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setRecipients(Message.RecipientType.TO,
                    new InternetAddress[] { new InternetAddress(to) });
            mimeMessage.setSubject(subject);
            mimeMessage.setContent(body.toString(), contentType);
            if (mailHost.trim().equals("")) {
                log.info("No Mail Host.  Would have sent:");
                log.info("From: " + from);
                log.info("To: " + to);
                log.info("Subject: " + subject);
                log.info(mimeMessage.getContent());
            } else {
                Transport.send(mimeMessage);
                sent++;
            }
            message.setSent(new Date());
        } catch (Throwable t) {
            message.failedAttempt();
            if (message.getAttempts() >= maxAttempts) {
                message.setExpires(new Timestamp(System.currentTimeMillis()));
            }
            log.error(t.getMessage(), t);
        }
    }
    return sent;
}

From source file:net.wasdev.gameon.concierge.PlayerClient.java

/**
 * Obtain a JWT for the player id that can be used to invoke player REST services.
 * /* w ww.  java2s. co  m*/
 * We can create this, because the concierge has access to the private certificate 
 * required to sign such a JWT. 
 * 
 * @param playerId The id to build the JWT for
 * @return The JWT as a string.
 * @throws IOException
 */
private String getClientJwtForId(String playerId) throws IOException {
    // grab the key if needed
    if (signingKey == null)
        getKeyStoreInfo();

    Claims onwardsClaims = Jwts.claims();

    // Set the subject using the "id" field from our claims map.
    onwardsClaims.setSubject(playerId);

    // We'll use this claim to know this is a user token
    onwardsClaims.setAudience("client");

    // we set creation time to 24hrs ago, to avoid timezone issues in the
    // browser
    // verification of the jwt.
    Calendar calendar1 = Calendar.getInstance();
    calendar1.add(Calendar.HOUR, -24);
    onwardsClaims.setIssuedAt(calendar1.getTime());

    // client JWT has 24 hrs validity from now.
    Calendar calendar2 = Calendar.getInstance();
    calendar2.add(Calendar.HOUR, 24);
    onwardsClaims.setExpiration(calendar2.getTime());

    // finally build the new jwt, using the claims we just built, signing it
    // with our signing key, and adding a key hint as kid to the encryption 
    // header, which is optional, but can be used by the receivers of the 
    // jwt to know which key they should verifiy it with.
    String newJwt = Jwts.builder().setHeaderParam("kid", "playerssl").setClaims(onwardsClaims)
            .signWith(SignatureAlgorithm.RS256, signingKey).compact();

    return newJwt;
}

From source file:com.keybox.manage.action.UploadAndPushAction.java

@Action(value = "/admin/push", results = { @Result(name = "success", location = "/admin/upload_result.jsp") })
public String push() {

    Long userId = AuthUtil.getUserId(servletRequest.getSession());
    Long sessionId = AuthUtil.getSessionId(servletRequest.getSession());
    try {//from   w  w w .j a va2  s . co m

        //get next pending system
        pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);
        if (pendingSystemStatus != null) {
            //get session for system
            SchSession session = null;
            for (Integer instanceId : SecureShellAction.getUserSchSessionMap().get(sessionId).getSchSessionMap()
                    .keySet()) {

                //if host system id matches pending system then upload
                if (pendingSystemStatus.getId().equals(SecureShellAction.getUserSchSessionMap().get(sessionId)
                        .getSchSessionMap().get(instanceId).getHostSystem().getId())) {
                    session = SecureShellAction.getUserSchSessionMap().get(sessionId).getSchSessionMap()
                            .get(instanceId);
                }
            }

            if (session != null) {

                //push upload to system
                currentSystemStatus = SSHUtil.pushUpload(pendingSystemStatus, session.getSession(),
                        UPLOAD_PATH + "/" + uploadFileName, pushDir + "/" + uploadFileName);

                //update system status
                SystemStatusDB.updateSystemStatus(currentSystemStatus, userId);

                pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);
            }

        }

        //if push has finished to all servers then delete uploaded file
        if (pendingSystemStatus == null) {
            File delFile = new File(UPLOAD_PATH, uploadFileName);
            FileUtils.deleteQuietly(delFile);

            //delete all expired files in upload path
            File delDir = new File(UPLOAD_PATH);
            if (delDir.isDirectory()) {

                //set expire time to delete all files older than 48 hrs
                Calendar expireTime = Calendar.getInstance();
                expireTime.add(Calendar.HOUR, -48);

                Iterator<File> filesToDelete = FileUtils.iterateFiles(delDir,
                        new AgeFileFilter(expireTime.getTime()), TrueFileFilter.TRUE);
                while (filesToDelete.hasNext()) {
                    delFile = filesToDelete.next();
                    delFile.delete();
                }

            }

        }
        hostSystemList = SystemStatusDB.getAllSystemStatus(userId);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }

    return SUCCESS;
}

From source file:CalendarUtilsTest.java

/**
 * Tests various values with the trunc method
 *///w  w  w.  j av a 2  s  . co m
public void testTrunc() throws Exception {
    assertEquals("trunc year-1 failed", new Date("2002 January 1"), CalendarUtils.trunc(date1, Calendar.YEAR));
    assertEquals("trunc year-2 failed", new Date("2001 January 1"), CalendarUtils.trunc(date2, Calendar.YEAR));
    assertEquals("trunc month-1 failed", new Date("2002 February 1"),
            CalendarUtils.trunc(date1, Calendar.MONTH));
    assertEquals("trunc month-2 failed", new Date("2001 November 1"),
            CalendarUtils.trunc(date2, Calendar.MONTH));
    assertEquals("trunc semimonth-1 failed", new Date("2002 February 1"),
            CalendarUtils.trunc(date1, CalendarUtils.SEMI_MONTH));
    assertEquals("trunc semimonth-2 failed", new Date("2001 November 16"),
            CalendarUtils.trunc(date2, CalendarUtils.SEMI_MONTH));
    assertEquals("trunc date-1 failed", new Date("2002 February 12"),
            CalendarUtils.trunc(date1, Calendar.DATE));
    assertEquals("trunc date-2 failed", new Date("2001 November 18"),
            CalendarUtils.trunc(date2, Calendar.DATE));
    assertEquals("trunc hour-1 failed", parser.parse("February 12, 2002 12:00:00.000"),
            CalendarUtils.trunc(date1, Calendar.HOUR));
    assertEquals("trunc hour-2 failed", parser.parse("November 18, 2001 1:00:00.000"),
            CalendarUtils.trunc(date2, Calendar.HOUR));
    assertEquals("trunc minute-1 failed", parser.parse("February 12, 2002 12:34:00.000"),
            CalendarUtils.trunc(date1, Calendar.MINUTE));
    assertEquals("trunc minute-2 failed", parser.parse("November 18, 2001 1:23:00.000"),
            CalendarUtils.trunc(date2, Calendar.MINUTE));
    assertEquals("trunc second-1 failed", parser.parse("February 12, 2002 12:34:56.000"),
            CalendarUtils.trunc(date1, Calendar.SECOND));
    assertEquals("trunc second-2 failed", parser.parse("November 18, 2001 1:23:11.000"),
            CalendarUtils.trunc(date2, Calendar.SECOND));

}