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.openapis.example.manual.AbstractResource.java

@PUT
@Path("/{id}")
public T update(@PathParam("id") String id, T entity) {
    T existing = service.findOne(id);/*from   ww  w  . ja v a 2s  .  co  m*/

    if (existing != null) {
        entity.setId(id);

        if (entity instanceof Auditable) {
            LocalDateTime now = LocalDateTime.now();
            String user = getUserName();
            Auditable auditable = (Auditable) entity;
            Auditable from = (Auditable) existing;
            auditable.setCreatedBy(from.getCreatedBy());
            auditable.setCreatedDate(from.getCreatedDate());
            auditable.setModifiedBy(user);
            auditable.setModifiedDate(now);
        }

        return service.save(entity);
    } else {
        throw new NotFoundException();
    }
}

From source file:org.wallride.web.controller.admin.article.ArticlePreviewController.java

@RequestMapping
public void preview(@PathVariable String language, @Valid @ModelAttribute("form") ArticlePreviewForm form,
        BindingResult result, AuthorizedUser authorizedUser, Model model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Article article = new Article();
    article.setLanguage(language);//from   w  w  w . j  a v a2 s  . co m
    article.setCover(form.getCoverId() != null ? mediaService.getMedia(form.getCoverId()) : null);
    article.setTitle(form.getTitle());
    article.setBody(form.getBody());
    article.setDate(form.getDate() != null ? form.getDate() : LocalDateTime.now());

    List<CustomFieldValue> fieldValues = new ArrayList<>();
    for (CustomFieldValueEditForm valueForm : form.getCustomFieldValues()) {
        CustomFieldValue value = new CustomFieldValue();
        value.setCustomField(customFieldService.getCustomFieldById(valueForm.getCustomFieldId(), language));
        if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)
                && !ArrayUtils.isEmpty(valueForm.getTextValues())) {
            value.setTextValue(String.join(",", valueForm.getTextValues()));
        } else {
            value.setTextValue(valueForm.getTextValue());
        }
        value.setStringValue(valueForm.getStringValue());
        value.setNumberValue(valueForm.getNumberValue());
        value.setDateValue(valueForm.getDateValue());
        value.setDatetimeValue(valueForm.getDatetimeValue());
        fieldValues.add(value);
    }
    article.setCustomFieldValues(new TreeSet<>(fieldValues));
    article.setAuthor(authorizedUser);

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        throw new ServiceException("GuestServlet is not ready yet");
    }

    Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
    BlogLanguage blogLanguage = blog.getLanguage(language);
    request.setAttribute(BlogLanguageMethodArgumentResolver.BLOG_LANGUAGE_ATTRIBUTE, blogLanguage);

    DefaultModelAttributeInterceptor interceptor = context.getBean(DefaultModelAttributeInterceptor.class);
    ModelAndView mv = new ModelAndView("dummy");
    interceptor.postHandle(request, response, this, mv);

    final WebContext ctx = new WebContext(request, response, servletContext, LocaleContextHolder.getLocale(),
            mv.getModelMap());
    ctx.setVariable("article", article);

    ThymeleafEvaluationContext evaluationContext = new ThymeleafEvaluationContext(context, null);
    ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME,
            evaluationContext);

    SpringTemplateEngine templateEngine = context.getBean("templateEngine", SpringTemplateEngine.class);
    String html = templateEngine.process("article/describe", ctx);

    response.setContentType("text/html;charset=UTF-8");
    response.setContentLength(html.getBytes("UTF-8").length);
    response.getWriter().write(html);
}

From source file:ch.wisv.areafiftylan.utils.TaskScheduler.java

@Scheduled(fixedRate = USER_CLEANUP_CHECK_INTERVAL_MINUTES * 60 * 1000)
public void CleanUpUsers() {
    LocalDateTime now = LocalDateTime.now();
    List<VerificationToken> allExpiredVerificationTokens = verificationTokenRepository
            .findAllByExpiryDateBefore(now);
    allExpiredVerificationTokens.stream().filter(Token::isUnused).forEach(this::handleExpiredVerificationToken);
}

From source file:kitt.admin.service.UserService.java

/**
 * ?? -- /* w ww .  j a  v  a2  s  .c  om*/
 * @param company   ?
 * @param remarks   
 * @return          true or false
 */
@Transactional
public boolean doCompanyVerifyPassMethod(Company company, String remarks) {
    CompanyVerify companyVerify = companyMapper.getTheLatestCompanyVerifyByCompanyIdUserIdStatus(
            company.getId(), company.getUserid(), "");
    if (companyVerify != null) {
        String status = EnumCommonString.VerifyPass.value();
        int row1 = companyMapper.setCompVerify(status, session.getAdmin().getUsername(), LocalDateTime.now(),
                remarks, company.getId(), companyVerify.getId());
        int row2 = companyMapper.setCompanyStatus(status, remarks, company.getId());
        int row3 = userMapper.setUserVerifyStatus(status, LocalDateTime.now(), company.getUserid());
        int row4 = companyMapper.addCompVerSus(new CompVerSus(company.getName(), company.getAddress(),
                company.getPhone(), company.getFax(), company.getLegalperson(), company.getBusinesslicense(),
                company.getIdentificationnumber(), company.getOrganizationcode(), company.getOperatinglicense(),
                company.getUserid(), company.getLegalpersonname(), company.getAccount(),
                company.getOpeningbank()));
        if (row1 == 1 && row2 == 1 && row3 == 1 && row4 == 1) {
            String phone = userMapper.getUserById(company.getUserid()).getSecurephone();
            final String content = "??????";
            MessageNotice.CommonMessage.noticeUser(phone, content);
            //?
            mySupplyerService.auditSupplyer(phone);
            return true;
        }
    }
    throw new BusinessException("???");

}

From source file:cc.kave.commons.utils.exec.CompletionEventProcessor.java

private static void log(String msg, Object... args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    String date = LocalDateTime.now().format(formatter);
    System.out.printf("\n%s %s", date, String.format(msg, args));
}

From source file:fi.csc.emrex.smp.ThymeController.java

@RequestMapping(value = "/smp/", method = RequestMethod.GET)
public String smpsmp(HttpServletRequest request, Model model) throws Exception {
    String firstName = request.getHeader("shib-givenName");
    model.addAttribute("name", firstName);
    context.getSession().setAttribute("sessionStartTime", LocalDateTime.now());

    return "smp";
}

From source file:org.wallride.web.controller.admin.page.PagePreviewController.java

@RequestMapping
public void preview(@PathVariable String language, @Valid @ModelAttribute("form") PagePreviewForm form,
        BindingResult result, AuthorizedUser authorizedUser, Model model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Page page = new Page();
    page.setLanguage(language);//w w  w  .j  a v  a 2s . co  m
    page.setCover(form.getCoverId() != null ? mediaService.getMedia(form.getCoverId()) : null);
    page.setTitle(form.getTitle());
    page.setBody(form.getBody());
    page.setDate(form.getDate() != null ? form.getDate() : LocalDateTime.now());
    List<CustomFieldValue> fieldValues = new ArrayList<>();
    for (CustomFieldValueEditForm valueForm : form.getCustomFieldValues()) {
        CustomFieldValue value = new CustomFieldValue();
        value.setCustomField(customFieldService.getCustomFieldById(valueForm.getCustomFieldId(), language));
        if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)
                && !ArrayUtils.isEmpty(valueForm.getTextValues())) {
            value.setTextValue(String.join(",", valueForm.getTextValues()));
        } else {
            value.setTextValue(valueForm.getTextValue());
        }
        value.setStringValue(valueForm.getStringValue());
        value.setNumberValue(valueForm.getNumberValue());
        value.setDateValue(valueForm.getDateValue());
        value.setDatetimeValue(valueForm.getDatetimeValue());
        fieldValues.add(value);
    }
    page.setCustomFieldValues(new TreeSet<>(fieldValues));
    page.setAuthor(authorizedUser);

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        throw new ServiceException("GuestServlet is not ready yet");
    }

    Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
    BlogLanguage blogLanguage = blog.getLanguage(language);
    request.setAttribute(BlogLanguageMethodArgumentResolver.BLOG_LANGUAGE_ATTRIBUTE, blogLanguage);

    DefaultModelAttributeInterceptor interceptor = context.getBean(DefaultModelAttributeInterceptor.class);
    ModelAndView mv = new ModelAndView("dummy");
    interceptor.postHandle(request, response, this, mv);

    final WebContext ctx = new WebContext(request, response, servletContext, LocaleContextHolder.getLocale(),
            mv.getModelMap());
    ctx.setVariable("page", page);

    ThymeleafEvaluationContext evaluationContext = new ThymeleafEvaluationContext(context, null);
    ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME,
            evaluationContext);

    SpringTemplateEngine templateEngine = context.getBean("templateEngine", SpringTemplateEngine.class);
    String html = templateEngine.process("page/describe", ctx);

    response.setContentType("text/html;charset=UTF-8");
    response.setContentLength(html.getBytes("UTF-8").length);
    response.getWriter().write(html);
}

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

private void validateGeneralTab(CreditCardApplicationDTO creditCardApplicationDTO, Errors errors) {
    // Validate date of issue
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dob", ErrorCodes.FIELD_REQUIRED);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", ErrorCodes.FIELD_REQUIRED);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", ErrorCodes.FIELD_REQUIRED);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gender", ErrorCodes.FIELD_REQUIRED);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "typeOfID", ErrorCodes.FIELD_REQUIRED);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "passportNumber", ErrorCodes.FIELD_REQUIRED);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dateOfIssue", ErrorCodes.FIELD_REQUIRED);
    if (creditCardApplicationDTO.getCitizenship() != null
            && "+84".equals(creditCardApplicationDTO.getCitizenship().getCode())) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "placeOfIssue", ErrorCodes.FIELD_REQUIRED);
    }//  www  .  java  2s  . com
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "passportNumber", ErrorCodes.FIELD_REQUIRED);
    LocalDateTime dateOfIssue = creditCardApplicationDTO.getDateOfIssue();
    if (dateOfIssue != null) {
        if (dateOfIssue.isAfter(LocalDateTime.now())) {
            errors.rejectValue("dateOfIssue", ErrorCodes.FIELD_NOT_FUTURE);
        }
    }
    validateMobilephone(creditCardApplicationDTO, errors);
}

From source file:rmblworx.tools.timey.gui.AlarmIntegrationTest.java

/**
 * Testet/*from   ww  w.  j a  v a2 s  . c  o  m*/
 * <ol>
 * <li>Anlegen eines Alarms per GUI,</li>
 * <li>Senden des Ereignisses zum Auslsen des Alarms per Backend und</li>
 * <li>Reaktion der GUI auf das Ereignis.</li>
 * </ol>
 */
@Test
@Ignore("schlgt derzeit fehl") // TODO
public final void testCreateAlarmAndHandleEvent() {
    /*
     * Zeitdifferenz, die der Alarm in der Zukunft ausgelst werden soll.
     * Wert mglichst klein halten, um Test nich unntig lange dauern zu lassen, aber dennoch gro genug, um sicherzustellen, dass
     * Alarm bis zu diesem Zeitpunkt vollstndig angelegt werden kann.
     */
    final int bufferInSeconds = 2;

    final String alarmDescription = "relevanter Alarm";

    final AlarmController controller = (AlarmController) getController();
    final GuiHelper guiHelper = controller.getGuiHelper();
    final ITimey facade = guiHelper.getFacade();

    // zwei unwichtige Alarme per Fassade hinzufgen
    final LocalDateTime now = LocalDateTime.now().withNano(0);
    facade.setAlarm(AlarmDescriptorConverter
            .getAsAlarmDescriptor(new Alarm(now.minusYears(1), "alter Alarm", "", false)));
    facade.setAlarm(
            AlarmDescriptorConverter.getAsAlarmDescriptor(new Alarm(now.plusYears(1), "Zukunftsalarm")));

    // relevanten Alarm per GUI hinzufgen
    final Button alarmAddButton = (Button) stage.getScene().lookup("#alarmAddButton");
    click(alarmAddButton);
    waitForThreads();

    final Scene dialogScene = controller.getDialogStage().getScene();
    final TimePicker alarmTimePicker = (TimePicker) dialogScene.lookup("#alarmTimePicker");
    final TextField alarmDescriptionTextField = (TextField) dialogScene.lookup("#alarmDescriptionTextField");
    final Button alarmSaveButton = (Button) dialogScene.lookup("#alarmSaveButton");

    Platform.runLater(new Runnable() {
        public void run() {
            alarmTimePicker.setValue(alarmTimePicker.getValue().plusSeconds(bufferInSeconds));
            alarmDescriptionTextField.setText(alarmDescription);
        }
    });
    FXTestUtils.awaitEvents();

    final MessageHelper messageHelper = mock(MessageHelper.class);
    guiHelper.setMessageHelper(messageHelper);

    // Speichern-Schaltflche bettigen
    click(alarmSaveButton);
    waitForThreads();

    // sicherstellen, dass Ereignis genau einmal fr den korrekten Alarm eintritt und verarbeitet wird
    verify(messageHelper, timeout(WAIT_FOR_EVENT)).showTrayMessageWithFallbackToDialog(anyString(),
            eq(alarmDescription), isNull(TrayIcon.class), isA(ResourceBundle.class));
}

From source file:com.fns.grivet.service.EntityServiceTest.java

@Test
public void testCreateThenFindByTypeVariant() throws IOException {
    registerType("TestType2");
    Resource r = resolver.getResource("classpath:TestTypeData2.json");
    String json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
    JSONObject payload = new JSONObject(json);

    entityService.create("TestType2", payload);

    String result = entityService.findByCreatedTime("TestType2", LocalDateTime.now().minusSeconds(3),
            LocalDateTime.now(), null);
    JSONArray resultAsJsonArray = new JSONArray(result);
    JsonAssert.assertJsonEquals(payload.toString(), resultAsJsonArray.get(0).toString());
}