Example usage for java.time.temporal ChronoUnit HOURS

List of usage examples for java.time.temporal ChronoUnit HOURS

Introduction

In this page you can find the example usage for java.time.temporal ChronoUnit HOURS.

Prototype

ChronoUnit HOURS

To view the source code for java.time.temporal ChronoUnit HOURS.

Click Source Link

Document

Unit that represents the concept of an hour.

Usage

From source file:com.ikanow.aleph2.data_model.utils.TimeUtils.java

/** The simplest date parsing utility - only handles daily/hourly/monthly type strings (1d, d, daily, day - etc). Note "m" is ambiguous and not supported, use "min" or "month"
 * @param human_readable_period - daily/hourly/monthly type strings (1d, d, daily, day - etc). Note "m" is ambiguous and not supported, use "min" or "month"
 * @return a ChronoUnit if successful, else a generic error string
 *///from w w  w .ja va2s  . co m
public static Validation<String, ChronoUnit> getTimePeriod(final String human_readable_period) {
    return Patterns
            .match(Optional.ofNullable(human_readable_period).orElse("").toLowerCase().replaceAll("\\s+", ""))
            .<Validation<String, ChronoUnit>>andReturn()
            .when(d -> d.equals("1d"), __ -> Validation.success(ChronoUnit.DAYS))
            .when(d -> d.equals("d"), __ -> Validation.success(ChronoUnit.DAYS))
            .when(d -> d.equals("1day"), __ -> Validation.success(ChronoUnit.DAYS))
            .when(d -> d.equals("day"), __ -> Validation.success(ChronoUnit.DAYS))
            .when(d -> d.equals("daily"), __ -> Validation.success(ChronoUnit.DAYS))

            .when(d -> d.equals("1w"), __ -> Validation.success(ChronoUnit.WEEKS))
            .when(d -> d.equals("w"), __ -> Validation.success(ChronoUnit.WEEKS))
            .when(d -> d.equals("1wk"), __ -> Validation.success(ChronoUnit.WEEKS))
            .when(d -> d.equals("wk"), __ -> Validation.success(ChronoUnit.WEEKS))
            .when(d -> d.equals("1week"), __ -> Validation.success(ChronoUnit.WEEKS))
            .when(d -> d.equals("week"), __ -> Validation.success(ChronoUnit.WEEKS))
            .when(d -> d.equals("weekly"), __ -> Validation.success(ChronoUnit.WEEKS))

            .when(d -> d.equals("1month"), __ -> Validation.success(ChronoUnit.MONTHS))
            .when(d -> d.equals("month"), __ -> Validation.success(ChronoUnit.MONTHS))
            .when(d -> d.equals("monthly"), __ -> Validation.success(ChronoUnit.MONTHS))

            .when(d -> d.equals("1sec"), __ -> Validation.success(ChronoUnit.SECONDS))
            .when(d -> d.equals("sec"), __ -> Validation.success(ChronoUnit.SECONDS))
            .when(d -> d.equals("1s"), __ -> Validation.success(ChronoUnit.SECONDS))
            .when(d -> d.equals("s"), __ -> Validation.success(ChronoUnit.SECONDS))
            .when(d -> d.equals("1second"), __ -> Validation.success(ChronoUnit.SECONDS))
            .when(d -> d.equals("second"), __ -> Validation.success(ChronoUnit.SECONDS))

            .when(d -> d.equals("1min"), __ -> Validation.success(ChronoUnit.MINUTES))
            .when(d -> d.equals("min"), __ -> Validation.success(ChronoUnit.MINUTES))
            .when(d -> d.equals("1minute"), __ -> Validation.success(ChronoUnit.MINUTES))
            .when(d -> d.equals("minute"), __ -> Validation.success(ChronoUnit.MINUTES))

            .when(d -> d.equals("1h"), __ -> Validation.success(ChronoUnit.HOURS))
            .when(d -> d.equals("h"), __ -> Validation.success(ChronoUnit.HOURS))
            .when(d -> d.equals("1hour"), __ -> Validation.success(ChronoUnit.HOURS))
            .when(d -> d.equals("hour"), __ -> Validation.success(ChronoUnit.HOURS))
            .when(d -> d.equals("hourly"), __ -> Validation.success(ChronoUnit.HOURS))

            .when(d -> d.equals("1y"), __ -> Validation.success(ChronoUnit.YEARS))
            .when(d -> d.equals("y"), __ -> Validation.success(ChronoUnit.YEARS))
            .when(d -> d.equals("1year"), __ -> Validation.success(ChronoUnit.YEARS))
            .when(d -> d.equals("year"), __ -> Validation.success(ChronoUnit.YEARS))
            .when(d -> d.equals("1yr"), __ -> Validation.success(ChronoUnit.YEARS))
            .when(d -> d.equals("yr"), __ -> Validation.success(ChronoUnit.YEARS))
            .when(d -> d.equals("yearly"), __ -> Validation.success(ChronoUnit.YEARS))

            .otherwise(__ -> Validation
                    .fail(ErrorUtils.get(ErrorUtils.INVALID_DATETIME_FORMAT, human_readable_period)));
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedHEADUriFromPath() throws IOException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*w w  w.  ja v a  2  s .  co  m*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.put(path, TEST_DATA);

    // This will throw an error if the newly inserted object isn't present
    mantaClient.head(path);

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "HEAD", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    try {
        connection.setReadTimeout(3000);
        connection.setRequestMethod("HEAD");
        connection.connect();

        Map<String, List<String>> headers = connection.getHeaderFields();

        if (connection.getResponseCode() != 200) {
            Assert.fail(IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset()));
        }

        Assert.assertNotNull(headers);
        Assert.assertEquals(TEST_DATA.length(), connection.getContentLength());
    } finally {
        connection.disconnect();
    }
}

From source file:com.querydsl.webhooks.GithubReviewWindow.java

@VisibleForTesting
protected static String makeHumanReadable(Duration duration) {
    StringBuilder output = new StringBuilder();
    duration = truncateAndAppend(duration, duration.toDays(), ChronoUnit.DAYS, "day", output);
    duration = truncateAndAppend(duration, duration.toHours(), ChronoUnit.HOURS, "hour", output);
    duration = truncateAndAppend(duration, duration.toMinutes(), ChronoUnit.MINUTES, "minute", output);
    duration = truncateAndAppend(duration, duration.getSeconds(), ChronoUnit.SECONDS, "second", output);
    return output.toString().trim();
}

From source file:cn.edu.zjnu.acm.judge.user.ResetPasswordController.java

@PostMapping("/resetPassword")
public void doPost(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "action", required = false) String action,
        @RequestParam(value = "verify", required = false) String verify,
        @RequestParam(value = "username", required = false) String username, Locale locale) throws IOException {
    response.setContentType("text/javascript;charset=UTF-8");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(false);
    String word = null;//w  w  w  . j a v a2s .co m
    if (session != null) {
        word = (String) session.getAttribute("word");
        session.removeAttribute("word");
    }
    if (word == null || !word.equalsIgnoreCase(verify)) {
        out.print("alert('??');");
        return;
    }

    User user = userMapper.findOne(username);
    if (user == null) {
        out.print("alert('?');");
        return;
    }
    String email = user.getEmail();
    if (email == null || !email.toLowerCase().matches(ValueCheck.EMAIL_PATTERN)) {
        out.print(
                "alert('???????');");
        return;
    }
    try {
        String vc = user.getVcode();
        if (vc == null || user.getExpireTime() != null && user.getExpireTime().compareTo(Instant.now()) < 0) {
            vc = Utility.getRandomString(16);
        }
        user = user.toBuilder().vcode(vc).expireTime(Instant.now().plus(1, ChronoUnit.HOURS)).build();
        userMapper.update(user);
        String url = getPath(request, "/resetPassword.html?vc=", vc + "&u=", user.getId());
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("url", url);
        map.put("ojName", judgeConfiguration.getContextPath() + " OJ");

        String content = templateEngine.process("users/password", new Context(locale, map));
        String title = templateEngine.process("users/passwordTitle", new Context(locale, map));

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setTo(email);
        helper.setSubject(title);
        helper.setText(content, true);
        helper.setFrom(javaMailSender.getUsername());

        javaMailSender.send(mimeMessage);
    } catch (MailException | MessagingException ex) {
        log.error("", ex);
        out.print("alert('?????')");
        return;
    }
    out.print("alert('???" + user.getEmail() + "??');");
}

From source file:devbury.dewey.plugins.RemindMe.java

private Date notifyAt(long amount, String units) {
    ChronoUnit chronoUnit = ChronoUnit.SECONDS;
    switch (units) {
    case "weeks":
    case "week":
        chronoUnit = ChronoUnit.WEEKS;
        break;/*from   w  w w  .j  av a  2  s  .  c om*/
    case "months":
    case "month":
        chronoUnit = ChronoUnit.MONTHS;
        break;
    case "days":
    case "day":
        chronoUnit = ChronoUnit.DAYS;
        break;
    case "hours":
    case "hour":
        chronoUnit = ChronoUnit.HOURS;
        break;
    case "minutes":
    case "minute":
        chronoUnit = ChronoUnit.MINUTES;
        break;
    }
    return Date.from(Instant.now().plus(amount, chronoUnit));
}

From source file:io.kamax.mxisd.threepid.session.ThreePidSession.java

public synchronized void validate(String token) {
    if (Instant.now().minus(24, ChronoUnit.HOURS).isAfter(getCreationTime())) {
        throw new BadRequestException("Session " + getId() + " has expired");
    }//  w w w  .j  a v  a  2 s  .  c o m

    if (!StringUtils.equals(this.token, token)) {
        throw new InvalidCredentialsException();
    }

    if (isValidated()) {
        return;
    }

    validationTimestamp = Instant.now();
    isValidated = true;
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedPUTUriFromPath() throws IOException, InterruptedException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*from  w  w  w  . j a  v a  2 s  .  co  m*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "PUT", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    connection.setReadTimeout(3000);
    connection.setRequestMethod("PUT");
    connection.setDoOutput(true);
    connection.setChunkedStreamingMode(10);
    connection.connect();

    try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), UTF_8)) {
        out.write(TEST_DATA);
    } finally {
        connection.disconnect();
    }

    // Wait for file to become available
    for (int i = 0; i < 10; i++) {
        Thread.sleep(500);

        if (mantaClient.existsAndIsAccessible(path)) {
            break;
        }
    }

    String actual = mantaClient.getAsString(path);
    Assert.assertEquals(actual, TEST_DATA);
}

From source file:com.ikanow.aleph2.data_model.utils.TimeUtils.java

/** Returns the suffix of a time-based index given the grouping period
 * @param grouping_period - the grouping period
 * @param lowest_granularity//from   www  .  jav a2 s  .  c  o  m
 * @return the index suffix, ie added to the base index
 */
public static String getTimeBasedSuffix(final ChronoUnit grouping_period,
        final Optional<ChronoUnit> lowest_granularity) {
    return lowest_granularity
            .map(lg -> grouping_period.compareTo(lg) < 0 ? getTimeBasedSuffix(lg, Optional.empty()) : null)
            .orElse(Patterns.match(grouping_period).<String>andReturn()
                    .when(p -> ChronoUnit.SECONDS == p, __ -> "yyyy.MM.dd.HH:mm:ss")
                    .when(p -> ChronoUnit.MINUTES == p, __ -> "yyyy.MM.dd.HH:mm")
                    .when(p -> ChronoUnit.HOURS == p, __ -> "yyyy.MM.dd.HH")
                    .when(p -> ChronoUnit.DAYS == p, __ -> "yyyy.MM.dd")
                    .when(p -> ChronoUnit.WEEKS == p, __ -> "YYYY-ww") // (deliberately 'Y' (week-year) not 'y' since 'w' is week-of-year 
                    .when(p -> ChronoUnit.MONTHS == p, __ -> "yyyy.MM")
                    .when(p -> ChronoUnit.YEARS == p, __ -> "yyyy").otherwise(__ -> ""));
}

From source file:com.ikanow.aleph2.core.shared.utils.TimeSliceDirUtils.java

/** Low level util because java8 time "plus" is odd
 * @param to_adjust/*from ww w . j a  v  a 2  s .c o  m*/
 * @param increment
 * @return
 */
private static Date adjustTime(Date to_adjust, ChronoUnit increment) {
    return Patterns.match(increment).<Date>andReturn()
            .when(t -> t == ChronoUnit.SECONDS, __ -> DateUtils.addSeconds(to_adjust, 1))
            .when(t -> t == ChronoUnit.MINUTES, __ -> DateUtils.addMinutes(to_adjust, 1))
            .when(t -> t == ChronoUnit.HOURS, __ -> DateUtils.addHours(to_adjust, 1))
            .when(t -> t == ChronoUnit.DAYS, __ -> DateUtils.addDays(to_adjust, 1))
            .when(t -> t == ChronoUnit.WEEKS, __ -> DateUtils.addWeeks(to_adjust, 1))
            .when(t -> t == ChronoUnit.MONTHS, __ -> DateUtils.addMonths(to_adjust, 1))
            .when(t -> t == ChronoUnit.YEARS, __ -> DateUtils.addYears(to_adjust, 1)).otherwiseAssert();
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedOPTIONSUriFromPath() throws IOException, InterruptedException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/* ww w .  jav  a2  s .c o  m*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.put(path, TEST_DATA);

    // This will throw an error if the newly inserted object isn't present
    mantaClient.head(path);

    Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA);

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "OPTIONS", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    try {
        connection.setReadTimeout(3000);
        connection.setRequestMethod("OPTIONS");
        connection.connect();

        Map<String, List<String>> headers = connection.getHeaderFields();

        if (connection.getResponseCode() != 200) {
            String errorText = IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset());

            if (config.getMantaUser().contains("/")) {
                String msg = String.format("This fails due to an outstanding bug: MANTA-2839.\n%s", errorText);
                throw new SkipException(msg);
            }

            Assert.fail(errorText);
        }

        Assert.assertNotNull(headers);
        Assert.assertEquals(headers.get("Server").get(0), "Manta");
    } finally {
        connection.disconnect();
    }
}