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:cz.muni.fi.editor.database.test.RequestDAOTest.java

@Test
public void create() {
    Request request = new Request();
    request.setRequestDate(LocalDateTime.now());
    request.setRequestor(userDAO.getById(8L));
    request.setAction("create");
    request.setClazz("cz.muni.fi.editor.api.dto.OrganizationDTO");
    request.setTargetId(6L);/*w  ww  .  j  a va  2  s .c om*/
    request.setState(RequestState.PENDING);

    requestDAO.create(request);

    Assert.assertNotNull(request.getId());
}

From source file:io.yields.math.framework.kpi.ScoreDAO.java

/**
 * Persists a #{ScoreResult}.//  www  . j a  va  2 s .  c  o  m
 * If a system property yields.score.path is found, this result is written to that location.
 * Otherwise, this result is written to the path defined by the system property java.io.tmpDir.
 *
 * @param scoreResult Score Result to persist
 */
public static void save(ScoreResult scoreResult) {

    File destinationFolder = getRootFolder();

    if (!destinationFolder.exists()) {
        try {
            forceMkdir(destinationFolder);
        } catch (IOException ioe) {
            throw new IllegalStateException(format("Destination folder for scores could not be created at %s",
                    destinationFolder.getAbsolutePath()), ioe);
        }
    }

    if (!destinationFolder.isDirectory()) {
        throw new IllegalStateException(
                format("Destination path for scores %s is not a folder", destinationFolder.getAbsolutePath()));
    }

    if (!destinationFolder.canWrite()) {
        throw new IllegalStateException(format("Destination folder for scores %s is not writable",
                destinationFolder.getAbsolutePath()));
    }

    ObjectMapper jsonMapper = getObjectMapper();
    File destinationFile = new File(destinationFolder, scoreResult.getName().replaceAll("[^a-zA-Z0-9]", "_")
            + "_" + DATE_TIME_FORMATTER.format(LocalDateTime.now()) + "." + FILE_SUFFIX);
    try {
        scoreResult.setTimestamp(ZonedDateTime.now());
        jsonMapper.writeValue(destinationFile, scoreResult);
        logger.info("Written score result to {}", destinationFile.getAbsolutePath());
    } catch (IOException ioe) {
        logger.error("Could not write score result to file " + destinationFile.getAbsolutePath(), ioe);
        throw new IllegalStateException(
                format("Could not write score file at %s", destinationFile.getAbsolutePath()), ioe);
    }

}

From source file:com.esri.geoevent.test.tools.RunTcpInBdsOutTest.java

public void send(String server, Integer port, Long numEvents, Integer rate, String data_file) {

    BufferedReader br = null;//  ww  w. java  2s  .co  m
    ArrayList<String> lines = new ArrayList<>();
    LocalDateTime st = null;

    try {

        // Read the file into String array
        br = new BufferedReader(new FileReader(data_file));

        String line = null;
        while ((line = br.readLine()) != null) {
            lines.add(line);
        }

        Socket sckt = new Socket(server, port);
        OutputStream os = sckt.getOutputStream();

        Integer cnt = 0;

        st = LocalDateTime.now();

        Double ns_delay = 1000000000.0 / (double) rate;

        long ns = ns_delay.longValue();
        if (ns < 0) {
            ns = 0;
        }

        int i = 0;
        int j = 0;

        while (i < numEvents) {
            i++;
            j++;
            if (j >= lines.size()) {
                j = 0;
            }
            line = lines.get(j) + "\n";

            final long stime = System.nanoTime();

            long etime = 0;
            do {
                etime = System.nanoTime();
            } while (stime + ns >= etime);

            os.write(line.getBytes());
            os.flush();

        }

        LocalDateTime et = LocalDateTime.now();
        if (st != null) {
            et = LocalDateTime.now();

            Duration delta = Duration.between(st, et);

            Double elapsed_seconds = (double) delta.getSeconds() + delta.getNano() / 1000000000.0;

            send_rate = (double) numEvents / elapsed_seconds;
        }

        sckt.close();
        os = null;

    } catch (Exception e) {
        System.err.println(e.getMessage());
        send_rate = -1.0;
    } finally {
        try {
            br.close();
        } catch (Exception e) {
            //
        }

        this.send_rate = send_rate;

    }

}

From source file:com.streamsets.pipeline.stage.processor.parser.TestDataParserProcessor.java

@Test
public void testSyslogParsing() throws Exception {
    int priority = 17;
    int facility = priority / 8;
    int severity = priority % 8;
    LocalDateTime date = LocalDateTime.now().withNano(0);
    String host = "1.2.3.4";
    String rest = "Nothing interesting happened.";

    String inputFieldPath = "input";
    String outputFieldPath = "/output";

    String syslogMsg = String.format("<%d>%s %s %s", priority,
            DateTimeFormatter.ofPattern("MMM dd HH:mm:ss").format(date), host, rest);

    DataParserConfig configs = new DataParserConfig();
    configs.dataFormat = DataFormat.SYSLOG;
    final DataParserFormatConfig dataParserFormatConfig = new DataParserFormatConfig();
    configs.dataFormatConfig = dataParserFormatConfig;
    configs.fieldPathToParse = "/" + inputFieldPath;
    configs.parsedFieldPath = outputFieldPath;

    DataParserProcessor processor = new DataParserProcessor(configs);

    final String outputLane = "out";

    ProcessorRunner runner = new ProcessorRunner.Builder(DataParserDProcessor.class, processor)
            .addOutputLane(outputLane).setOnRecordError(OnRecordError.TO_ERROR).build();
    Map<String, Field> map = new HashMap<>();
    map.put(inputFieldPath, Field.create(syslogMsg));
    Record record = RecordCreator.create();
    record.set(Field.create(map));
    List<Record> input = new ArrayList<>();
    input.add(record);/* w w  w . jav  a 2s  .c  o  m*/
    try {
        runner.runInit();
        StageRunner.Output output = runner.runProcess(input);
        assertTrue(output.getRecords().containsKey(outputLane));
        final List<Record> records = output.getRecords().get(outputLane);
        assertEquals(1, records.size());
        assertTrue(records.get(0).has(outputFieldPath));
        assertEquals(Field.Type.MAP, records.get(0).get(outputFieldPath).getType());
        Map<String, Field> syslogFields = records.get(0).get(outputFieldPath).getValueAsMap();
        assertThat(syslogFields, hasKey(SyslogMessage.FIELD_SYSLOG_PRIORITY));
        assertThat(syslogFields.get(SyslogMessage.FIELD_SYSLOG_PRIORITY), fieldWithValue(priority));
        assertThat(syslogFields.get(SyslogMessage.FIELD_SYSLOG_FACILITY), fieldWithValue(facility));
        assertThat(syslogFields.get(SyslogMessage.FIELD_SYSLOG_SEVERITY), fieldWithValue(severity));
        assertThat(syslogFields.get(SyslogMessage.FIELD_HOST), fieldWithValue(host));
        assertThat(syslogFields.get(SyslogMessage.FIELD_REMAINING), fieldWithValue(rest));
        assertThat(syslogFields.get(SyslogMessage.FIELD_RAW), fieldWithValue(syslogMsg));
        assertThat(syslogFields.get(SyslogMessage.FIELD_TIMESTAMP),
                fieldWithValue(date.toInstant(ZoneOffset.UTC).toEpochMilli()));

    } finally {
        runner.runDestroy();
    }
}

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

/**
 * Test of removePost method, of class BlogDaoInMemImpl.
 *//*from ww  w. ja  va 2s  .co  m*/
@Test
public void testRemovePost() {
    System.out.println("removePost");
    Post post1 = new Post("Supergirl", "Clark Kent", "hot new cousin saves city", "super, girl",
            LocalDateTime.now().toString(), "12-30-2015");
    Post post2 = new Post("Supeergirl", "Clark Kentd", "hot5 new cousin saves city", "super, girl",
            LocalDateTime.now().toString(), "12-30-2015");
    Post post3 = new Post("Superfgirl", "Clark Kentd", "hot 4new cousin saves city", "super, girl",
            LocalDateTime.now().toString(), "12-30-2015");
    BlogDaoInMemImpl instance = new BlogDaoInMemImpl();
    instance.addPost(post1);
    System.out.println(post1.getPostID());
    instance.addPost(post2);
    System.out.println(post2.getPostID());
    instance.addPost(post3);
    System.out.println(post3.getPostID());
    instance.removePost(post2.getPostID());
    assertEquals(2, instance.getBlogPosts().size());
}

From source file:io.curly.tagger.listener.DefaultTagEventListener.java

@RabbitListener(queues = "tag.queue")
public void onReceive(@Nullable Message message) throws IOException {
    if (message != null) {
        TagMessage[] values = objectMapper.readValue(message.getBody(), TagMessage[].class);
        Set<TagMessage> tagMessages = new HashSet<>(Arrays.asList(values));
        log.info("Received messages {} on tag.queue, notifying Bus...", tagMessages);
        eventBus.notify("tag.bus", Event.wrap(tagMessages));
    } else {/*ww w.j ava2 s  .  c  o  m*/
        log.warn("Cannot process null message occurred on " + LocalDateTime.now());
    }
}

From source file:ca.qhrtech.controllers.UserController.java

@ApiMethod(description = "Add a new User to BGL")
@RequestMapping(value = "/user", method = RequestMethod.POST)
public ResponseEntity<BGLUser> createUser(@RequestBody BGLUser user) {
    if (!userService.doesUserExist(user)) {
        user.setJoinDate(LocalDateTime.now());
        String hash = new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(hash);//from   ww  w  .j  a v  a  2s.co m
        BGLUser newUser = userService.saveUser(user);
        return new ResponseEntity<>(newUser, HttpStatus.CREATED);
    }
    return new ResponseEntity<>(HttpStatus.CONFLICT);
}

From source file:org.apdplat.superword.system.AntiRobotFilter.java

public static void main(String[] args) {
    LocalDateTime timePoint = LocalDateTime.now().minusDays(1);
    String date = SIMPLE_DATE_FORMAT.format(Date.from(timePoint.atZone(ZoneId.systemDefault()).toInstant()));
    System.out.println(date);//  w  ww .j  ava2s. c  om
}

From source file:io.yields.math.framework.kpi.ExplorerDAO.java

private static File getRootFolder(String group) {
    if (exportFolder == null) {
        exportFolder = new File(getTempDirectory(), DATE_TIME_FORMATTER.format(LocalDateTime.now()));
    }/*w w  w  . j a  va2  s .  c o m*/
    return new File(exportFolder, group);
}

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

public Comment createComment(CommentCreateRequest request, AuthorizedUser createdBy) {
    Post post = postRepository.findOneByIdAndLanguage(request.getPostId(),
            request.getBlogLanguage().getLanguage());
    if (post == null) {
        throw new ServiceException("Post was not found [" + request.getPostId() + "]");
    }/*from w  w  w  .ja v a2  s .  c o m*/

    User author = userRepository.findOneById(request.getAuthorId());

    LocalDateTime now = LocalDateTime.now();
    Comment comment = new Comment();
    comment.setPost(post);
    comment.setAuthor(author);
    comment.setAuthorName(author.toString());
    comment.setDate(request.getDate());
    comment.setContent(request.getContent());
    comment.setApproved(request.isApproved());

    comment.setCreatedAt(now);
    comment.setCreatedBy(createdBy.toString());
    comment.setUpdatedAt(now);
    comment.setUpdatedBy(createdBy.toString());

    return commentRepository.saveAndFlush(comment);
}