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:edu.wustl.lookingglass.community.CommunityRepository.java

private void resolveMerge() throws NoWorkTreeException, GitAPIException, IOException {
    assert this.username != null;
    assert this.email != null;

    Status status = this.git.status().call();
    Map<String, StageState> conflicting = status.getConflictingStageState();

    for (String path : conflicting.keySet()) {
        StageState stageState = conflicting.get(path);
        switch (stageState) {
        case BOTH_MODIFIED: // UU
        case BOTH_ADDED: // AA
        case ADDED_BY_US: // AU
        case ADDED_BY_THEM: // UA
            // Both the local and server version have been modified
            File conflictingFile = new File(this.repoDir, path);
            String fullPath = conflictingFile.getAbsolutePath();

            // Since the local copy was modified it probably makes sense to leave it
            // since that's the copy the user has been working on. Here's my assumption...
            // a sync didn't happen, so the user opens their project and sees it's not their
            // latest changes, they accept the failure and start to fix it... finally a sync
            // happens... at this point they are probably editing this world, so when they save
            // they wouldn't even load the new file, so we should just keep the old file.

            // TODO: we should really prompt the user to resolve this conflict.
            // but that's kinda hard with the singletons... because you probably just want
            // to open both files in two different windows (editors) but we can't do that. :(

            // Recover server version
            this.git.checkout().setStage(Stage.THEIRS).addPath(path).call();

            // Append a timestamp
            LocalDateTime date = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-mm-dd+HH'h'MM'm'");
            String timestamp = date.format(formatter);
            File theirFile = new File(FilenameUtils.getFullPath(fullPath), FilenameUtils.getBaseName(path)
                    + " (" + timestamp + ")." + FilenameUtils.getExtension(path));

            if (conflictingFile.exists() && !theirFile.exists()) {
                Files.move(conflictingFile.toPath(), theirFile.toPath());

                String relativePath = this.repoDir.toURI().relativize(theirFile.toURI()).getPath();
                this.git.add().addFilepattern(relativePath).call();
            }//from  w w  w.  j  a  v  a  2 s  .  c om

            // Recover local version
            this.git.checkout().setStage(Stage.OURS).addPath(path).call();
            this.git.add().addFilepattern(path).call();
            break;

        case DELETED_BY_US: // DU
            // The modified local version is already in the checkout, so it just needs to be added.
            // We need to specifically mention the file, so we can't reuse the Add () method
            this.git.add().addFilepattern(path).call();
            break;
        case DELETED_BY_THEM: // UD
            // Recover server version
            this.git.checkout().setStage(Stage.THEIRS).addPath(path).call();
            this.git.add().addFilepattern(path).call();
            break;
        case BOTH_DELETED: // DD
            break;
        default:
            throw new IllegalArgumentException("Unknown StageState: " + stageState);
        }
    }

    RepositoryState resolvedState = this.git.getRepository().getRepositoryState();
    assert resolvedState == RepositoryState.MERGING_RESOLVED;

    // we are done resolving the merge!
    this.git.commit().setAuthor(this.username, this.email).call();

    RepositoryState safeState = this.git.getRepository().getRepositoryState();
    assert safeState == RepositoryState.SAFE;
}

From source file:de.sub.goobi.forms.IndexingForm.java

private void startIndexing(ObjectType type, IndexWorker worker) {
    int attempts = 0;
    while (attempts < 10) {
        try {//from  w  w  w . j a v  a 2s  .  c  o  m
            if (Objects.equals(currentIndexState, ObjectType.NONE)) {
                indexingStartedTime = LocalDateTime.now();
                currentIndexState = type;
                pollingChannel.send(INDEXING_STARTED_MESSAGE + currentIndexState);
                indexerThread = new Thread((worker));
                indexerThread.setDaemon(true);
                indexerThread.start();
                indexerThread.join();
                break;
            } else {
                logger.debug("Cannot start '" + type
                        + "' indexing while a different indexing process running: '" + currentIndexState + "'");
                Thread.sleep(pause);
                attempts++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.gnadenheimer.mg.utils.Utils.java

public void backUpIfOld() {
    try {/*from  ww  w.j  a v a 2s .co  m*/
        Path dir = Paths.get(getPersistenceMap().get("backUpDir")); // specify your directory

        Optional<Path> lastFilePath = Files.list(dir) // here we get the stream with full directory listing
                .filter(f -> Files.isDirectory(f)) // exclude files from listing
                .max(Comparator.comparingLong(f -> f.toFile().lastModified())); // finally get the last file using simple comparator by lastModified field

        if (lastFilePath.isPresent()) // your folder may be empty
        {
            FileTime fileTime = Files.getLastModifiedTime(lastFilePath.get());
            Long age = DAYS.between(LocalDateTime.ofInstant(fileTime.toInstant(), ZoneOffset.UTC),
                    LocalDateTime.now());
            if (age > 7) {
                exectueBackUp(getPersistenceMap().get("backUpDir"));
            }
        } else {
            exectueBackUp(getPersistenceMap().get("backUpDir"));
        }
    } catch (Exception ex) {
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage());
    }
}

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

@CacheEvict(value = WallRideCacheConfiguration.ARTICLE_CACHE, allEntries = true)
public List<Article> bulkPublishArticle(ArticleBulkPublishRequest request, AuthorizedUser authorizedUser) {
    List<Article> articles = new ArrayList<>();
    for (long id : request.getIds()) {
        postRepository.lock(id);//from  w ww .ja  v a 2s  .c  om
        Article article = articleRepository.findOneByIdAndLanguage(id, request.getLanguage());
        if (article.getStatus() != Post.Status.DRAFT && request.getDate() == null) {
            continue;
        }

        if (!StringUtils.hasText(article.getCode())) {
            throw new NotNullException();
        }
        if (!StringUtils.hasText(article.getTitle())) {
            throw new NotNullException();
        }
        if (!StringUtils.hasText(article.getBody())) {
            throw new NotNullException();
        }

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime date = article.getDate();
        if (request.getDate() != null) {
            date = request.getDate();
        }
        if (date == null) {
            date = now;
        }
        article.setDate(date);
        article.setUpdatedAt(now);
        article.setUpdatedBy(authorizedUser.toString());

        article = publishArticle(article);

        if (article.getDate().isAfter(now)) {
            article.setStatus(Post.Status.SCHEDULED);
        } else {
            article.setStatus(Post.Status.PUBLISHED);
        }
        article = articleRepository.saveAndFlush(article);

        articles.add(article);
    }
    return articles;
}

From source file:org.codelibs.fess.service.SearchLogService.java

public void deleteBefore(final int days) {
    final LocalDateTime targetTime = LocalDateTime.now().minusDays(days);
    clickLogBhv.varyingQueryDelete(cb2 -> {
        cb2.query().querySearchLog().setRequestedTime_LessThan(targetTime);
    }, op -> op.allowNonQueryDelete());
    searchFieldLogBhv.varyingQueryDelete(cb3 -> {
        cb3.query().querySearchLog().setRequestedTime_LessThan(targetTime);
    }, op -> op.allowNonQueryDelete());
    searchLogBhv.varyingQueryDelete(cb1 -> {
        cb1.query().setRequestedTime_LessThan(targetTime);
    }, op -> op.allowNonQueryDelete());
}

From source file:com.gnadenheimer.mg.utils.Utils.java

/**
 * Delete AutoBackUps if older than 60 days
 *///w w  w  .  j  a va  2  s.c  o  m
public void deleteOldBackUps() {
    try {
        Path dir = Paths.get(getPersistenceMap().get("backUpDir")); // specify your directory

        Optional<Path> lastFilePath = Files.list(dir) // here we get the stream with full directory listing
                .filter(f -> Files.isDirectory(f)) // exclude files from listing
                .min(Comparator.comparingLong(f -> f.toFile().lastModified())); // finally get the last file using simple comparator by lastModified field

        if (lastFilePath.isPresent()) // your folder may be empty
        {
            FileTime fileTime = Files.getLastModifiedTime(lastFilePath.get());
            Long age = DAYS.between(LocalDateTime.ofInstant(fileTime.toInstant(), ZoneOffset.UTC),
                    LocalDateTime.now());
            if (age > 30) {
                Files.walk(lastFilePath.get(), FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                        .map(Path::toFile).peek(System.out::println).forEach(File::delete);
                deleteOldBackUps();
            }
        }
    } catch (Exception ex) {
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage());
    }
}

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

@CacheEvict(value = WallRideCacheConfiguration.ARTICLE_CACHE, allEntries = true)
public List<Article> bulkUnpublishArticle(ArticleBulkUnpublishRequest request, AuthorizedUser authorizedUser) {
    List<Article> articles = new ArrayList<>();
    for (long id : request.getIds()) {
        postRepository.lock(id);/*from   w  w  w  .  j  a  v  a  2  s  .  c  o  m*/
        Article article = articleRepository.findOneByIdAndLanguage(id, request.getLanguage());
        if (article.getStatus() == Post.Status.DRAFT) {
            continue;
        }

        LocalDateTime now = LocalDateTime.now();
        article.setUpdatedAt(now);
        article.setUpdatedBy(authorizedUser.toString());

        article = unpublishArticle(article);
        articles.add(article);
    }
    return articles;
}

From source file:com.romeikat.datamessie.core.processing.task.documentProcessing.DocumentProcessorTest.java

@Test
public void processDocument_redirectedDownloadError() throws Exception {
    Document document1 = documentDao.getEntity(sessionProvider.getStatelessSession(), 1);
    RawContent rawContent1 = rawContentDao.getEntity(sessionProvider.getStatelessSession(), 1);
    CleanedContent cleanedContent1 = cleanedContentDao.getEntity(sessionProvider.getStatelessSession(), 1);
    StemmedContent stemmedContent1 = stemmedContentDao.getEntity(sessionProvider.getStatelessSession(), 1);
    final DocumentAndContentValues oldValues = new DocumentAndContentValues(document1, rawContent1,
            cleanedContent1, stemmedContent1);

    // Simulate error
    final DocumentRedirectingResult expectedDocumentRedirectingResult = new DocumentRedirectingResult(
            REDIRECTED_URL,//from   w w w .ja v a2 s  .co m
            new DownloadResult(document1.getUrl(), REDIRECTED_URL, null, LocalDateTime.now(), 503));
    doReturn(expectedDocumentRedirectingResult).when(documentRedirector).redirect(any(StatelessSession.class),
            any(Document.class), any(RawContent.class));

    // Process
    documentProcessor.processDocument(sessionProvider.getStatelessSession(), document1);

    // Processing failed:
    // state becomes REDIRECTING_ERROR; cleaned and stemmed contents become null; other fields
    // remain unmodified
    document1 = documentDao.getEntity(sessionProvider.getStatelessSession(), 1);
    rawContent1 = rawContentDao.getEntity(sessionProvider.getStatelessSession(), 1);
    cleanedContent1 = cleanedContentDao.getEntity(sessionProvider.getStatelessSession(), 1);
    stemmedContent1 = stemmedContentDao.getEntity(sessionProvider.getStatelessSession(), 1);
    final DocumentAndContentValues expectedValues = new DocumentAndContentValues(oldValues.getTitle(),
            oldValues.getStemmedTitle(), oldValues.getUrl(), oldValues.getDescription(),
            oldValues.getStemmedDescription(), oldValues.getPublished(), oldValues.getDownloaded(),
            DocumentProcessingState.REDIRECTING_ERROR, oldValues.getStatusCode(), oldValues.getRawContent(),
            null, null);
    final DocumentAndContentValues actualValues = new DocumentAndContentValues(document1, rawContent1,
            cleanedContent1, stemmedContent1);
    assertEquals(expectedValues, actualValues);
    final List<NamedEntityOccurrence> namedEntityOccurrences = namedEntityOccurrenceDao
            .getByDocument(sessionProvider.getStatelessSession(), 1);
    assertEquals(0, namedEntityOccurrences.size());

    // Statistics are rebuilt
    final StatisticsRebuildingSparseTable statisticsToBeRebuilt = documentProcessor.getStatisticsToBeRebuilt();
    assertTrue(statisticsToBeRebuilt.getValue(document1.getSourceId(), document1.getPublishedDate()));

    // Failed documents
    assertTrue(documentProcessor.getFailedDocumentIds().isEmpty());
}

From source file:kitt.site.controller.mobile.UserController.java

/**
 * ???//ww w.j av a2s  .c o m
 */
@LoginRequired
@ResponseBody
@RequestMapping(value = "/account/resetPassword", method = RequestMethod.POST)
public Object resetPassword(String code, String password, @CurrentUser User user, BindResult bindResult) {
    Phonevalidator phonevalidator = validMapper.findVerifyCode(user.getSecurephone(), code,
            ValidateType.resetpasswordWeixin);
    //??
    if (StringUtils.isBlank(code)) {
        bindResult.addError("verifyCode", "???");
    } else if (phonevalidator == null) {
        bindResult.addError("verifyCode", "??");
    } else if (phonevalidator.getExpiretime().isBefore(LocalDateTime.now())) {
        bindResult.addError("verifyCode", "??");
    } else {
        validMapper.modifyValidatedAndTime(user.getSecurephone(), code);
        userMapper.modifyPasswdByPhone(DigestUtils.md5Hex(password), user.getSecurephone());
    }
    return json(bindResult);
}