Example usage for java.time LocalDateTime now

List of usage examples for java.time LocalDateTime now

Introduction

In this page you can find the example usage for java.time LocalDateTime now.

Prototype

public static LocalDateTime now() 

Source Link

Document

Obtains the current date-time from the system clock in the default time-zone.

Usage

From source file:org.apache.metron.parsers.syslog.BaseSyslogParser.java

@SuppressWarnings("unchecked")
private void setTimestamp(JSONObject message) throws ParseException {
    String timeStampString = (String) message.get(SyslogFieldKeys.HEADER_TIMESTAMP.getField());
    if (!StringUtils.isBlank(timeStampString) && !timeStampString.equals("-")) {
        message.put("timestamp", SyslogUtils.parseTimestampToEpochMillis(timeStampString, deviceClock));
    } else {// ww w. j a  v a 2  s. co  m
        message.put("timestamp", LocalDateTime.now().toEpochSecond(ZoneOffset.UTC));
    }
}

From source file:com.swcguild.capstoneproject.dao.BlogDaoDbImplTest.java

/**
 * Test of getAllPostObjects method, of class BlogDaoDbImpl.
 *//* ww  w  .  j  a v a2s.  c om*/
@Test
public void testGetAllPostObjects() {
    System.out.println("getAllPostObjects");
    Post post1 = new Post("Supergirl", "Clark Kent", "hot new cousin saves city", "super, girl",
            LocalDateTime.now().toString(), "2015-12-20");
    Post post2 = new Post("Super", "Kent", "cousin saves city", "super", LocalDateTime.now().toString(),
            "2015-12-20");
    Post post3 = new Post("girl", "Clar", "new cousin saves city", "girl", LocalDateTime.now().toString(),
            "2015-12-20");
    post1.setStatus(1);
    post2.setStatus(1);
    post3.setStatus(1);
    dao.addPost(post1);
    dao.addPost(post2);
    dao.addPost(post3);
    List<Post> expResult = new ArrayList();
    expResult.add(post1);
    expResult.add(post2);
    expResult.add(post3);
    List<Post> result = dao.getAllPostObjects();
    assertEquals(expResult.size(), result.size());
}

From source file:ch.wisv.areafiftylan.integration.TicketRestIntegrationTest.java

@Test
public void testRemoveTicketType() {
    User admin = createAdmin();// w  w w . j  a  v a  2 s .  c o m
    TicketType type = new TicketType("testRemoveType", "Type for remove test", 10, 0,
            LocalDateTime.now().plusDays(1), false);
    type = ticketService.addTicketType(type);
    //@formatter:off
    given().header(getXAuthTokenHeaderForUser(admin)).when().delete(TICKETS_ENDPOINT + "/types/" + type.getId())
            .then().statusCode(HttpStatus.SC_OK);
    //@formatter:on

    assertThat(ticketService.getAllTicketTypes()).doesNotContain(type);
}

From source file:cz.muni.fi.editor.services.api.requests.RequestServiceImpl.java

@TransactionalEventListener
@Async//from ww  w.  j a  v a  2  s .  c  o m
@Transactional
public void createOrganization(EOrganizationCreate organizationCreatedEvent) {
    Request request = new Request();
    request.setAction("create");
    request.setTargetId(organizationCreatedEvent.getOrganizationDTO().getId());
    request.setClazz(OrganizationDTO.class.getName());
    request.setState(RequestState.PENDING);
    request.setRequestDate(LocalDateTime.now());
    request.setRequestor(mapper.map(organizationCreatedEvent.getActor(), User.class));

    requestDAO.create(request);

    applicationEventPublisher
            .publishEvent(new ERequestCreated(this, organizationCreatedEvent.getActor(), request));
}

From source file:com.ccserver.digital.validator.CreditCardApplicationValidator.java

private void validateEmploymentTab(CreditCardApplicationDTO creditCardApplicationDTO, Errors errors) {
    if (creditCardApplicationDTO.getTypeOfEmployement() == TypeOfEmployment.Business) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "licenseNumber", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "businessStartDate", ErrorCodes.FIELD_REQUIRED);
        if (creditCardApplicationDTO.getBusinessStartDate() != null) {
            if (creditCardApplicationDTO.getBusinessStartDate().isAfter(LocalDateTime.now())) {
                errors.rejectValue("businessStartDate", ErrorCodes.FIELD_NOT_FUTURE);
            }/*from  w  w w. ja  v  a 2s. co  m*/
        }
        ValidationUtils.rejectIfEmpty(errors, "businessPhone", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "businessAddress", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "companyName", ErrorCodes.FIELD_REQUIRED);

    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "nameOfEmployer", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "occupation", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "industry", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "employerAddress", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "businessTelephone", ErrorCodes.FIELD_REQUIRED);

        if ((creditCardApplicationDTO.getMonthsOfWorking() == null
                || creditCardApplicationDTO.getMonthsOfWorking() == 0)
                && (creditCardApplicationDTO.getYearsOfWorking() == null
                        || creditCardApplicationDTO.getYearsOfWorking() == 0)) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "monthsOfWorking", ErrorCodes.FIELD_REQUIRED);
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "yearsOfWorking", ErrorCodes.FIELD_REQUIRED);
        }
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "monthlyIncome", ErrorCodes.FIELD_REQUIRED);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "monthlyExpenses", ErrorCodes.FIELD_REQUIRED);

    if (creditCardApplicationDTO.getMonthlyExpenses() != null && creditCardApplicationDTO.getMonthlyExpenses()
            .compareTo(creditCardApplicationDTO.getMonthlyIncome()) > 0) {
        errors.rejectValue("monthlyExpenses", ErrorCodes.FIELD_INVALID);
    }
}

From source file:eu.crydee.alignment.aligner.ae.MetricsOneVsOneC.java

@Override
public void collectionProcessComplete() throws AnalysisEngineProcessException {
    try {/*from www .  ja  v a2  s .com*/
        String template = IOUtils.toString(getClass()
                .getResourceAsStream("/eu/crydee/alignment/aligner/ae/" + "metrics-one-vs-one-template.html"));
        template = template.replace("@@TITLE@@",
                "Metrics comparator" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        template = template.replace("@@LEFTALGO@@", leftAlgoName);
        template = template.replace("@@RIGHTALGO@@", rightAlgoName);
        StringBuilder sb = new StringBuilder();
        sb.append("<table class=\"table table-condensed\">\n").append("            <thead>\n")
                .append("                <tr>\n").append("                    <th>Document\\Metric</th>\n");
        for (String key : keys) {
            sb.append("                    <th colspan=\"2\">").append(methodsMetadata.get(key).getRight())
                    .append("</th>\n");
        }
        sb.append("                <tr>\n").append("            </thead>\n").append("            <tbody>\n")
                .append("                <tr>\n").append("                    <td>\n")
                .append("                        <strong>Total</strong>\n")
                .append("                    </td>\n");
        for (String key : keys) {
            SummaryStatistics ss1 = new SummaryStatistics(), ss2 = new SummaryStatistics();
            List<Pair<Double, Double>> column = results.column(key).values().stream().peek(p -> {
                ss1.addValue(p.getLeft());
                ss2.addValue(p.getRight());
            }).collect(Collectors.toList());
            boolean significant = TestUtils.pairedTTest(column.stream().mapToDouble(p -> p.getLeft()).toArray(),
                    column.stream().mapToDouble(p -> p.getRight()).toArray(), 0.05);
            double mean1 = ss1.getMean(), mean2 = ss2.getMean();
            boolean above = mean1 > mean2;
            String summary1 = String.format("%.3f", mean1) + "<small class=\"text-muted\">" + ""
                    + String.format("%.3f", ss1.getStandardDeviation()) + "</small>",
                    summary2 = String.format("%.3f", mean2) + "<small class=\"text-muted\">" + ""
                            + String.format("%.3f", ss2.getStandardDeviation()) + "</small>";
            sb.append("                    <td class=\"")
                    .append(significant ? (above ? "success" : "danger") : "warning").append("\">")
                    .append(summary1).append("</td>\n");
            sb.append("                    <td class=\"")
                    .append(significant ? (!above ? "success" : "danger") : "warning").append("\">")
                    .append(summary2).append("</td>\n");
        }
        sb.append("                </tr>\n");
        SortedSet<String> rows = new TreeSet<>(results.rowKeySet());
        for (String row : rows) {
            sb.append("                <tr>\n").append("                    <td>").append(row)
                    .append("</td>\n");
            for (String key : keys) {
                Pair<Double, Double> r = results.get(row, key);
                sb.append("                    <td>").append(String.format("%.3f", r.getLeft()))
                        .append("</td>\n").append("                    <td>")
                        .append(String.format("%.3f", r.getRight())).append("</td>\n");

            }
            sb.append("                </tr>\n");
        }
        sb.append("            </tbody>\n").append("        </table>");
        FileUtils.write(new File(htmlFilepath), template.replace("@@TABLE@@", sb.toString()),
                StandardCharsets.UTF_8);
    } catch (IOException ex) {
        logger.error("IO problem with the HTML output.");
        throw new AnalysisEngineProcessException(ex);
    }
}

From source file:com.match_tracker.twitter.TwitterSearch.java

protected boolean isLongRunningSearch(LocalDateTime lastLogTime) {
    LocalDateTime oneMinuteAgo = LocalDateTime.now().minusSeconds(LONG_SEARCH_THRESHOLD_SECONDS);
    return oneMinuteAgo.isAfter(lastLogTime);
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.stylesheet.StylesheetValidationTest.java

private void saveData(String xml, byte[] pdf, Class<? extends S2SFormGenerator> clazz) {
    final String printLogging = System.getProperty(ConfigurationConstants.PRINT_LOGGING_ENABLE);
    final String printPdfLogging = System.getProperty(ConfigurationConstants.PRINT_PDF_LOGGING_ENABLE);
    final String printDirectory = System.getProperty(ConfigurationConstants.PRINT_LOGGING_DIRECTORY);

    if (StringUtils.isNotBlank(printDirectory)) {
        try {// w  w  w. j  a  v  a  2s  .  co  m
            if ("true".equalsIgnoreCase(printLogging)) {
                File xmlFile = new File(new File(printDirectory),
                        clazz.getSimpleName() + LocalDateTime.now().toString() + ".xml");
                FileUtils.write(xmlFile, xml);
            }

            if ("true".equalsIgnoreCase(printPdfLogging) && pdf != null) {
                File pdfFile = new File(new File(printDirectory),
                        clazz.getSimpleName() + LocalDateTime.now().toString() + ".pdf");
                FileUtils.writeByteArrayToFile(pdfFile, pdf);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.ambraproject.rhino.rest.controller.ArticleCrudController.java

/**
 * Calculate the date range using the specified rule. For example:
 *
 * <ul>/*from  w ww.  j av a 2 s .  c o  m*/
 * <li>sinceRule=2y  - 2 years</li>
 * <li>sinceRule=5m  - 5 months</li>
 * <li>sinceRule=10d - 10 days</li>
 * <li>sinceRule=5h  - 5 hours</li>
 * <li>sinceRule=33  - 33 minutes</li>
 * </ul>
 *
 * The method will result in a {@link java.util.Map Map} containing the following keys:
 *
 * <ul>
 * <li><b>fromDate</b> - the starting date
 * <li><b>toDate</b> - the ending date, which will be the current system date (i.e. now())
 * </ul>
 *
 * @param sinceRule The rule to calculate the date range
 *
 * @return A {@link java.util.Map Map}
 */
public static final Map<String, LocalDateTime> calculateDateRange(String sinceRule) {
    if (StringUtils.isBlank(sinceRule)) {
        return ImmutableMap.of();
    }

    final String timeDesignation = StringUtils.right(sinceRule, 1);
    long timeDelta = 0;
    try {
        // Assume last character is NOT a letter (i.e. all characters are digits).
        timeDelta = Long.parseLong(sinceRule);
    } catch (NumberFormatException exception) {
        // If an exception, then last character MUST have been a letter,
        // so we now exclude the last character and re-try conversion.
        try {
            timeDelta = Long.parseLong(sinceRule.substring(0, sinceRule.length() - 1));
        } catch (NumberFormatException error) {
            log.warn("Failed to convert {} to a timeDelta/timeDesignation!", sinceRule);
            timeDelta = 0;
        }
    }

    if (timeDelta < 1) {
        return ImmutableMap.of();
    }

    final LocalDateTime toDate = LocalDateTime.now();
    final LocalDateTime fromDate;
    if (timeDesignation.equalsIgnoreCase("y")) {
        fromDate = toDate.minusYears(timeDelta);
    } else if (timeDesignation.equalsIgnoreCase("m")) {
        fromDate = toDate.minusMonths(timeDelta);
    } else if (timeDesignation.equalsIgnoreCase("d")) {
        fromDate = toDate.minusDays(timeDelta);
    } else if (timeDesignation.equalsIgnoreCase("h")) {
        fromDate = toDate.minus(timeDelta, ChronoUnit.HOURS);
    } else {
        fromDate = toDate.minus(timeDelta, ChronoUnit.MINUTES);
    }

    final ImmutableMap<String, LocalDateTime> dateRange = ImmutableMap.of(FROM_DATE, fromDate, TO_DATE, toDate);
    return dateRange;
}

From source file:com.caricah.iotracah.datastore.ignitecache.internal.AbstractHandler.java

public void initializeSequence(String nameOfSequence, Ignite ignite) {

    long currentTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
    IgniteAtomicSequence idSequence = ignite.atomicSequence(nameOfSequence, currentTime, true);
    setIdSequence(idSequence);// w ww .  ja va 2s. c  o m
}