Example usage for java.time LocalDateTime isAfter

List of usage examples for java.time LocalDateTime isAfter

Introduction

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

Prototype

@Override 
public boolean isAfter(ChronoLocalDateTime<?> other) 

Source Link

Document

Checks if this date-time is after the specified date-time.

Usage

From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = false)//  w  ww  .  j  av  a2 s.  c om
public String reserver(final LocalDate date, final int individuId, final Famille famille, final Boolean reserve)
        throws FunctionalException, TechnicalException {
    final LocalDateTime heureResa = this.getLimiteResaCantine(date);
    if (!heureResa.isAfter(LocalDateTime.now())) {
        throw new ActNonModifiableException("activite non reservable");
    }
    final Date d = Date.from(Instant.from(date.atStartOfDay(ZoneId.systemDefault())));
    final Activite activite = getCantineActivite();
    final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille);
    final Inscription ict = icts.stream().filter(i -> individuId == i.getIndividu().getId()).findFirst().get();
    final List<Consommation> consos = this.consommationRepository.findByInscriptionActiviteUniteDate(ict,
            activite, ict.getGroupe(), d);
    final Unite unite = this.uniteRepository.findOneByActiviteAndType(ict.getActivite(), "Unitaire");
    if ((reserve == null && consos != null && !consos.isEmpty())
            || (reserve != null && reserve == false && consos != null && !consos.isEmpty())) {
        consos.forEach(c -> this.consommationRepository.delete(c));
        return "libre";
        // on supprime la conso
    } else if ((reserve == null && (consos == null || consos.isEmpty()))
            || (reserve == true && (consos == null || consos.isEmpty()))) {
        // cree la conso
        final Consommation conso = new Consommation();
        conso.setActivite(activite);
        conso.setDate(d);
        conso.setDateSaisie(new Date());
        conso.setEtat("reservation");
        conso.setGroupe(ict.getGroupe());
        conso.setIndividu(ict.getIndividu());
        conso.setInscription(ict);
        conso.setComptePayeur(ict.getComptePayeur());
        conso.setCategorieTarif(ict.getCategorieTarif());
        conso.setUnite(unite);
        conso.setHeureDebut(unite.getHeureDebut());
        conso.setHeureFin(unite.getHeureFin());

        this.consommationRepository.save(conso);
        return "reserve";
    }
    return "rien";

}

From source file:org.jbb.security.impl.lockout.DefaultMemberLockoutService.java

private void removeOldEntriesFromInvalidSignInRepositoryIfNeeded(Long memberId) {
    LocalDateTime now = DateTimeProvider.now();
    LocalDateTime dateCeiling = calculateDateCeilingWhereYoungerEntriesShouldBeDeleted(memberId, now);

    if (now.isAfter(dateCeiling)) {
        log.debug(/*from ww  w  . j  a  v  a2s .com*/
                "Some entries for member {} are qualified to be delete. All entries for that member before {} will be deleted",
                memberId, dateCeiling);
        removeTooOldEntriesFromInvalidSignInRepository(memberId);
    }
}

From source file:com.otway.picasasync.syncutil.ImageSync.java

public boolean newerThan(LocalDateTime threshold) throws ServiceException {
    boolean localFileExists = localFile.exists();

    if (localFileExists) {
        LocalDateTime localTimeStamp = getTimeFromMS(localFile.lastModified());

        // There's a local file. See if it's newer
        if (localTimeStamp.isAfter(threshold))
            return true;
    }//from ww  w  .j ava 2 s. c o m

    if (remotePhoto != null) {
        LocalDateTime remoteTimeStamp = LocalDateTime.ofInstant(remotePhoto.getTimestamp().toInstant(),
                ZoneId.systemDefault());

        // There's a remote file. See if it's newer
        if (remoteTimeStamp.isAfter(threshold))
            return true;
    }

    return false;
}

From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = true)//  w  ww  . j a v  a2  s  . c  om
public PlanningDto getDateOuvert(final YearMonth anneeMois, final Famille famille) throws TechnicalException {
    final Date startDate = Date.from(Instant.from(anneeMois.atDay(1).atStartOfDay(ZoneId.systemDefault())));
    final Date endDate = Date.from(Instant.from(anneeMois.atEndOfMonth().atStartOfDay(ZoneId.systemDefault())));

    final Activite activite = getCantineActivite();

    final LocalDateTime heureH = LocalDateTime.now();
    final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille);

    final PlanningDto planning = new PlanningDto();

    icts.forEach(ict -> {
        planning.getHeaders().add(ict.getIndividu().getPrenom());
        final List<Consommation> consos = this.consommationRepository
                .findByFamilleInscriptionActiviteUniteEtatsPeriode(famille, activite, ict.getGroupe(),
                        Arrays.asList("reservation"), startDate, endDate);
        final List<Ouverture> ouvertures = this.ouvertureRepository.findByActiviteAndGroupeAndPeriode(activite,
                ict.getGroupe(), startDate, endDate);
        ouvertures.forEach(o -> {
            final LocalDate date = LocalDate.from(((java.sql.Date) o.getDate()).toLocalDate());
            final LocalDateTime heureResa = this.getLimiteResaCantine(date);
            final LigneDto ligne = planning.getOrCreateLigne(date);
            final CaseDto c = new CaseDto();
            c.setDate(date);
            c.setIndividu(ict.getIndividu());
            c.setActivite(o.getActivite());
            c.setUnite(o.getUnite());
            c.setReservable(heureResa.isAfter(heureH));
            final Optional<Consommation> cOpt = consos.stream().filter(conso -> {
                final LocalDate dateConso = LocalDate.from(((java.sql.Date) conso.getDate()).toLocalDate());
                return dateConso.equals(date);
            }).findAny();
            c.setReserve(cOpt.isPresent());
            ligne.getCases().add(c);
        });
    });

    return planning;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.HopsworksRMAppSecurityActions.java

protected boolean isTime2Renew(LocalDateTime now, LocalDateTime tokenExpiration) {
    return now.isAfter(tokenExpiration) || now.isEqual(tokenExpiration);
}

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  .  j  a  v  a  2 s  .c  om
            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: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 {//  w  ww  .  j a  v a  2s  .  co  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.service.ArticleService.java

@CacheEvict(value = WallRideCacheConfiguration.ARTICLE_CACHE, allEntries = true)
public Article saveArticle(ArticleUpdateRequest request, AuthorizedUser authorizedUser) {
    postRepository.lock(request.getId());
    Article article = articleRepository.findOneByIdAndLanguage(request.getId(), request.getLanguage());
    LocalDateTime now = LocalDateTime.now();

    String code = request.getCode();
    if (code == null) {
        try {//  www .  j  a  va 2 s  .c  o  m
            code = new CodeFormatter().parse(request.getTitle(), LocaleContextHolder.getLocale());
        } catch (ParseException e) {
            throw new ServiceException(e);
        }
    }
    if (!StringUtils.hasText(code)) {
        if (!article.getStatus().equals(Post.Status.DRAFT)) {
            throw new EmptyCodeException();
        }
    }
    if (!article.getStatus().equals(Post.Status.DRAFT)) {
        Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage());
        if (duplicate != null && !duplicate.equals(article)) {
            throw new DuplicateCodeException(code);
        }
    }

    if (!article.getStatus().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());

    //      User author = null;
    //      if (request.getAuthorId() != null) {
    //         author = entityManager.getReference(User.class, request.getAuthorId());
    //      }
    //      article.setAuthor(author);

    LocalDateTime date = request.getDate();
    if (!Post.Status.DRAFT.equals(article.getStatus())) {
        if (date == null) {
            date = now;
        } else if (date.isAfter(now)) {
            article.setStatus(Post.Status.SCHEDULED);
        } else {
            article.setStatus(Post.Status.PUBLISHED);
        }
    }
    article.setDate(date);
    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.setUpdatedAt(now);
    article.setUpdatedBy(authorizedUser.toString());

    Map<CustomField, CustomFieldValue> valueMap = new LinkedHashMap<>();
    for (CustomFieldValue value : article.getCustomFieldValues()) {
        valueMap.put(value.getCustomField(), value);
    }

    article.getCustomFieldValues().clear();
    if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) {
        for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) {
            CustomField customField = entityManager.getReference(CustomField.class,
                    valueForm.getCustomFieldId());
            CustomFieldValue value = valueMap.get(customField);
            if (value == null) {
                value = new CustomFieldValue();
            }
            value.setCustomField(customField);
            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:org.talend.dataprep.api.filter.SimpleFilterService.java

/**
 * Create a predicate that checks if the date value is within a range [min, max[
 *
 * @param columnId The column id/*from  w w w  .ja  v a 2 s  .c  o m*/
 * @param start The start value
 * @param end The end value
 * @return The date range predicate
 */
private Predicate<DataSetRow> createDateRangePredicate(final String columnId, final String start,
        final String end, final RowMetadata rowMetadata) {
    try {
        final long minTimestamp = Long.parseLong(start);
        final long maxTimestamp = Long.parseLong(end);

        final LocalDateTime minDate = dateManipulator.fromEpochMillisecondsWithSystemOffset(minTimestamp);
        final LocalDateTime maxDate = dateManipulator.fromEpochMillisecondsWithSystemOffset(maxTimestamp);

        return safeDate(r -> {
            final ColumnMetadata columnMetadata = rowMetadata.getById(columnId);
            final LocalDateTime columnValue = getDateParser().parse(r.get(columnId), columnMetadata);
            return minDate.compareTo(columnValue) == 0
                    || (minDate.isBefore(columnValue) && maxDate.isAfter(columnValue));
        });
    } catch (Exception e) {
        LOGGER.debug("Unable to create date range predicate.", e);
        throw new IllegalArgumentException(
                "Unsupported query, malformed date 'range' (expected timestamps in min and max properties).");
    }
}

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

@CacheEvict(value = WallRideCacheConfiguration.PAGE_CACHE, allEntries = true)
public Page savePage(PageUpdateRequest request, AuthorizedUser authorizedUser) {
    postRepository.lock(request.getId());
    Page page = pageRepository.findOneByIdAndLanguage(request.getId(), request.getLanguage());
    LocalDateTime now = LocalDateTime.now();

    String code = request.getCode();
    if (code == null) {
        try {/*ww  w  .  j a v  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 (!page.getStatus().equals(Post.Status.DRAFT)) {
            throw new EmptyCodeException();
        }
    }
    if (!page.getStatus().equals(Post.Status.DRAFT)) {
        Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage());
        if (duplicate != null && !duplicate.equals(page)) {
            throw new DuplicateCodeException(code);
        }
    }

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

    Page parent = (request.getParentId() != null)
            ? entityManager.getReference(Page.class, request.getParentId())
            : null;
    if (!(page.getParent() == null && parent == null)
            && !ObjectUtils.nullSafeEquals(page.getParent(), parent)) {
        pageRepository.shiftLftRgt(page.getLft(), page.getRgt());
        pageRepository.shiftRgt(page.getRgt());
        pageRepository.shiftLft(page.getRgt());

        int rgt = 0;
        if (parent == null) {
            rgt = pageRepository.findMaxRgt();
            rgt++;
        } else {
            rgt = parent.getRgt();
            pageRepository.unshiftRgt(rgt);
            pageRepository.unshiftLft(rgt);
        }
        page.setLft(rgt);
        page.setRgt(rgt + 1);
    }

    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());

    //      User author = null;
    //      if (request.getAuthorId() != null) {
    //         author = entityManager.getReference(User.class, request.getAuthorId());
    //      }
    //      page.setAuthor(author);

    LocalDateTime date = request.getDate();
    if (Post.Status.PUBLISHED.equals(page.getStatus())) {
        if (date == null) {
            date = now.truncatedTo(ChronoUnit.HOURS);
        } else if (date.isAfter(now)) {
            page.setStatus(Post.Status.SCHEDULED);
        }
    }
    page.setDate(date);
    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);

    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.setUpdatedAt(now);
    page.setUpdatedBy(authorizedUser.toString());

    SortedSet<CustomFieldValue> fieldValues = new TreeSet<>();
    Map<CustomField, CustomFieldValue> valueMap = new LinkedHashMap<>();
    for (CustomFieldValue value : page.getCustomFieldValues()) {
        valueMap.put(value.getCustomField(), value);
    }

    page.getCustomFieldValues().clear();
    if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) {
        for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) {
            CustomField customField = entityManager.getReference(CustomField.class,
                    valueForm.getCustomFieldId());
            CustomFieldValue value = valueMap.get(customField);
            if (value == null) {
                value = new CustomFieldValue();
            }
            value.setCustomField(customField);
            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()) {
                fieldValues.add(value);
            }
        }
    }
    page.setCustomFieldValues(fieldValues);

    return pageRepository.save(page);
}