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.fns.grivet.service.NamedQueryServiceSelectTest.java

@Test
public void testCreateThenGetIncorrectParamsSupplied() throws IOException {
    Assertions.assertThrows(IllegalArgumentException.class, () -> {
        Resource r = resolver.getResource("classpath:TestSelectQuery.json");
        String json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
        NamedQuery namedQuery = objectMapper.readValue(json, NamedQuery.class);
        namedQueryService.create(namedQuery);

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("timedCreated", LocalDateTime.now().plusDays(1).toString());
        namedQueryService.get("getAttributesCreatedBefore", params);
    });//w ww .j av  a 2  s .  c om
}

From source file:org.jgrades.backup.creator.EncryptArchiveJob.java

private void updateEventType(BackupEvent event, BackupEventType backupEventType) {
    event.setEventType(backupEventType);
    event.setEndTime(LocalDateTime.now());
    backupEventRepository.save(event);
}

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

public PasswordResetToken createPasswordResetToken(PasswordResetTokenCreateRequest request) {
    User user = userRepository.findOneByEmail(request.getEmail());
    if (user == null) {
        throw new EmailNotFoundException();
    }/*from   w  w  w.  j a  v  a2 s .  co m*/

    LocalDateTime now = LocalDateTime.now();
    PasswordResetToken passwordResetToken = new PasswordResetToken();
    passwordResetToken.setUser(user);
    passwordResetToken.setEmail(user.getEmail());
    passwordResetToken.setExpiredAt(now.plusHours(24));
    passwordResetToken.setCreatedAt(now);
    passwordResetToken.setCreatedBy(user.toString());
    passwordResetToken.setUpdatedAt(now);
    passwordResetToken.setUpdatedBy(user.toString());
    passwordResetToken = passwordResetTokenRepository.saveAndFlush(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("/password-reset");
        builder.path("/{token}");

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

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

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

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

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

    return passwordResetToken;
}

From source file:ch.wisv.areafiftylan.products.service.TicketServiceImpl.java

private boolean isTicketAvailable(TicketType type) {
    boolean typeLimitReached = type.getLimit() != 0 && ticketRepository.countByType(type) >= type.getLimit();
    boolean eventLimitReached = ticketRepository.count() >= TICKET_LIMIT;
    boolean deadlineExceeded = type.getDeadline().isBefore(LocalDateTime.now());

    return !typeLimitReached && !deadlineExceeded && !eventLimitReached;
}

From source file:com.otway.picasasync.syncutil.SyncManager.java

public void BeginCompleteSync() {

    if (syncState.getIsInProgress()) {

        log.warn("Sync started when already in progress. Doing nothing...");
        return;/*from w  w w. j  ava2  s  . c  om*/
    }

    LocalDateTime startDate = LocalDateTime.now();
    startDate = startDate.plusDays(-1 * settings.getSyncDateRange());
    boolean endedWithError = true;

    log.info("Synchronisation started. Max photo age: " + startDate);

    if (SwingUtilities.isEventDispatchThread()) {
        log.error("Sync started on GUI thread!");
        throw new RuntimeException("This method should not be run on the GUI thread");
    }

    try {
        syncState.start();

        File rootFolder = initFolder();

        syncState.setStatus("Starting synchronisation");

        // Do the actual sync
        Synchronise(rootFolder, startDate);

        syncState.setStatus("Sync complete");

        endedWithError = false;

    } catch (ServiceForbiddenException forbiddenEx) {

        log.error("Auth expired. Discarding web client; will re-auth on next loop.");
        invalidateWebClient();
    } catch (UnknownHostException ex) {
        log.warn("Unknown host exception. Did we lose internet access?");
        // Cancel this sync, and we'll try again in a bit
        syncState.setStatus("Error finding Google.com. Sync Aborted.");
    } catch (SocketException ex) {
        log.warn("Socket exception. Did we lose internet access?");
        // Cancel this sync, and we'll try again in a bit
        syncState.setStatus("Connection error. Sync Aborted.");
    } catch (SocketTimeoutException ex) {
        log.warn("Socket timeout. Did we lose internet access?");
        // Cancel this sync, and we'll try again in a bit
        syncState.setStatus("Connection timeout. Sync aborted.");
    } catch (Exception ex) {
        log.error("Unexpected error: ", ex);
    } finally {
        log.info("Synchronisation ended.");
        if (endedWithError)
            syncState.setStatus("Sync failed.");
        syncState.cancel(endedWithError);
    }
}

From source file:com.google.refine.model.medadata.ProjectMetadata.java

public ProjectMetadata() {
    this(LocalDateTime.now());
    _modified = _created;
}

From source file:org.jgrades.backup.creator.StartBackupJob.java

private void setFailureDetails(Backup backup, BackupEvent event) {
    backup.setStatus(BackupStatus.DONE_WITH_ERROR);
    event.setSeverity(BackupEventSeverity.ERROR);
    event.setMessage("Cannot create directory for backup");
    event.setEndTime(LocalDateTime.now());
    backupRepository.save(backup);//from w ww  .j  av  a  2 s  .c o  m
    backupEventRepository.save(event);
}

From source file:org.jgrades.backup.creator.EncryptArchiveJob.java

private void setWarnDetails(BackupEvent event) {
    event.setEventType(BackupEventType.FINISHED);
    event.setSeverity(BackupEventSeverity.WARNING);
    event.setEndTime(LocalDateTime.now());
    backupEventRepository.save(event);//from   w w  w.  j  a va  2 s  . co m
}

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

/**
 * Ckeditor?/*from ww w  . j a  v a2 s.c  o  m*/
 *
 * @param request
 * @return
 */
public static String processUploadPostForCkeditor(HttpServletRequest request) {
    LocalDateTime now = LocalDateTime.now();
    String realFolder = LOCALROOT + getImageRelativePathByDate(now);
    String urlPath = getImageUrlPathByDate(now);

    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(new File(realFolder));
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    servletFileUpload.setFileSizeMax(MAX_FILE_SIZE);

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Iterator<String> fileNameIter = multipartRequest.getFileNames();
    try {
        while (fileNameIter.hasNext()) {
            MultipartFile mr = multipartRequest.getFile(fileNameIter.next());
            String sourceFileName = mr.getOriginalFilename();
            if (StringUtils.isNotBlank(sourceFileName)) {
                String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1);
                if (ALLOWEXT.contains(fileType)) {
                    String filename = getDateTypeFileName(now, fileType);
                    File targetFile = new File(realFolder + File.separator + filename);
                    logger.info("Upload file path: " + targetFile.getAbsolutePath());
                    mr.transferTo(targetFile);
                    return urlPath + "/" + filename;
                } else {
                    logger.error("?: " + fileType);
                    return "";
                }
            }
        }
    } catch (IOException e) {
        logger.error("error", e);
    }
    return "";
}

From source file:com.br.ifpb.servlet.UploadImagemPerfil.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from ww w.  j  a v  a 2s. co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Usuario usuario = ((Usuario) request.getSession().getAttribute("usuario"));
    if (usuario == null) {
        response.sendRedirect("");
    } else {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = null;
            try {
                items = (List<FileItem>) upload.parseRequest(request);
            } catch (FileUploadException ex) {
                Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
            }
            FileItem item = items.get(0);
            if (item != null) {
                String nome_arquivo = String.valueOf(new Date().getTime()) + item.getName();
                String caminho = getServletContext().getRealPath("/imagens") + "\\" + usuario.getId() + "\\";
                File file = new File(caminho);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File uploadedFile = new File(caminho + nome_arquivo);
                try {
                    item.write(uploadedFile);
                } catch (Exception ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciarUsuario gerenciarUsuario = new GerenciarUsuario();
                try {
                    gerenciarUsuario.atualizarFotoPerfil("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            usuario.getId());
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciarFotos gerenciarFotos = new GerenciarFotos();
                try {
                    gerenciarFotos.publicarFoto("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            Timestamp.valueOf(LocalDateTime.now()), usuario);
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    usuario = gerenciarUsuario.getUsuario(usuario.getId());
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                request.getSession().setAttribute("usuario", usuario);
                response.sendRedirect("configuracao");
            } else {

            }
        }

    }
}