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.ccserver.digital.service.CreditCardApplicationExtractionServiceTest.java

@Test
public void ExportExcelAdminTest() throws IOException {
    List<CreditCardApplication> applicationList = new ArrayList<>();
    CreditCardApplication creditCardApplication = new CreditCardApplication();
    creditCardApplication.setFirstName("First Name");
    creditCardApplication.setLastName("Last Name");
    creditCardApplication.setPassportNumber("121213");
    creditCardApplication.setEmail("you@you");
    creditCardApplication.setBusinessStartDate(LocalDateTime.now());
    creditCardApplication.setDateOfIssue(null);
    Phone mobile = new Phone();
    mobile.setCountryCode("+84");
    mobile.setPhoneNumber("98599999999");
    creditCardApplication.setMobile(mobile);
    //creditCardApplication.setLosApplicationId("123GTP");
    creditCardApplication.setSaleAgentId("45678");
    creditCardApplication.setStatus(Status.SubmittedApp);
    creditCardApplication.setSubmittedAppTime(LocalDateTime.of(1992, 1, 10, 0, 0));
    creditCardApplication.setSubmittedDocTime(LocalDateTime.now());
    creditCardApplication.setVerification(LocalDateTime.now());
    creditCardApplication.setCardShipped(LocalDateTime.now());
    creditCardApplication.setCardDelivered(LocalDateTime.now());
    creditCardApplication.setId(1L);//from   w ww .j  ava 2s  . c o m
    applicationList.add(creditCardApplication);
    Date from = new Date();
    Date to = new Date();
    Mockito.when(repository.getApplicationsByTime(from, to)).thenReturn(applicationList);

    byte[] result = ccAppExtractionService.exportExcelAdmin(from, to);
    Assert.assertNotNull(result);
}

From source file:fr.inria.wimmics.coresetimer.CoreseTimer.java

public void writeStatistics() {
    Document doc = null;//from  w ww. java 2  s . c  om
    try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.newDocument();
        Element rootElement = doc.createElement("TestResult");

        Element inputs = doc.createElement("Inputs");

        Element inputFile = doc.createElement("Input");
        Text inputFileText = doc.createTextNode(test.getInput());
        inputFile.appendChild(inputFileText);

        Element request = doc.createElement("Request");
        Text requestText = doc.createTextNode(test.getRequest());
        request.appendChild(requestText);

        Element timestamp = doc.createElement("Timestamp");
        Text timestampText = doc.createTextNode(LocalDateTime.now().toString());
        timestamp.appendChild(timestampText);

        Element[] subElements = { inputFile, request, timestamp };
        for (Element e : subElements) {
            inputs.appendChild(e);
        }

        Element outputs = doc.createElement("Statistics");

        Element statsMemory = doc.createElement("CPU");
        Text statsMemoryText = doc.createTextNode(getStats().toString());
        statsMemory.appendChild(statsMemoryText);

        Element statsMemoryCoreseMem = doc.createElement("Memory");
        Text statsMemoryCoreseMemText = doc.createTextNode(getStatsMemory().toString());
        statsMemoryCoreseMem.appendChild(statsMemoryCoreseMemText);

        Element[] subElements2 = { statsMemory, statsMemoryCoreseMem };
        for (Element e : subElements2) {
            outputs.appendChild(e);
        }

        rootElement.appendChild(inputs);
        rootElement.appendChild(outputs);

        doc.appendChild(rootElement);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult streamResult = new StreamResult(new File(test.getOutputPath()));
        transformer.transform(source, streamResult);
        LOGGER.log(Level.INFO, "Results were written in:", test.getOutputPath());
    } catch (ParserConfigurationException | TransformerException ex) {
        LOGGER.log(Level.INFO, "Error when writing results:", ex.getMessage());
        ex.printStackTrace();
    }

}

From source file:org.apache.nifi.processors.orc.PutORCTest.java

@Test
public void testWriteORCWithAvroLogicalTypes() throws IOException, InitializationException {
    final String avroSchema = IOUtils.toString(
            new FileInputStream("src/test/resources/user_logical_types.avsc"), StandardCharsets.UTF_8);
    schema = new Schema.Parser().parse(avroSchema);
    Calendar now = Calendar.getInstance();
    LocalTime nowTime = LocalTime.now();
    LocalDateTime nowDateTime = LocalDateTime.now();
    LocalDate epoch = LocalDate.ofEpochDay(0);
    LocalDate nowDate = LocalDate.now();

    final int timeMillis = nowTime.get(ChronoField.MILLI_OF_DAY);
    final Timestamp timestampMillis = Timestamp.valueOf(nowDateTime);
    final Date dt = Date.valueOf(nowDate);
    final double dec = 1234.56;

    configure(proc, 10, (numUsers, readerFactory) -> {
        for (int i = 0; i < numUsers; i++) {
            readerFactory.addRecord(i, timeMillis, timestampMillis, dt, dec);
        }/*ww  w.ja v  a  2s. co m*/
        return null;
    });

    final String filename = "testORCWithDefaults-" + System.currentTimeMillis();

    final Map<String, String> flowFileAttributes = new HashMap<>();
    flowFileAttributes.put(CoreAttributes.FILENAME.key(), filename);

    testRunner.setProperty(PutORC.HIVE_TABLE_NAME, "myTable");

    testRunner.enqueue("trigger", flowFileAttributes);
    testRunner.run();
    testRunner.assertAllFlowFilesTransferred(PutORC.REL_SUCCESS, 1);

    final Path orcFile = new Path(DIRECTORY + "/" + filename);

    // verify the successful flow file has the expected attributes
    final MockFlowFile mockFlowFile = testRunner.getFlowFilesForRelationship(PutORC.REL_SUCCESS).get(0);
    mockFlowFile.assertAttributeEquals(PutORC.ABSOLUTE_HDFS_PATH_ATTRIBUTE, orcFile.getParent().toString());
    mockFlowFile.assertAttributeEquals(CoreAttributes.FILENAME.key(), filename);
    mockFlowFile.assertAttributeEquals(PutORC.RECORD_COUNT_ATTR, "10");
    // DDL will be created with field names normalized (lowercased, e.g.) for Hive by default
    mockFlowFile.assertAttributeEquals(PutORC.HIVE_DDL_ATTRIBUTE,
            "CREATE EXTERNAL TABLE IF NOT EXISTS `myTable` (`id` INT, `timemillis` INT, `timestampmillis` TIMESTAMP, `dt` DATE, `dec` DOUBLE) STORED AS ORC");

    // verify we generated a provenance event
    final List<ProvenanceEventRecord> provEvents = testRunner.getProvenanceEvents();
    assertEquals(1, provEvents.size());

    // verify it was a SEND event with the correct URI
    final ProvenanceEventRecord provEvent = provEvents.get(0);
    assertEquals(ProvenanceEventType.SEND, provEvent.getEventType());
    // If it runs with a real HDFS, the protocol will be "hdfs://", but with a local filesystem, just assert the filename.
    Assert.assertTrue(provEvent.getTransitUri().endsWith(DIRECTORY + "/" + filename));

    // verify the content of the ORC file by reading it back in
    verifyORCUsers(orcFile, 10, (x, currUser) -> {
        assertEquals((int) currUser, ((IntWritable) x.get(0)).get());
        assertEquals(timeMillis, ((IntWritable) x.get(1)).get());
        assertEquals(timestampMillis, ((TimestampWritableV2) x.get(2)).getTimestamp().toSqlTimestamp());
        final DateFormat noTimeOfDayDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        noTimeOfDayDateFormat.setTimeZone(TimeZone.getTimeZone("gmt"));
        assertEquals(noTimeOfDayDateFormat.format(dt), ((DateWritableV2) x.get(3)).get().toString());
        assertEquals(dec, ((DoubleWritable) x.get(4)).get(), Double.MIN_VALUE);
        return null;
    });

    // verify we don't have the temp dot file after success
    final File tempOrcFile = new File(DIRECTORY + "/." + filename);
    Assert.assertFalse(tempOrcFile.exists());

    // verify we DO have the CRC file after success
    final File crcAvroORCFile = new File(DIRECTORY + "/." + filename + ".crc");
    Assert.assertTrue(crcAvroORCFile.exists());
}

From source file:org.jspare.jsdbc.JsdbcMockedImpl.java

/**
 * Result fail.// w ww .  j  a v  a  2s  . c  o m
 *
 * @return the result
 */
private Result resultFail() {

    return new Result(Status.FAIL, LocalDateTime.now(), "tid");
}

From source file:grakn.core.daemon.executor.Storage.java

/**
 * Attempt to start Storage and perform periodic polling until it is ready. The readiness check is performed with nodetool.
 * <p>/* w  w w.ja v a 2  s  . c  om*/
 * A {@link GraknDaemonException} will be thrown if Storage does not start after a timeout specified
 * in the 'WAIT_INTERVAL_SECOND' field.
 *
 * @throws GraknDaemonException
 */
private void start() {
    System.out.print("Starting " + DISPLAY_NAME + "...");
    System.out.flush();

    // Consume configuration from Grakn config file into Cassandra config file
    initialiseConfig();

    Future<Executor.Result> result = daemonExecutor.executeAsync(storageCommand(), graknHome.toFile());

    LocalDateTime timeout = LocalDateTime.now().plusSeconds(STORAGE_STARTUP_TIMEOUT_SECOND);

    while (LocalDateTime.now().isBefore(timeout) && !result.isDone()) {
        System.out.print(".");
        System.out.flush();

        if (storageStatus().equals("running")) {
            System.out.println("SUCCESS");
            return;
        }

        try {
            Thread.sleep(WAIT_INTERVAL_SECOND * 1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    try {
        System.out.println("FAILED!");
        System.err.println("Unable to start " + DISPLAY_NAME + ".");
        String errorMessage = "Process exited with code '" + result.get().exitCode() + "': '"
                + result.get().stderr() + "'";
        System.err.println(errorMessage);
        throw new GraknDaemonException(errorMessage);
    } catch (InterruptedException | ExecutionException e) {
        throw new GraknDaemonException(e.getMessage(), e);
    }
}

From source file:demo.admin.controller.UserController.java

@RequestMapping("/user/verifyreject")
public Object companyVerifyreject(int companyId, String remarks) {
    Company company = companyMapper.getCompanyById(companyId);
    if (company == null)
        throw new NotFoundException();
    companyMapper.setCompVerify("", session.getAdmin().getUsername(), LocalDateTime.now(),
            remarks, companyId);/* ww w. ja va  2 s .  c  o  m*/
    companyMapper.setCompanyStatus("", remarks, companyId);
    userMapper.setUserVerifyStatus("", company.getUserid());
    return true;
}

From source file:edu.zipcloud.cloudstreetmarket.api.services.StockProductServiceOnlineImpl.java

private void updateChartStockFromYahoo(StockProduct stock, ChartType type, ChartHistoSize histoSize,
        ChartHistoMovingAverage histoAverage, ChartHistoTimeSpan histoPeriod, Integer intradayWidth,
        Integer intradayHeight) {

    Preconditions.checkNotNull(stock, "stock must not be null!");
    Preconditions.checkNotNull(type, "ChartType must not be null!");

    String guid = AuthenticationUtil.getPrincipal().getUsername();
    SocialUser socialUser = usersConnectionRepository.getRegisteredSocialUser(guid);
    if (socialUser == null) {
        return;//from  w  ww  .j a  v a  2s  .  co m
    }
    String token = socialUser.getAccessToken();
    Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

    if (connection != null) {
        byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(stock.getId(), type,
                histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm");
        LocalDateTime dateTime = LocalDateTime.now();
        String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230"
        String imageName = stock.getId().toLowerCase() + "_" + type.name().toLowerCase() + "_"
                + formattedDateTime + ".png";
        String pathToYahooPicture = env.getProperty("user.home").concat(env.getProperty("pictures.yahoo.path"))
                .concat(File.separator + imageName);

        try {
            Path newPath = Paths.get(pathToYahooPicture);
            Files.write(newPath, yahooChart, StandardOpenOption.CREATE);
        } catch (IOException e) {
            throw new Error("Storage of " + pathToYahooPicture + " failed", e);
        }

        ChartStock chartStock = new ChartStock(stock, type, histoSize, histoAverage, histoPeriod, intradayWidth,
                intradayHeight, pathToYahooPicture);
        chartStockRepository.save(chartStock);
    }
}

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

@Override
public void saveWsdl(SubsystemId subsystemId, ServiceId serviceId, String wsdlString) {
    Assert.notNull(subsystemId);//from   ww  w .  ja va 2s. c  o  m
    Assert.notNull(serviceId);
    Service oldService;
    // bit ugly this one, would be a little cleaner if
    // https://jira.spring.io/browse/DATAJPA-209 was resolved
    if (serviceId.getServiceVersion() == null) {
        oldService = serviceRepository.findActiveNullVersionByNaturalKey(subsystemId.getXRoadInstance(),
                subsystemId.getMemberClass(), subsystemId.getMemberCode(), subsystemId.getSubsystemCode(),
                serviceId.getServiceCode());
    } else {
        oldService = serviceRepository.findActiveByNaturalKey(subsystemId.getXRoadInstance(),
                subsystemId.getMemberClass(), subsystemId.getMemberCode(), subsystemId.getSubsystemCode(),
                serviceId.getServiceCode(), serviceId.getServiceVersion());
    }
    if (oldService == null) {
        throw new IllegalStateException("service " + serviceId + " not found!");
    }
    LocalDateTime now = LocalDateTime.now();
    Wsdl wsdl = new Wsdl();
    wsdl.setData(wsdlString);
    Wsdl oldWsdl = oldService.getWsdl();
    if (oldWsdl == null) {
        wsdl.initializeExternalId();
        wsdl.getStatusInfo().setTimestampsForNew(now);
        oldService.setWsdl(wsdl);
        wsdl.setService(oldService);
        wsdlRepository.save(wsdl);
    } else {
        if (oldWsdl.getStatusInfo().isRemoved()) {
            // resurrect
            oldWsdl.setData(wsdl.getData());
            oldWsdl.getStatusInfo().setChanged(now);
            oldWsdl.getStatusInfo().setRemoved(null);
            oldWsdl.getStatusInfo().setFetched(now);
        } else {
            // update existing
            boolean wsdlChanged = !oldWsdl.getData().equals(wsdl.getData());
            if (wsdlChanged) {
                oldWsdl.getStatusInfo().setChanged(now);
                oldWsdl.setData(wsdl.getData());
            }
            oldWsdl.getStatusInfo().setFetched(now);
        }
    }
}

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

@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true)
public User updatePassword(PasswordUpdateRequest request, PasswordResetToken passwordResetToken) {
    User user = userRepository.findOneForUpdateById(request.getUserId());
    if (user == null) {
        throw new IllegalArgumentException("The user does not exist");
    }/*w w  w .  j  a  v  a2  s.c  o m*/
    PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
    user.setLoginPassword(passwordEncoder.encode(request.getPassword()));
    user.setUpdatedAt(LocalDateTime.now());
    user.setUpdatedBy(passwordResetToken.getUser().toString());
    user = userRepository.saveAndFlush(user);

    passwordResetTokenRepository.delete(passwordResetToken);

    try {
        Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
        String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

        ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
        if (blog.isMultiLanguage()) {
            builder.path("/{language}");
        }
        builder.path("/login");

        Map<String, Object> urlVariables = new LinkedHashMap<>();
        urlVariables.put("language", request.getLanguage());
        urlVariables.put("token", passwordResetToken.getToken());
        String loginLink = builder.buildAndExpand(urlVariables).toString();

        Context ctx = new Context(LocaleContextHolder.getLocale());
        ctx.setVariable("passwordResetToken", passwordResetToken);
        ctx.setVariable("resetLink", loginLink);

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
        message.setSubject(MessageFormat.format(
                messageSourceAccessor.getMessage("PasswordChangedSubject", LocaleContextHolder.getLocale()),
                blogTitle));
        message.setFrom(mailProperties.getProperties().get("mail.from"));
        message.setTo(passwordResetToken.getEmail());

        String htmlContent = templateEngine.process("password-changed", ctx);
        message.setText(htmlContent, true); // true = isHtml

        mailSender.send(mimeMessage);
    } catch (MessagingException e) {
        throw new ServiceException(e);
    }

    return user;
}

From source file:org.jspare.jsdbc.JsdbcMockedImpl.java

@Override
public CountResult count(Query query) throws JsdbcException {
    try {//from  ww w .  j a v a2  s  .c om
        CountResult result = new CountResult(Status.SUCCESS, LocalDateTime.now(), "tid", 1);
        return result;
    } catch (SerializationException e) {

        throw new JsdbcException(e);
    }
}