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.apache.metron.dataloads.nonbulk.geo.GeoEnrichmentLoader.java

protected void loadGeoIpDatabase(CommandLine cli) throws IOException {
    // Retrieve the database file
    System.out.println("Retrieving GeoLite2 archive");
    String url = GeoEnrichmentOptions.GEO_URL.get(cli,
            "http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz");
    String tmpDir = GeoEnrichmentOptions.TMP_DIR.get(cli, "/tmp") + "/"; // Make sure there's a file separator at the end
    File localGeoFile = downloadGeoFile(url, tmpDir);
    // Want to delete the tar in event of failure
    localGeoFile.deleteOnExit();/*  w  ww . j  av a  2s. com*/
    System.out.println("GeoIP files downloaded successfully");

    // Push the file to HDFS and update Configs to ensure clients get new view
    String zookeeper = GeoEnrichmentOptions.ZK_QUORUM.get(cli);
    long millis = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli();
    String hdfsLoc = GeoEnrichmentOptions.REMOTE_DIR.get(cli, "/apps/metron/geo/" + millis);
    System.out.println("Putting GeoLite2 file into HDFS at: " + hdfsLoc);

    // Put into HDFS
    Path srcPath = new Path(localGeoFile.getAbsolutePath());
    Path dstPath = new Path(hdfsLoc);
    putDbFile(srcPath, dstPath);
    pushConfig(srcPath, dstPath, zookeeper);

    System.out.println("GeoLite2 file placement complete");
    System.out.println("Successfully created and updated new GeoIP information");
}

From source file:org.openhab.binding.openuv.internal.handler.OpenUVBridgeHandler.java

public @Nullable OpenUVResult getUVData(String latitude, String longitude, @Nullable String altitude) {
    StringBuilder urlBuilder = new StringBuilder(BASE_URL).append("?lat=").append(latitude).append("&lng=")
            .append(longitude);/*from  w  ww .jav a 2 s  .c  o m*/

    if (altitude != null) {
        urlBuilder.append("&alt=").append(altitude);
    }
    String errorMessage = null;
    try {
        String jsonData = HttpUtil.executeUrl("GET", urlBuilder.toString(), header, null, null,
                REQUEST_TIMEOUT);
        OpenUVResponse uvResponse = gson.fromJson(jsonData, OpenUVResponse.class);
        if (uvResponse.getError() == null) {
            updateStatus(ThingStatus.ONLINE);
            return uvResponse.getResult();
        } else {
            errorMessage = uvResponse.getError();
        }
    } catch (IOException e) {
        errorMessage = e.getMessage();
    }

    if (errorMessage.startsWith(ERROR_QUOTA_EXCEEDED)) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, errorMessage);
        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plusDays(1);
        LocalDateTime tomorrowMidnight = tomorrow.atStartOfDay().plusMinutes(2);

        logger.warn("Quota Exceeded, going OFFLINE for today, will retry at : {} ", tomorrowMidnight);
        scheduler.schedule(this::initiateConnexion,
                Duration.between(LocalDateTime.now(), tomorrowMidnight).toMinutes(), TimeUnit.MINUTES);

    } else if (errorMessage.startsWith(ERROR_WRONG_KEY)) {
        logger.error("Error occured during API query : {}", errorMessage);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, errorMessage);
    }
    return null;
}

From source file:cz.muni.fi.editor.services.api.requests.RequestServiceImpl.java

@TransactionalEventListener
@Async//from  www  .  j a  v a 2  s  . c o  m
@Transactional
public void joinOrganization(EOrganizationJoined eOrganizationJoined) {
    Request request = new Request();
    request.setAction("join");
    request.setTargetId(eOrganizationJoined.getOrganization().getId());
    request.setClazz(OrganizationDTO.class.getName());
    request.setState(RequestState.PENDING);
    request.setRequestDate(LocalDateTime.now());
    request.setRequestor(mapper.map(eOrganizationJoined.getActor(), User.class));

    requestDAO.create(request);

    applicationEventPublisher.publishEvent(new ERequestCreated(this, eOrganizationJoined.getActor(), request));
}

From source file:org.darkware.wpman.util.TimeWindow.java

/**
 * Fetch a time offset to a random moment within the time window.
 *
 * @return A number of seconds to a moment that is within the time window.
 *//*from  w w  w . j  av  a2  s.  c om*/
public Duration getRandomOffset() {
    return Duration.between(LocalDateTime.now(), this.getRandomMoment());
}

From source file:gov.ca.cwds.cals.service.builder.PlacementHomeEntityAwareDTOBuilder.java

private List<PhoneContactDetail> mapPhoneContactDetails(ApplicantDTO applicantDTO) {
    if (CollectionUtils.isNotEmpty(applicantDTO.getPhones())) {
        return applicantDTO.getPhones().stream().map(phoneNumber -> {
            PhoneContactDetail phoneContactDetail = new PhoneContactDetail();
            phoneContactDetail.setEstblshCd("S");
            phoneContactDetail.setPhoneNo(Long.parseLong(phoneNumber.getNumber()));
            if (StringUtils.isNotEmpty(phoneNumber.getExtension())) {
                phoneContactDetail.setPhextNo(Integer.valueOf(phoneNumber.getExtension()));
            }/*from ww w  .  ja  v  a2  s.  c  o  m*/
            phoneContactDetail.setPhnTypCd(phoneNumber.getPhoneType().getCwsShortCode());
            phoneContactDetail.setLstUpdId(PrincipalUtils.getStaffPersonId());
            phoneContactDetail.setLstUpdTs(LocalDateTime.now());
            return phoneContactDetail;
        }).collect(Collectors.toList());
    }
    return Collections.emptyList();
}

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

/**
 * ???? ??/*from ww w  . j a va  2  s . c  om*/
 * @param companyc    ? companyc   ?? companyc ? ??
 * @param company     ?
 * @return            true or false
 */
@Transactional
public boolean doSaveCompanyInfoMethod(Company companyc, Company company, int userid) {
    int row1;
    if (companyc == null) {
        row1 = companyMapper.addCompany(company);
    } else {
        row1 = companyMapper.modifyCompany(company);
    }
    int row2 = companyMapper.setCompanyStatus("", null, companyMapper.getIdByUserid(userid));
    int row3 = companyMapper.addCompVerify(
            new CompanyVerify("", LocalDateTime.now(), companyMapper.getIdByUserid(userid), userid,
                    "?id=" + session.getAdmin().getId() + ", ??="
                            + session.getAdmin().getUsername() + ", ??="
                            + session.getAdmin().getJobnum()));
    int row4 = userMapper.setUserVerifyStatus("", null, userid);
    if (row1 == 1 && row2 == 1 && row3 == 1 && row4 == 1) {
        mySupplyerService.updateSupplyerForAuditCompanies(company);
        return true;
    }
    throw new BusinessException("??????");
}

From source file:com.zuoxiaolong.blog.cache.service.UserArticleServiceManager.java

/**
 * ???/*from  w w  w  .ja  va  2s  . c o m*/
 *
 * @return
 */
@Cacheable(value = GuavaCacheConfig.BLOG_CACHE, key = "#root.methodName")
public List<ArticleRankResponseDto> getArticlesRank() {
    List<ArticleCategory> articleCategories = articleCategoryServiceManager.getAllArticleCategory();
    if (CollectionUtils.isEmpty(articleCategories))
        return Collections.emptyList();

    List<ArticleRankResponseDto> articleRankResponseDtos = Lists.newArrayList();

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

    Map<String, Object> recommendMap = Maps.newHashMap();
    List<UserArticle> recommendUserArticles;
    List<ArticleRankResponseDataResult> recommendArticleRankResponseDataResultList = Lists.newArrayList();
    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(CacheConstants.ACTION_TYPE_READ);

    Map<String, Object> readMap = Maps.newHashMap();
    List<UserArticle> readUserArticles;
    ArticleRankResponseDataResult readDataResult;
    List<ArticleRankResponseDataResult> readArticleRankResponseDataResultList = Lists.newArrayList();
    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(CacheConstants.ACTION_TYPE_COMMEND);

    Map<String, Object> commendMap = Maps.newHashMap();
    List<UserArticle> commendUserArticles;
    ArticleRankResponseDataResult commendDataResult;
    List<ArticleRankResponseDataResult> commendArticleRankResponseDataResultList = Lists.newArrayList();
    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.fns.grivet.controller.PersistDocumentationTest.java

@Test
// GET (bounded by createdTimeStart and createdTimeEnd)
public void fetchByTimeRange() {
    try {/* ww w  .  j  a v  a 2s  .  co  m*/
        defineType("TestType2");
        createType("TestType2", "TestTypeData2");
        String createdTimeStart = LocalDateTime.now().minusMinutes(15)
                .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        String createdTimeEnd = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        mockMvc.perform(get("/api/v1/type/TestType2").param("createdTimeStart", createdTimeStart)
                .param("createdTimeEnd", createdTimeEnd).contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk()).andExpect(content().json(asArray(payload("TestTypeData2"))));
    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:org.opendatakit.briefcase.operations.Export.java

public static void export(String storageDir, String formid, String fileName, String exportPath,
        Date startDateString, Date endDateString, boolean exportMedia, boolean overwrite,
        Optional<String> pemKeyFile) {
    bootCache(storageDir);/*from   w ww.  jav  a2  s. co  m*/
    BriefcaseFormDefinition formDefinition = null;
    List<BriefcaseFormDefinition> forms = FileSystemUtils.getBriefcaseFormList();
    for (int i = 0; i < forms.size(); i++) {
        BriefcaseFormDefinition x = forms.get(i);
        if (formid.equals(x.getFormId())) {
            formDefinition = x;
            break;
        }
    }

    if (formDefinition == null) {
        LOGGER.error("Form not found");
        return;
    }

    if (formDefinition.isFileEncryptedForm() || formDefinition.isFieldEncryptedForm()) {
        File pemFile;
        if (!pemKeyFile.isPresent()) {
            LOGGER.error("Briefcase action failed: No specified PrivateKey file for encrypted form");
            return;
        }
        pemFile = new File(pemKeyFile.get());
        if (!pemFile.exists()) {
            LOGGER.error("Briefcase action failed: No PrivateKey file for encrypted form");
            return;
        }

        String errorMsg = null;
        boolean success = false;
        for (;;) /* this only executes once... */ {
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(new FileInputStream(pemFile), "UTF-8"));
                PEMReader rdr = new PEMReader(br);
                Object o = rdr.readObject();
                try {
                    rdr.close();
                } catch (IOException e) {
                    // ignore.
                }
                if (o == null) {
                    errorMsg = "The supplied file is not in PEM format.";
                    System.err.println(errorMsg);
                    break;
                }
                PrivateKey privKey;
                if (o instanceof KeyPair) {
                    KeyPair kp = (KeyPair) o;
                    privKey = kp.getPrivate();
                } else if (o instanceof PrivateKey) {
                    privKey = (PrivateKey) o;
                } else {
                    privKey = null;
                }
                if (privKey == null) {
                    errorMsg = "The supplied file does not contain a private key.";
                    System.err.println(errorMsg);
                    break;
                }
                formDefinition.setPrivateKey(privKey);
                success = true;
                break;
            } catch (IOException e) {
                System.err.println("The supplied PEM file could not be parsed.");
                e.printStackTrace();
                break;
            }
        }
        if (!success) {
            EventBus.publish(new ExportProgressEvent(errorMsg, formDefinition));
            EventBus.publish(new ExportFailedEvent(formDefinition));
            return;
        }
    }

    TerminationFuture terminationFuture = new TerminationFuture();
    terminationFuture.reset();
    File dir = new File(exportPath);
    LOGGER.info("exporting to : " + dir.getAbsolutePath());
    ExportToCsv exp = new ExportToCsv(dir, formDefinition, terminationFuture, fileName, exportMedia, overwrite,
            startDateString, endDateString);
    exp.doAction();
    BriefcasePreferences.forClass(ExportPanel.class).put(buildExportDateTimePrefix(formDefinition.getFormId()),
            LocalDateTime.now().format(ISO_DATE_TIME));
}

From source file:com.pawandubey.griffin.Griffin.java

private void initializeConfigurationSettings() throws NumberFormatException, IOException {

    String title = null, author = null, date = null, slug = null, layout = "post", category = null, tags = null;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));

    while (StringUtils.isEmpty(title)) {
        System.out.println("1. title :");
        title = br.readLine();//from  www.  j  av  a 2 s . co  m
    }

    while (StringUtils.isEmpty(author)) {
        System.out.println("2. your name : (default is " + config.getSiteAuthor() + ",press Enter omit!)");
        author = br.readLine();
        if (StringUtils.isBlank(author)) {
            author = config.getSiteAuthor();
        }
    }
    while (StringUtils.isEmpty(slug)) {
        System.out.println("3. url :");
        slug = br.readLine();
    }

    while (StringUtils.isEmpty(category)) {
        System.out.println("4. category : (" + config.getCategories() + ",pick one or create new !):");
        category = br.readLine();
    }
    while (StringUtils.isEmpty(tags)) {
        System.out.println("5. tag : eg: tag1,tag2");
        tags = br.readLine();
    }

    while (StringUtils.isEmpty(date)) {
        System.out.println(
                "6. write date :  (format :" + config.getInputDateFormat() + ",press Enter user today.)");
        date = br.readLine();
        if (StringUtils.isEmpty(date)) {
            date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(config.getInputDateFormat()));
        }
    }

    ;

    Path draftPath = Paths.get(config.getSourceDir())
            .resolve(title.replaceAll("\\s+|;|\\)|\\(|&", "-") + ".markdown");
    String content = postTemplate.replace("#title", title).replace("#date", date).replace("#category", category)
            .replace("#layout", layout).replace("#author", author).replace("#tags", formatTag(tags))
            .replace("#slug", slug);

    try (BufferedWriter bw = Files.newBufferedWriter(draftPath, StandardCharsets.UTF_8)) {
        bw.write(content);
    } catch (IOException ex) {
        Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("draft path [" + draftPath + "]");
    System.out.println("*******************************************************************");
    System.out.println(content);
    System.out.println("*******************************************************************");
    System.out.println("draft path [" + draftPath + "]");

}