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.swcguild.capstoneproject.dao.BlogDaoDbImplTest.java

/**
 * Test of getPostById method, of class BlogDaoDbImpl.
 *//*from w w  w .j  a v  a  2s .  c  om*/
@Test
public void testGetPostById() {
    System.out.println("getPostById");
    Post expResult = new Post("Supergirl", "Clark Kent", "hot new cousin saves city", "super, girl",
            LocalDateTime.now().toString(), "2015-12-30");
    dao.addPost(expResult);
    int postId = expResult.getPostID();
    Post result = dao.getPostById(postId);
    assertTrue(
            expResult.getAuthor().equals(result.getAuthor()) && expResult.getTitle().equals(result.getTitle()));
}

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

@Override
protected Operation initDb() {
    final Project project1 = new Project(1, "Project1", false, false);
    final Source source1 = new Source(1, "Source1", "http://www.source1.de/", true);
    final Crawling crawling1 = new Crawling(1, project1.getId());
    final NamedEntity namedEntity = new NamedEntity(1, "NamedEntity");
    final LocalDateTime now = LocalDateTime.now();
    // Document1 with download success
    final LocalDateTime published1 = now.minusDays(1);
    final Document document1 = new Document(1, crawling1.getId(), source1.getId()).setTitle("Title1")
            .setUrl("http://www.document1.de/").setDescription("Description1").setPublished(published1)
            .setDownloaded(now).setState(DocumentProcessingState.DOWNLOADED).setStatusCode(200);
    final RawContent rawContent1 = new RawContent(document1.getId(), "RawContent1");
    final CleanedContent cleanedContent1 = new CleanedContent(document1.getId(), "Outdated CleanedContent1");
    final StemmedContent stemmedContent1 = new StemmedContent(document1.getId(), "Outdated StemmedContent1");
    final NamedEntityOccurrence namedEntityOccurrence1 = new NamedEntityOccurrence(1, namedEntity.getId(),
            namedEntity.getId(), NamedEntityType.MISC, 1, document1.getId());
    // Document2 with failed download
    final LocalDateTime published2 = now.minusDays(2);
    final Document document2 = new Document(2, crawling1.getId(), source1.getId()).setTitle("Title2")
            .setUrl("http://www.document2.de/").setDescription("Description2").setPublished(published2)
            .setDownloaded(now).setState(DocumentProcessingState.DOWNLOAD_ERROR).setStatusCode(400);
    final RawContent rawContent2 = new RawContent(document2.getId(), "Outdated RawContent2");
    final CleanedContent cleanedContent2 = new CleanedContent(document2.getId(), "Outdated CleanedContent2");
    final StemmedContent stemmedContent2 = new StemmedContent(document2.getId(), "Outdated StemmedContent3");
    final NamedEntityOccurrence namedEntityOccurrence2 = new NamedEntityOccurrence(2, namedEntity.getId(),
            namedEntity.getId(), NamedEntityType.MISC, 1, document2.getId());

    return sequenceOf(CommonOperations.DELETE_ALL_FOR_DATAMESSIE,
            sequenceOf(insertIntoProject(project1), insertIntoSource(source1), insertIntoCrawling(crawling1),
                    insertIntoNamedEntity(namedEntity), insertIntoDocument(document1),
                    insertIntoRawContent(rawContent1), insertIntoCleanedContent(cleanedContent1),
                    insertIntoStemmedContent(stemmedContent1),
                    insertIntoNamedEntityOccurrence(namedEntityOccurrence1), insertIntoDocument(document2),
                    insertIntoRawContent(rawContent2), insertIntoCleanedContent(cleanedContent2),
                    insertIntoStemmedContent(stemmedContent2),
                    insertIntoNamedEntityOccurrence(namedEntityOccurrence2)));
}

From source file:org.jboss.as.test.manualmode.deployment.DeploymentScannerUnitTestCase.java

@Test
public void testStartup() throws Exception {
    final Path oneDeployed = deployDir.resolve(JAR_ONE + ".deployed");
    final Path twoFailed = deployDir.resolve(JAR_TWO + ".failed");
    container.start();/*from   w w w  .  ja  va2 s. co m*/
    try {
        client = TestSuiteEnvironment.getModelControllerClient();
        //set the logging to debug
        addDebugDeploymentLogger();
        try {
            final Path deploymentOne = deployDir.resolve(JAR_ONE);
            final Path deploymentTwo = deployDir.resolve(JAR_TWO);

            createDeployment(deploymentOne, "org.jboss.modules");
            createDeployment(deploymentTwo, "non.existing.dependency");
            addDeploymentScanner(0, false);
            try {
                // Wait until deployed ...
                long timeout = System.currentTimeMillis() + TIMEOUT;
                while (!(exists(DEPLOYMENT_ONE) && exists(DEPLOYMENT_TWO))
                        && System.currentTimeMillis() < timeout) {
                    Thread.sleep(100);
                }
                Assert.assertTrue(exists(DEPLOYMENT_ONE));
                Assert.assertEquals("OK", deploymentState(DEPLOYMENT_ONE));
                Assert.assertTrue(exists(DEPLOYMENT_TWO));
                Assert.assertEquals("FAILED", deploymentState(DEPLOYMENT_TWO));
                Assert.assertTrue(Files.exists(oneDeployed));
                Assert.assertTrue(Files.exists(twoFailed));

                ModelNode rollBackOnBoot = Util.getWriteAttributeOperation(
                        PathAddress.parseCLIStyleAddress("/subsystem=deployment-scanner/scanner=testScanner"),
                        "runtime-failure-causes-rollback", true);
                ModelNode result = executeOperation(rollBackOnBoot);
                assertEquals("Unexpected outcome of rollbacking the test deployment scanner: " + rollBackOnBoot,
                        ModelDescriptionConstants.SUCCESS, result.get(OUTCOME).asString());

                // Restart ...
                client.close();
                container.stop();
                container.start();
                client = TestSuiteEnvironment.getModelControllerClient();

                // Wait until started ...
                timeout = System.currentTimeMillis() + TIMEOUT;
                while (!isRunning() && System.currentTimeMillis() < timeout) {
                    Thread.sleep(10);
                }

                Assert.assertTrue(Files.exists(oneDeployed));
                Assert.assertTrue(Files.exists(twoFailed));

                Assert.assertTrue(exists(DEPLOYMENT_ONE));
                Assert.assertEquals("OK", deploymentState(DEPLOYMENT_ONE));

                timeout = System.currentTimeMillis() + TIMEOUT;
                while (exists(DEPLOYMENT_TWO) && System.currentTimeMillis() < timeout) {
                    Thread.sleep(10);
                }
                Assert.assertFalse(
                        "Deployment two should exist at " + TIME_FORMATTER.format(LocalDateTime.now()),
                        exists(DEPLOYMENT_TWO));
                ModelNode disableScanner = Util.getWriteAttributeOperation(
                        PathAddress.parseCLIStyleAddress("/subsystem=deployment-scanner/scanner=testScanner"),
                        "scan-interval", 300000);
                result = executeOperation(disableScanner);
                assertEquals("Unexpected outcome of disabling the test deployment scanner: " + disableScanner,
                        ModelDescriptionConstants.SUCCESS, result.get(OUTCOME).asString());

                final ModelNode undeployOp = Util.getEmptyOperation(DeploymentUndeployHandler.OPERATION_NAME,
                        DEPLOYMENT_ONE.toModelNode());
                result = executeOperation(undeployOp);
                assertEquals("Unexpected outcome of undeploying deployment one: " + undeployOp,
                        ModelDescriptionConstants.SUCCESS, result.get(OUTCOME).asString());
                Assert.assertTrue(exists(DEPLOYMENT_ONE));
                Assert.assertEquals("STOPPED", deploymentState(DEPLOYMENT_ONE));

                timeout = System.currentTimeMillis() + TIMEOUT;

                while (Files.exists(oneDeployed) && System.currentTimeMillis() < timeout) {
                    Thread.sleep(10);
                }
                Assert.assertFalse(Files.exists(oneDeployed));
            } finally {
                removeDeploymentScanner();
                removeDebugDeploymentLogger();
            }

        } finally {
            StreamUtils.safeClose(client);
        }
    } finally {
        container.stop();
    }
}

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

@RequestMapping("/user/verifypass")
public Object companyVerifyPass(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 . j  a v  a  2  s .  c  o  m
    companyMapper.setCompanyStatus("", remarks, companyId);
    userMapper.setUserVerifyStatus("", company.getUserid());
    companyMapper.addCompVerSus(new CompVerSus(company.getName(), company.getAddress(), company.getPhone(),
            company.getFax(), company.getLegalperson(), company.getBusinesslicense(),
            company.getIdentificationnumber(), company.getOrganizationcode(), company.getOperatinglicense(),
            company.getUserid(), company.getLegalpersonname(), company.getAccount(), company.getOpeningbank()));
    return true;
}

From source file:com.ikanow.aleph2.example.flume_harvester.services.FlumeHarvesterSink.java

@Override
public Status process() throws EventDeliveryException {
    Status status = null;/*from   w  ww.ja  va  2s .com*/

    //TODO (ALEPH-10): handy to know: there's a timeout that appears to occur, so can log a heartbeat every N seconds and use in the poll freq to ensure this thread hasn't crashed...
    //TODO (ALEPH-10): also have a log the first time an error occurs, and maybe hourly log messages reporting data sizes

    // Start transaction
    final Channel ch = getChannel();
    final Transaction txn = ch.getTransaction();
    txn.begin();
    try {
        // This try clause includes whatever Channel operations you want to do

        final Event event = ch.take();

        final Optional<JsonNode> maybe_json_event = getEventJson(event, _config)
                // Extra step
                .map(json -> _time_field.filter(tf -> !json.has(tf)) // (ie filter out JSON objects with the timestamp field, those are passed unchanged by the orElse 
                        .<JsonNode>map(tf -> ((ObjectNode) json).put(tf, LocalDateTime.now().toString())) // put the timestamp field in
                        .orElse(json));

        maybe_json_event.ifPresent(json_event -> {
            if (_config.map(cfg -> cfg.output()).map(out -> out.direct_output()).isPresent()) {
                this.directOutput(json_event, _config.get(), _bucket);
            } else {
                if (_streaming) {
                    _context.sendObjectToStreamingPipeline(Optional.empty(), Either.left(json_event));
                }
                if (_batch) {
                    this.directOutput(json_event, _BATCH_CONFIG, _bucket);
                }
            }
        });

        txn.commit();
        status = Status.READY;
    } catch (Throwable t) {
        //DEBUG
        //_logger.warn("Error", t);

        txn.rollback();

        // Log exception, handle individual exceptions as needed

        status = Status.BACKOFF;

        // re-throw all Errors
        if (t instanceof Error) {
            throw (Error) t;
        }
    } finally {
        txn.close();
    }
    return status;
}

From source file:com.doctor.esper.reference_5_2_0.Chapter21Performance.java

/**
 * 21.2.35. Query Planning Index Hints/*w w  w . j  a v  a 2  s.  c o  m*/
 * 
 * @see http://www.espertech.com/esper/release-5.2.0/esper-reference/html_single/index.html#perf-tips-25b
 * 
 *      ? @Hint('index(httpLogWinLength100ForIndex, bust)')bustMultiple indexes can be listed separated by comma (,).
 * 
 */
@Test
public void test_Query_Planning() {
    HttpLog httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com",
            "userAgent", LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(2, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(3, UUID.randomUUID().toString(), "www.baidu.com/tieba_son", "www.baidu.com",
            "userAgent", LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(4, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(6, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(8, UUID.randomUUID().toString(), "www.baidu.com/tieba_son", "www.baidu.com",
            "userAgent", LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);

    Stopwatch stopwatch = Stopwatch.createStarted();
    List<HttpLog> list = httpLogWinLength100Query
            .prepareQueryWithParameters(Chapter21Performance::httpLogMapRow, "www.baidu.com/tieba_son", 2, 10);
    System.out.println(stopwatch.elapsed(TimeUnit.MICROSECONDS));
    stopwatch.stop();
    assertThat(list.size(), equalTo(2));
    System.out.println(list);
}

From source file:com.codeabovelab.dm.cluman.job.AbstractJobInstance.java

private SafeCloseable statusChanged(JobStatus expected, JobStatus status, Throwable e) {
    JobInfo old = this.infoRef.get();
    if (expected == null) {
        expected = old.getStatus();/*from  w  w  w .ja  v a2 s . c o m*/
    }
    while (true) {
        JobInfo.Builder jib = JobInfo.builder().from(old);
        if (jib.getStatus() == expected) {
            jib.status(status);
        }
        if (status.isEnd()) {
            jib.setEndTime(LocalDateTime.now());
        }
        if (status == JobStatus.STARTED) {
            jib.setStartTime(LocalDateTime.now());
        }
        JobInfo newInfo = jib.build();
        boolean change = setInfo(old, newInfo);
        if (change) {
            return () -> sendEvent(new JobEvent(newInfo, null, e));
        }
        old = this.infoRef.get();
    }
}

From source file:com.qq.tars.service.config.ConfigService.java

@Transactional(rollbackFor = Exception.class)
public ConfigFile updateConfigFile(UpdateConfigFile params) {
    ConfigFile configFile = configMapper.loadConfigFile(params.getId());
    configFile.setConfig(params.getConfig());
    configFile.setPosttime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    configMapper.updateConfigFile(configFile);

    ConfigFileHistory history = new ConfigFileHistory();
    history.setConfigId(configFile.getId());
    history.setReason(params.getReason());
    history.setContent(configFile.getConfig());
    history.setPosttime(configFile.getPosttime());
    configMapper.insertConfigFileHistory(history);

    return configFile;
}

From source file:de.decoit.siemgui.service.TicketServiceImpl.java

/**
 * Create a new ticket for a specific incident.
 *
 * @param inc Incident to create a ticket for
 * @return The created ticket/*from  w w w.ja v a2 s  .c o m*/
 *
 * @throws ExternalServiceException if an error occurs while accessing the external service
 */
private Ticket createTicketForIncident(Incident inc) throws ExternalServiceException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating ticket for incident ID " + inc.getId());
    }

    LocalDateTime dueOn = inc.getTimestamp();
    switch (inc.getThreatLevel()) {
    case LOW:
        dueOn = dueOn.plus(sysConf.getThreatLevelLowDueIn());
        break;
    case MEDIUM:
        dueOn = dueOn.plus(sysConf.getThreatLevelMedDueIn());
        break;
    case HIGH:
        dueOn = dueOn.plus(sysConf.getThreatLevelHighDueIn());
        break;
    default:
        throw new IllegalStateException("No thread level calculated on incident");
    }

    NewTicket tmpTicket = new NewTicket();
    TicketQueue queue = ticketQueueDao.getTicketQueueDetails(sysConf.getSiemTicketQueueName(), authSysUser);

    StringBuilder sb = new StringBuilder("[Incident ");
    sb.append(inc.getId());
    sb.append("] ");
    sb.append(inc.getName());

    StringBuilder sbText = new StringBuilder("[p]");
    sbText.append(inc.getDescription());
    sbText.append("[/p]");

    if (!StringUtils.isBlank(inc.getRecommendation())) {
        sbText.append("[p]");
        sbText.append(inc.getRecommendation());
        sbText.append("[/p]");
    }

    //      for(IncidentRecommendation iRec : inc.getRecommendations()) {
    //         StringBuilder sbRec = new StringBuilder("[p]");
    //         sbRec.append(iRec.getRecommendation());
    //         sbRec.append("[/p]");
    //
    //         sbText.append(sbRec);
    //      }

    tmpTicket.setTitle(sb.toString());
    tmpTicket.setQueue(queue);
    tmpTicket.setText(sbText.toString());
    tmpTicket.setRequestor(authSysUser.getUsername());
    tmpTicket.setStarts(LocalDateTime.now());
    tmpTicket.setIncidentId(inc.getId());
    tmpTicket.setRisk(inc.getRisk());
    tmpTicket.setDueOn(dueOn);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Ticket recommendation text: " + tmpTicket.getText());
    }

    long newId = ticketDao.createTicket(tmpTicket, authSysUser);

    return ticketDao.getTicketDetails(newId, authSysUser);
}

From source file:org.talend.dataprep.transformation.actions.date.ComputeTimeSince.java

private static LocalDateTime parseSinceDateIfConstant(Map<String, String> parameters) {
    String mode = parameters.containsKey(SINCE_WHEN_PARAMETER) ? parameters.get(SINCE_WHEN_PARAMETER)
            : NOW_SERVER_SIDE_MODE;/*from w ww  .j a  v a 2 s  .  c o  m*/

    LocalDateTime since;
    switch (mode) {
    case SPECIFIC_DATE_MODE:
        try {
            since = LocalDateTime.parse(parameters.get(SPECIFIC_DATE_PARAMETER), DEFAULT_FORMATTER);
        } catch (DateTimeException e) {
            LOGGER.info("Error parsing input date. The front-end might have supplied a corrupted value.", e);
            since = null;
        }
        break;
    case OTHER_COLUMN_MODE:
        since = null; // It will be computed in apply
        break;
    case NOW_SERVER_SIDE_MODE:
    default:
        since = LocalDateTime.now();
        break;
    }
    return since;
}