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:alfio.test.util.IntegrationTestUtil.java

public static Pair<Event, String> initEvent(List<TicketCategoryModification> categories,
        OrganizationRepository organizationRepository, UserManager userManager, EventManager eventManager,
        EventRepository eventRepository) {

    String organizationName = UUID.randomUUID().toString();
    String username = UUID.randomUUID().toString();
    String eventName = UUID.randomUUID().toString();

    userManager.createOrganization(organizationName, "org", "email@example.com");
    Organization organization = organizationRepository.findByName(organizationName).get();
    userManager.insertUser(organization.getId(), username, "test", "test", "test@example.com", Role.OPERATOR,
            User.Type.INTERNAL);
    userManager.insertUser(organization.getId(), username + "_owner", "test", "test", "test@example.com",
            Role.OWNER, User.Type.INTERNAL);

    LocalDateTime expiration = LocalDateTime.now().plusDays(5).plusHours(1);

    Map<String, String> desc = new HashMap<>();
    desc.put("en", "muh description");
    desc.put("it", "muh description");
    desc.put("de", "muh description");

    EventModification em = new EventModification(null, Event.EventType.INTERNAL, "url", "url", "url", "url",
            null, eventName, "event display name", organization.getId(), "muh location", "0.0", "0.0",
            ZoneId.systemDefault().getId(), desc,
            new DateTimeModification(LocalDate.now().plusDays(5), LocalTime.now()),
            new DateTimeModification(expiration.toLocalDate(), expiration.toLocalTime()), BigDecimal.TEN, "CHF",
            AVAILABLE_SEATS, BigDecimal.ONE, true, Collections.singletonList(PaymentProxy.OFFLINE), categories,
            false, new LocationDescriptor("", "", "", ""), 7, null, null);
    eventManager.createEvent(em);//from  w  w w.ja va 2  s. c o  m
    Event event = eventManager.getSingleEvent(eventName, username);
    Assert.assertEquals(AVAILABLE_SEATS, eventRepository.countExistingTickets(event.getId()).intValue());
    return Pair.of(event, username);
}

From source file:kitt.site.controller.CompanyController.java

@RequestMapping(value = "/account/saveCompany", method = RequestMethod.POST)
@ResponseBody//from   w  w w .ja  v a2  s .c om
public Object saveCompany(Company company, @CurrentUser User user) throws Exception {
    BeanValidators.validateWithException(company);
    boolean result = false;
    if (!"".equals(userMapper.getUserById(session.getUser().getId()).getVerifystatus())) {
        //temp,?upload
        fileStore.copyFileToUploadDir(company.getBusinesslicense());
        fileStore.copyFileToUploadDir(company.getIdentificationnumber());
        fileStore.copyFileToUploadDir(company.getOrganizationcode());
        fileStore.copyFileToUploadDir(company.getOpeninglicense());
        if (!StringUtils.isBlank(company.getOperatinglicense())) {
            fileStore.copyFileToUploadDir(company.getOperatinglicense());
            company.setOperatinglicense(company.getOperatinglicense().replace("temp", "upload"));
        }

        fileStore.copyFileToUploadDir(company.getOpeninglicense());
        if (!StringUtils.isBlank(company.getInvoicinginformation())) {
            fileStore.copyFileToUploadDir(company.getInvoicinginformation());
            company.setInvoicinginformation(company.getInvoicinginformation().replace("temp", "upload"));
        }

        company.setBusinesslicense(company.getBusinesslicense().replace("temp", "upload"));
        company.setIdentificationnumber(company.getIdentificationnumber().replace("temp", "upload"));
        company.setOrganizationcode(company.getOrganizationcode().replace("temp", "upload"));
        company.setOpeninglicense(company.getOpeninglicense().replace("temp", "upload"));
        company.setUserid(session.getUser().getId());

        if (companyMapper.countCompany(session.getUser().getId()) == 0) {
            companyMapper.addCompany(company);
        } else {
            companyMapper.modifyCompany(company);
        }
        companyMapper.addCompVerify(new CompanyVerify("", LocalDateTime.now(),
                companyMapper.getIdByUserid(session.getUser().getId()), session.getUser().getId()));
        companyMapper.setCompanyStatus("", null,
                companyMapper.getIdByUserid(session.getUser().getId()));
        userMapper.setUserVerifyStatus("", null, session.getUser().getId());
        result = true;
        MessageNotice.SubmitCompany.noticeUser(user.getSecurephone());
    }
    return result;
}

From source file:org.wallride.service.PageService.java

@CacheEvict(value = WallRideCacheConfiguration.PAGE_CACHE, allEntries = true)
public Page createPage(PageCreateRequest request, Post.Status status, AuthorizedUser authorizedUser) {
    LocalDateTime now = LocalDateTime.now();

    String code = request.getCode();
    if (code == null) {
        try {/*from  w  w  w. jav  a2 s.  c o m*/
            code = new CodeFormatter().parse(request.getTitle(), LocaleContextHolder.getLocale());
        } catch (ParseException e) {
            throw new ServiceException(e);
        }
    }
    if (!StringUtils.hasText(code)) {
        if (!status.equals(Post.Status.DRAFT)) {
            throw new EmptyCodeException();
        }
    }

    if (!status.equals(Post.Status.DRAFT)) {
        Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage());
        if (duplicate != null) {
            throw new DuplicateCodeException(code);
        }
    }

    Page page = new Page();

    if (!status.equals(Post.Status.DRAFT)) {
        page.setCode(code);
        page.setDraftedCode(null);
    } else {
        page.setCode(null);
        page.setDraftedCode(code);
    }

    Page parent = (request.getParentId() != null)
            ? pageRepository.findOneByIdAndLanguage(request.getParentId(), request.getLanguage())
            : null;
    int rgt = 0;
    if (parent == null) {
        rgt = pageRepository.findMaxRgt();
        rgt++;
    } else {
        rgt = parent.getRgt();
        pageRepository.unshiftRgt(rgt);
        pageRepository.unshiftLft(rgt);
    }

    page.setParent(parent);

    Media cover = null;
    if (request.getCoverId() != null) {
        cover = entityManager.getReference(Media.class, request.getCoverId());
    }
    page.setCover(cover);
    page.setTitle(request.getTitle());
    page.setBody(request.getBody());

    page.setAuthor(entityManager.getReference(User.class, authorizedUser.getId()));

    LocalDateTime date = request.getDate();
    if (Post.Status.PUBLISHED.equals(status)) {
        if (date == null) {
            date = now;
        } else if (date.isAfter(now)) {
            status = Post.Status.SCHEDULED;
        }
    }
    page.setDate(date);
    page.setStatus(status);
    page.setLanguage(request.getLanguage());

    page.getCategories().clear();
    SortedSet<Category> categories = new TreeSet<>();
    for (long categoryId : request.getCategoryIds()) {
        categories.add(entityManager.getReference(Category.class, categoryId));
    }
    page.setCategories(categories);

    page.getTags().clear();
    Set<String> tagNames = StringUtils.commaDelimitedListToSet(request.getTags());
    if (!CollectionUtils.isEmpty(tagNames)) {
        for (String tagName : tagNames) {
            Tag tag = tagRepository.findOneForUpdateByNameAndLanguage(tagName, request.getLanguage());
            if (tag == null) {
                tag = new Tag();
                tag.setName(tagName);
                tag.setLanguage(request.getLanguage());
                page.setCreatedAt(now);
                page.setCreatedBy(authorizedUser.toString());
                page.setUpdatedAt(now);
                page.setUpdatedBy(authorizedUser.toString());
                tag = tagRepository.saveAndFlush(tag);
            }
            page.getTags().add(tag);
        }
    }

    page.getRelatedPosts().clear();
    Set<Post> relatedPosts = new HashSet<>();
    for (long relatedId : request.getRelatedPostIds()) {
        relatedPosts.add(entityManager.getReference(Post.class, relatedId));
    }
    page.setRelatedToPosts(relatedPosts);

    Seo seo = new Seo();
    seo.setTitle(request.getSeoTitle());
    seo.setDescription(request.getSeoDescription());
    seo.setKeywords(request.getSeoKeywords());
    page.setSeo(seo);

    page.setLft(rgt);
    page.setRgt(rgt + 1);

    List<Media> medias = new ArrayList<>();
    if (StringUtils.hasText(request.getBody())) {
        //         Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
        String mediaUrlPrefix = wallRideProperties.getMediaUrlPrefix();
        Pattern mediaUrlPattern = Pattern.compile(String.format("%s([0-9a-zA-Z\\-]+)", mediaUrlPrefix));
        Matcher mediaUrlMatcher = mediaUrlPattern.matcher(request.getBody());
        while (mediaUrlMatcher.find()) {
            Media media = mediaRepository.findOneById(mediaUrlMatcher.group(1));
            medias.add(media);
        }
    }
    page.setMedias(medias);

    page.setCreatedAt(now);
    page.setCreatedBy(authorizedUser.toString());
    page.setUpdatedAt(now);
    page.setUpdatedBy(authorizedUser.toString());

    page.getCustomFieldValues().clear();
    if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) {
        for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) {
            CustomFieldValue value = new CustomFieldValue();
            value.setCustomField(entityManager.getReference(CustomField.class, valueForm.getCustomFieldId()));
            value.setPost(page);
            if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)) {
                if (!ArrayUtils.isEmpty(valueForm.getTextValues())) {
                    value.setTextValue(String.join(",", valueForm.getTextValues()));
                } else {
                    value.setTextValue(null);
                }
            } else {
                value.setTextValue(valueForm.getTextValue());
            }
            value.setStringValue(valueForm.getStringValue());
            value.setNumberValue(valueForm.getNumberValue());
            value.setDateValue(valueForm.getDateValue());
            value.setDatetimeValue(valueForm.getDatetimeValue());
            if (!value.isEmpty()) {
                page.getCustomFieldValues().add(value);
            }
        }
    }

    return pageRepository.save(page);
}

From source file:org.wallride.web.controller.guest.user.PasswordResetController.java

@RequestMapping(value = "/{token}", method = RequestMethod.GET)
public String edit(@PathVariable String token, RedirectAttributes redirectAttributes) {
    PasswordResetToken passwordResetToken = userService.getPasswordResetToken(token);
    if (passwordResetToken == null) {
        redirectAttributes.addFlashAttribute(INVALID_PASSOWRD_RESET_LINK_ATTR_NAME, true);
        return "redirect:/password-reset";
    }/*  w  w w.  j  av a 2 s  .  c o m*/
    LocalDateTime now = LocalDateTime.now();
    if (now.isAfter(passwordResetToken.getExpiredAt())) {
        redirectAttributes.addFlashAttribute(INVALID_PASSOWRD_RESET_LINK_ATTR_NAME, true);
        return "redirect:/password-reset";
    }

    return "user/password-reset3-reset";
}

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

/**
 * Test of removePost method, of class BlogDaoDbImpl.
 *//*from w w  w  . ja  v a 2s  . co m*/
@Test
public void testRemovePost() {
    System.out.println("removePost");
    Post post1 = new Post("Supergirl", "Clark Kent", "hot new cousin saves city", "super, girl",
            LocalDateTime.now().toString(), "2015-12-30");
    Post post2 = new Post("Supeergirl", "Clark Kentd", "hot5 new cousin saves city", "super, girl",
            LocalDateTime.now().toString(), "2015-12-30");
    Post post3 = new Post("Superfgirl", "Clark Kentd", "hot 4new cousin saves city", "super, girl",
            LocalDateTime.now().toString(), "2015-12-30");

    dao.addPost(post1);
    //    System.out.println(post1.getPostID());
    dao.addPost(post2);
    //   System.out.println(post2.getPostID());
    dao.addPost(post3);
    //    System.out.println(post3.getPostID());
    dao.removePost(post2.getPostID());
    assertEquals(2, dao.getAllPosts().size());
}

From source file:com.seleniumtests.uipage.htmlelements.GenericPictureElement.java

/**
 * Search the picture in the screenshot taken by Robot or WebDriver
 * Robot is used in Desktop mode/* www.ja v a  2  s  .c o  m*/
 * WebDriver is used in mobile, because Robot is not available for mobile platforms
 * 
 */
public void findElement() {

    LocalDateTime start = LocalDateTime.now();

    File screenshotFile = getScreenshotFile();

    if (screenshotFile == null) {
        throw new WebDriverException("Screenshot does not exist");
    }

    // for desktop search, without reference image, do not search
    if (detector != null) {
        detector.setSceneImage(screenshotFile);
        detector.detectExactZoneWithScale();
        detectedObjectRectangle = detector.getDetectedRectangle();
        pictureSizeRatio = detector.getSizeRatio();
    } else {
        detectedObjectRectangle = new Rectangle(0, 0, 0, 0);
        pictureSizeRatio = 1.0;
    }
    actionDuration = Duration.between(start, LocalDateTime.now()).toMillis();

    doAfterPictureSearch();
}

From source file:org.teknux.dropbitz.controller.UploadController.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_HTML })
@Authenticated/*from   ww  w .ja v a  2s  . c  o m*/
public Response uploadFile(@FormDataParam("file") final InputStream inputStream,
        @FormDataParam("file") final FormDataContentDisposition formDataContentDisposition,
        @FormDataParam("name") final String name, @FormDataParam("email") final String email,
        @FormDataParam("fallback") final Boolean fallback) {

    String fileName = null;
    try {
        fileName = new String(formDataContentDisposition.getFileName().getBytes(CHARSET_ISO_8859_1),
                CHARSET_UTF8);
    } catch (UnsupportedEncodingException e) {
        logger.warn("Can not translate file name charset", e);
        fileName = formDataContentDisposition.getFileName();
    }
    ;

    logger.trace("Checking email");
    if (!email.isEmpty()) {
        //validate email
        if (!EmailValidator.getInstance().isValid(email)) {
            return getResponse(fallback, Status.INTERNAL_SERVER_ERROR, fileName,
                    i18n(I18nKey.DROP_FILE_EMAIL_ERROR));
        }
    }

    String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(DATE_FORMAT));
    String destFileName = date + (name.isEmpty() ? "" : "-" + name) + "-" + fileName;

    try {
        if (formDataContentDisposition.getFileName().isEmpty()) {
            return getResponse(fallback, Status.BAD_REQUEST, fileName, i18n(I18nKey.DROP_FILE_MISSING));
        }
        Configuration config = getServiceManager().getService(IConfigurationService.class).getConfiguration();
        java.nio.file.Path outputPath = FileSystems.getDefault()
                .getPath(config.getDirectory().getAbsolutePath(), destFileName);

        //Checks destination directory
        if (!FileUtil.isChildOfDirectory(outputPath.toFile(), config.getDirectory())) {
            return getResponse(fallback, Status.FORBIDDEN, fileName, i18n(I18nKey.DROP_FILE_MISSING));
        }

        Files.copy(inputStream, outputPath);

        long fileSize = outputPath.toFile().length();
        sendEmail(true, name, fileName, destFileName, fileSize, email);
    } catch (IOException e) {
        logger.error("Can not copy file", e);

        sendEmail(false, name, fileName, null, 0L, email);
        return getResponse(fallback, Status.INTERNAL_SERVER_ERROR, fileName, i18n(I18nKey.DROP_FILE_ERROR));
    }

    return getResponse(fallback, Status.OK, fileName, null);
}

From source file:com.romeikat.datamessie.core.base.task.scheduling.IntervalTaskSchedulingThreadTest.java

private void run(final int taskExecutionInterval, final long taskExecutionDuration, final boolean allowOverlap,
        final boolean throwException) throws Exception {

    final MutableInt numberOfTaskExecutions = new MutableInt(0);
    final MutableInt numberOfTaskTriggerings = new MutableInt(0);
    final Task task = Mockito.spy(new FooTask() {
        @Override/*from  w  w w  .j a v  a 2 s .  co  m*/
        public void execute(final TaskExecution taskExecution) throws Exception {
            if (throwException) {
                throw new Exception();
            }
            numberOfTaskExecutions.add(1);
            Thread.sleep(taskExecutionDuration);
        }
    });
    final String taskName = task.getName();

    // Schedule task for multiple execution
    final MutableObject<LocalDateTime> startOfLatestCompletedTask = new MutableObject<LocalDateTime>();
    final FooIntervalTaskSchedulingThread intervalTaskSchedulingThread = new FooIntervalTaskSchedulingThread(
            task, taskName, taskExecutionInterval, allowOverlap, taskManager) {
        @Override
        protected boolean shouldStopTaskExecution() {
            return numberOfTaskTriggerings.intValue() == NUMBER_OF_TASK_EXECUTIONS;
        }

        @Override
        protected void onAfterTriggeringTask(final TaskExecution latestTaskExecution) {
            startOfLatestCompletedTask.setValue(LocalDateTime.now());
            numberOfTaskTriggerings.add(1);
        }

        @Override
        protected LocalDateTime getActualStartOfLatestCompletedTask() {
            return startOfLatestCompletedTask.getValue();
        }
    };
    intervalTaskSchedulingThread.start();

    // Wait until all executions are finished
    final long additionalWaiting = TaskManager.DEFAULT_MANAGEMENT_INTERVAL + 1000;
    final long timePerTaskExecution = throwException ? taskExecutionInterval
            : taskExecutionInterval + taskExecutionDuration;
    final long waitUntilTaskExecutionShouldBeFinished = NUMBER_OF_TASK_EXECUTIONS * timePerTaskExecution
            + additionalWaiting;
    Thread.sleep(waitUntilTaskExecutionShouldBeFinished);

    // Check executions
    final int expectedNumberOfTaskTriggerings = NUMBER_OF_TASK_EXECUTIONS;
    assertEquals(expectedNumberOfTaskTriggerings, numberOfTaskTriggerings.intValue());
    final int expectedNumbeOfTaskExecutions = throwException ? 0 : NUMBER_OF_TASK_EXECUTIONS;
    assertEquals(expectedNumbeOfTaskExecutions, numberOfTaskExecutions.intValue());
}

From source file:org.wallride.service.ArticleService.java

@CacheEvict(value = WallRideCacheConfiguration.ARTICLE_CACHE, allEntries = true)
public Article createArticle(ArticleCreateRequest request, Post.Status status, AuthorizedUser authorizedUser) {
    LocalDateTime now = LocalDateTime.now();

    String code = request.getCode();
    if (code == null) {
        try {/*  ww  w . ja  v  a  2s  .c o m*/
            code = new CodeFormatter().parse(request.getTitle(), LocaleContextHolder.getLocale());
        } catch (ParseException e) {
            throw new ServiceException(e);
        }
    }
    if (!StringUtils.hasText(code)) {
        if (!status.equals(Post.Status.DRAFT)) {
            throw new EmptyCodeException();
        }
    }

    if (!status.equals(Post.Status.DRAFT)) {
        Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage());
        if (duplicate != null) {
            throw new DuplicateCodeException(code);
        }
    }

    Article article = new Article();

    if (!status.equals(Post.Status.DRAFT)) {
        article.setCode(code);
        article.setDraftedCode(null);
    } else {
        article.setCode(null);
        article.setDraftedCode(code);
    }

    Media cover = null;
    if (request.getCoverId() != null) {
        cover = entityManager.getReference(Media.class, request.getCoverId());
    }
    article.setCover(cover);
    article.setTitle(request.getTitle());
    article.setBody(request.getBody());

    article.setAuthor(entityManager.getReference(User.class, authorizedUser.getId()));

    LocalDateTime date = request.getDate();
    if (Post.Status.PUBLISHED.equals(status)) {
        if (date == null) {
            date = now;
        } else if (date.isAfter(now)) {
            status = Post.Status.SCHEDULED;
        }
    }
    article.setDate(date);
    article.setStatus(status);
    article.setLanguage(request.getLanguage());

    article.getCategories().clear();
    for (long categoryId : request.getCategoryIds()) {
        article.getCategories().add(entityManager.getReference(Category.class, categoryId));
    }

    article.getTags().clear();
    Set<String> tagNames = StringUtils.commaDelimitedListToSet(request.getTags());
    if (!CollectionUtils.isEmpty(tagNames)) {
        for (String tagName : tagNames) {
            Tag tag = tagRepository.findOneForUpdateByNameAndLanguage(tagName, request.getLanguage());
            if (tag == null) {
                tag = new Tag();
                tag.setName(tagName);
                tag.setLanguage(request.getLanguage());
                article.setCreatedAt(now);
                article.setCreatedBy(authorizedUser.toString());
                article.setUpdatedAt(now);
                article.setUpdatedBy(authorizedUser.toString());
                tag = tagRepository.saveAndFlush(tag);
            }
            article.getTags().add(tag);
        }
    }

    article.getRelatedPosts().clear();
    Set<Post> relatedPosts = new HashSet<>();
    for (long relatedId : request.getRelatedPostIds()) {
        relatedPosts.add(entityManager.getReference(Post.class, relatedId));
    }
    article.setRelatedToPosts(relatedPosts);

    Seo seo = new Seo();
    seo.setTitle(request.getSeoTitle());
    seo.setDescription(request.getSeoDescription());
    seo.setKeywords(request.getSeoKeywords());
    article.setSeo(seo);

    List<Media> medias = new ArrayList<>();
    if (StringUtils.hasText(request.getBody())) {
        //         Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
        String mediaUrlPrefix = wallRideProperties.getMediaUrlPrefix();
        Pattern mediaUrlPattern = Pattern.compile(String.format("%s([0-9a-zA-Z\\-]+)", mediaUrlPrefix));
        Matcher mediaUrlMatcher = mediaUrlPattern.matcher(request.getBody());
        while (mediaUrlMatcher.find()) {
            Media media = mediaRepository.findOneById(mediaUrlMatcher.group(1));
            medias.add(media);
        }
    }
    article.setMedias(medias);

    article.setCreatedAt(now);
    article.setCreatedBy(authorizedUser.toString());
    article.setUpdatedAt(now);
    article.setUpdatedBy(authorizedUser.toString());

    article.getCustomFieldValues().clear();
    if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) {
        for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) {
            CustomFieldValue value = new CustomFieldValue();
            value.setCustomField(entityManager.getReference(CustomField.class, valueForm.getCustomFieldId()));
            value.setPost(article);
            if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)) {
                if (!ArrayUtils.isEmpty(valueForm.getTextValues())) {
                    value.setTextValue(String.join(",", valueForm.getTextValues()));
                } else {
                    value.setTextValue(null);
                }
            } else {
                value.setTextValue(valueForm.getTextValue());
            }
            value.setStringValue(valueForm.getStringValue());
            value.setNumberValue(valueForm.getNumberValue());
            value.setDateValue(valueForm.getDateValue());
            value.setDatetimeValue(valueForm.getDatetimeValue());
            if (!value.isEmpty()) {
                article.getCustomFieldValues().add(value);
            }
        }
    }
    return articleRepository.save(article);
}

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

/**
 * Test of getPostById method, of class BlogDaoInMemImpl.
 *///from ww  w  .j  av  a2 s .  c o m
@Test
public void testGetPostById() {
    System.out.println("getPostById");
    int postId = 0;
    BlogDaoInMemImpl instance = new BlogDaoInMemImpl();
    Post expResult = new Post("Supergirl", "Clark Kent", "hot new cousin saves city", "super, girl",
            LocalDateTime.now().toString(), "12-30-2015");
    instance.addPost(expResult);
    Post result = instance.getPostById(postId);
    assertEquals(expResult, result);
}