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:com.zuoxiaolong.blog.service.impl.UserArticleServiceImpl.java

/**
 * ???//from  w  ww .  ja  v a 2  s. c  om
 *
 * @return
 */
public List<ArticleRankResponseDto> getArticlesRank() {
    List<ArticleCategory> articleCategories = articleCategoryServiceManager.getAllArticleCategory();
    if (CollectionUtils.isEmpty(articleCategories))
        return Collections.emptyList();

    List<ArticleRankResponseDto> articleRankResponseDtos = new ArrayList<>();

    //??
    ArticleRankResponseDto recommentArticleRankResponseDto = new ArticleRankResponseDto();
    recommentArticleRankResponseDto.setActionType(ACTION_TYPE_RECOMMEND);

    Map<String, Object> recommendMap = new HashMap<>();
    List<UserArticle> recommendUserArticles;
    List<ArticleRankResponseDataResult> recommendArticleRankResponseDataResultList = new ArrayList<>();
    ArticleRankResponseDataResult recommendDataResult;
    for (ArticleCategory articleCategory : articleCategories) {
        recommendMap.put(QUERY_PARAMETER_CATEGORY_ID, articleCategory.getId());
        recommendMap.put(QUERY_PARAMETER_TIME,
                Timestamp.valueOf(LocalDateTime.now().minus(DEFAULT_DAYS_BEFORE, ChronoUnit.DAYS)));
        recommendUserArticles = this.getTopRecommendArticlesByCategoryIdAndTime(recommendMap);
        if (!CollectionUtils.isEmpty(recommendUserArticles)) {
            recommendDataResult = new ArticleRankResponseDataResult();
            recommendDataResult.setCategoryInfo(articleCategory);
            recommendDataResult.setArticleInfo(recommendUserArticles.get(TOP_NUM - 1));
            recommendArticleRankResponseDataResultList.add(recommendDataResult);
        }
    }
    recommentArticleRankResponseDto.setDataResult(recommendArticleRankResponseDataResultList);
    articleRankResponseDtos.add(recommentArticleRankResponseDto);

    //
    ArticleRankResponseDto readArticleRankResponseDto = new ArticleRankResponseDto();
    readArticleRankResponseDto.setActionType(ACTION_TYPE_READ);

    Map<String, Object> readMap = new HashMap<>();
    List<UserArticle> readUserArticles;
    ArticleRankResponseDataResult readDataResult;
    List<ArticleRankResponseDataResult> readArticleRankResponseDataResultList = new ArrayList<>();
    if (CollectionUtils.isEmpty(articleCategories))
        return Collections.emptyList();
    for (ArticleCategory articleCategory : articleCategories) {
        readMap.put(QUERY_PARAMETER_CATEGORY_ID, articleCategory.getId());
        readMap.put(QUERY_PARAMETER_TIME,
                Timestamp.valueOf(LocalDateTime.now().minus(DEFAULT_DAYS_BEFORE, ChronoUnit.DAYS)));
        readUserArticles = this.getTopReadArticlesByCategoryIdAndTime(readMap);
        if (!CollectionUtils.isEmpty(readUserArticles)) {
            readDataResult = new ArticleRankResponseDataResult();
            readDataResult.setCategoryInfo(articleCategory);
            readDataResult.setArticleInfo(readUserArticles.get(TOP_NUM - 1));
            readArticleRankResponseDataResultList.add(readDataResult);
        }
    }
    readArticleRankResponseDto.setDataResult(readArticleRankResponseDataResultList);
    articleRankResponseDtos.add(readArticleRankResponseDto);

    //
    ArticleRankResponseDto commendArticleRankResponseDto = new ArticleRankResponseDto();
    commendArticleRankResponseDto.setActionType(ACTION_TYPE_COMMENT);

    Map<String, Object> commendMap = new HashMap<>();
    List<UserArticle> commendUserArticles;
    ArticleRankResponseDataResult commendDataResult;
    List<ArticleRankResponseDataResult> commendArticleRankResponseDataResultList = new ArrayList<>();
    if (CollectionUtils.isEmpty(articleCategories))
        return Collections.emptyList();
    for (ArticleCategory articleCategory : articleCategories) {
        commendMap.put(QUERY_PARAMETER_CATEGORY_ID, articleCategory.getId());
        commendMap.put(QUERY_PARAMETER_TIME,
                Timestamp.valueOf(LocalDateTime.now().minus(DEFAULT_DAYS_BEFORE, ChronoUnit.DAYS)));
        commendUserArticles = this.getTopCommendArticles(commendMap);
        if (!CollectionUtils.isEmpty(commendUserArticles)) {
            commendDataResult = new ArticleRankResponseDataResult();
            commendDataResult.setCategoryInfo(articleCategory);
            commendDataResult.setArticleInfo(commendUserArticles.get(TOP_NUM - 1));
            commendArticleRankResponseDataResultList.add(commendDataResult);
        }
    }
    commendArticleRankResponseDto.setDataResult(commendArticleRankResponseDataResultList);
    articleRankResponseDtos.add(commendArticleRankResponseDto);

    return articleRankResponseDtos;
}

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

/**
 * Test of getActivePosts method, of class BlogDaoDbImpl.
 *///  w  ww. ja va  2 s.  c om
@Test
public void testGetActivePosts() {
    System.out.println("getActivePosts");
    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(0);
    post3.setStatus(1);
    dao.addPost(post1);
    dao.addPost(post2);
    dao.addPost(post3);
    List<Post> expResult = new ArrayList();
    expResult.add(post1);
    expResult.add(post3);
    List<Post> result = dao.getActivePosts();
    assertEquals(expResult.size(), result.size());
}

From source file:fi.vrk.xroad.catalog.persistence.CatalogServiceImpl.java

@Override
public void saveServices(SubsystemId subsystemId, Collection<Service> services) {
    assert subsystemId != null;
    Subsystem oldSubsystem = subsystemRepository.findActiveByNaturalKey(subsystemId.getXRoadInstance(),
            subsystemId.getMemberClass(), subsystemId.getMemberCode(), subsystemId.getSubsystemCode());
    if (oldSubsystem == null) {
        throw new IllegalStateException("subsystem " + subsystemId + " not found!");
    }//w  ww  .j av  a 2 s.  c om

    LocalDateTime now = LocalDateTime.now();

    Map<ServiceId, Service> unprocessedOldServices = new HashMap<>();
    oldSubsystem.getAllServices().stream().forEach(s -> unprocessedOldServices.put(s.createKey(), s));

    for (Service service : services) {
        Service oldService = unprocessedOldServices.get(service.createKey());
        if (oldService == null) {
            // brand new item, add it
            service.getStatusInfo().setTimestampsForNew(now);
            service.setSubsystem(oldSubsystem);
            oldSubsystem.getAllServices().add(service);
        } else {
            oldService.getStatusInfo().setTimestampsForFetched(now);
        }
        unprocessedOldServices.remove(service.createKey());
    }

    // now unprocessedOldServices should all be removed (either already removed, or will be now)
    for (Service oldToRemove : unprocessedOldServices.values()) {
        StatusInfo status = oldToRemove.getStatusInfo();
        if (!status.isRemoved()) {
            status.setTimestampsForRemoved(now);
        }
    }

}

From source file:nc.noumea.mairie.appock.services.impl.DemandeServiceImpl.java

@Override
public void traiteDemande(Demande demande) throws UnsupportedEncodingException, MessagingException {
    demande = demandeRepository.findOne(demande.getId());
    demande.setEtatDemande(EtatDemande.TRAITE);
    demande.setDateTraitement(LocalDateTime.now());
    demande.setTraitementUser(authHelper.getCurrentUser().getNomComplet());
    demandeRepository.save(demande);//from  w w w  .  j  a  va  2s  . co  m
    mailService.sendMailSuiteTraitementDemande(demande);
}

From source file:org.cloud.mblog.utils.FileUtil.java

/**
 * ?//w  w w.j av a 2 s .  c  o m
 *
 * @param avatar_file
 * @param request
 * @param x
 * @param y
 * @param width
 * @param height
 * @return
 */
public static ResponseMessage processCropPost(MultipartFile avatar_file, HttpServletRequest request, float x,
        float y, float width, float height) {
    LocalDateTime now = LocalDateTime.now();
    String realFolder = LOCALROOT + getThumbRelativePathByDate(now);
    String urlPath = getThumbUrlPathByDate(now);
    // MIMEtype
    String type = avatar_file.getContentType();
    if (type == null || !type.toLowerCase().startsWith("image/")) {
        return new ResponseMessage("????", null);
    }

    String sourceFileName = avatar_file.getOriginalFilename();
    String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1);
    String fileName = getDateTypeFileName(now, fileType);
    String fullUrl = urlPath + "/" + fileName;

    // 
    File targetFile = new File(realFolder, fileName);
    // ?
    try {
        if (!targetFile.exists()) {
            InputStream is = avatar_file.getInputStream();
            ImageUtil.cutAndScale(ImageIO.read(is), targetFile, (int) x, (int) y, (int) width, (int) height,
                    500, 300);
            is.close();
        }
    } catch (Exception e) {
        logger.error("error", e);
        return new ResponseMessage("" + e.getMessage(), null);
    }
    return new ResponseMessage("?", fullUrl);
}

From source file:com.bosch.iot.things.example.historian.Collector.java

/**
 * Collect list of individual property changes
 *//*from  w w  w .j  a v a2s  .  c  o  m*/
private static void collectChanges(List target, String thingId, String featureId, JsonPointer path,
        JsonValue value) {
    if (value.isObject()) {
        // on Object recursively collect all individual properties with concatenated property path
        JsonObject obj = value.asObject();
        obj.forEach(c -> {
            collectChanges(target, thingId, featureId, path.addLeaf(c.getKey()), c.getValue());
        });
    } else {
        target.add(new History(thingId, featureId, path, value, LocalDateTime.now()));
    }
}

From source file:io.mandrel.metrics.impl.MongoMetricsRepository.java

@Scheduled(cron = "0 0 * * * *")
public void prepareNextMinutes() {
    log.debug("Preparing next metric bucket");

    // TODO Distributed lock!
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime keytime = now.withMinute(0).withSecond(0).withNano(0).plusMinutes(1);

    prepareMinutes(keytime);/*w ww.  j av a2s  . c  om*/
}

From source file:org.dhatim.fastexcel.Correctness.java

@Test
public void singleWorksheet() throws Exception {
    String sheetName = "Worksheet 1";
    String stringValue = "Sample text with chars to escape : < > & \\ \" ' ~        ";
    Date dateValue = new Date();
    LocalDateTime localDateTimeValue = LocalDateTime.now();
    ZoneId timezone = ZoneId.of("Australia/Sydney");
    ZonedDateTime zonedDateValue = ZonedDateTime.ofInstant(dateValue.toInstant(), timezone);
    double doubleValue = 1.234;
    int intValue = 2_016;
    long longValue = 2_016_000_000_000L;
    BigDecimal bigDecimalValue = BigDecimal.TEN;
    byte[] data = writeWorkbook(wb -> {
        Worksheet ws = wb.newWorksheet(sheetName);
        int i = 1;
        ws.value(i, i++, stringValue);/*from w  w  w.jav a2  s.co  m*/
        ws.value(i, i++, dateValue);
        ws.value(i, i++, localDateTimeValue);
        ws.value(i, i++, zonedDateValue);
        ws.value(i, i++, doubleValue);
        ws.value(i, i++, intValue);
        ws.value(i, i++, longValue);
        ws.value(i, i++, bigDecimalValue);
        try {
            ws.finish();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    // Check generated workbook with Apache POI
    XSSFWorkbook xwb = new XSSFWorkbook(new ByteArrayInputStream(data));
    assertThat(xwb.getActiveSheetIndex()).isEqualTo(0);
    assertThat(xwb.getNumberOfSheets()).isEqualTo(1);
    XSSFSheet xws = xwb.getSheet(sheetName);
    @SuppressWarnings("unchecked")
    Comparable<XSSFRow> row = (Comparable) xws.getRow(0);
    assertThat(row).isNull();
    int i = 1;
    assertThat(xws.getRow(i).getCell(i++).getStringCellValue()).isEqualTo(stringValue);
    assertThat(xws.getRow(i).getCell(i++).getDateCellValue()).isEqualTo(dateValue);
    // Check zoned timestamps have the same textual representation as the Dates extracted from the workbook
    // (Excel date serial numbers do not carry timezone information)
    assertThat(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime
            .ofInstant(xws.getRow(i).getCell(i++).getDateCellValue().toInstant(), ZoneId.systemDefault())))
                    .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTimeValue));
    assertThat(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime
            .ofInstant(xws.getRow(i).getCell(i++).getDateCellValue().toInstant(), ZoneId.systemDefault())))
                    .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(zonedDateValue));
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(doubleValue);
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(intValue);
    assertThat(xws.getRow(i).getCell(i++).getNumericCellValue()).isEqualTo(longValue);
    assertThat(new BigDecimal(xws.getRow(i).getCell(i++).getRawValue())).isEqualTo(bigDecimalValue);
}

From source file:nc.noumea.mairie.appock.viewmodel.EditStockReferentAchatViewModel.java

@Command
public void demandeInventaireService() throws UnsupportedEncodingException, MessagingException {
    if (entity == null || getSelectedService() == null) {
        return;//from  w  ww . j a va  2s.  c o m
    }

    Service service = serviceService.findOne(getSelectedService().getId());
    Messagebox.show(
            "Voulez-vous vraiment demander au service '" + service.getLibellePoleDirectionService()
                    + "' de raliser un inventaire ?",
            "Confirmation", new Messagebox.Button[] { Messagebox.Button.YES, Messagebox.Button.NO },
            Messagebox.QUESTION, evt -> {
                if (evt.getName().equals("onYes")) {
                    entity.setInventaireDemande(true);
                    entity.setInventaireDemandeUser(authHelper.getCurrentUser().getNomComplet());
                    entity.setDateDerniereDemandeInventaire(LocalDateTime.now());
                    stockService.save(entity);
                    mailService.sendMailDemandeInventaire(getSelectedService());

                    refreshListeArticleStock();
                    rechargeOngletMonStock();
                    BindUtils.postNotifyChange(null, null, this, "*");
                    showNotificationStandard("Demande d'inventaire envoye au service");
                }
            });
}