List of usage examples for java.time LocalDateTime now
public static LocalDateTime now()
From source file:com.swcguild.capstoneproject.dao.BlogDaoDbImplTest.java
/** * Test of removePinPost method, of class BlogDaoDbImpl. *///from w w w .j a va 2 s. c om @Test public void testRemovePinPost() { System.out.println("removePinPost"); PinPost pinPost1 = new PinPost("Cali", "Shawn", "Won by 14", LocalDateTime.now().toString(), "2016-01-01"); PinPost pinPost2 = new PinPost("Cali1", "Shawn", "Won by 14", LocalDateTime.now().toString(), "2016-01-01"); PinPost pinPost3 = new PinPost("Cali2", "Shawn", "Won by 14", LocalDateTime.now().toString(), "2016-01-01"); dao.addPinPost(pinPost1); // System.out.println(pinPost1.getPinPostID()); dao.addPinPost(pinPost2); // System.out.println(pinPost2.getPinPostID()); dao.addPinPost(pinPost3); // System.out.println(pinPost3.getPinPostID()); dao.removePinPost(pinPost2.getPinPostID()); assertEquals(2, dao.getAllPinPosts().size()); }
From source file:org.wallride.service.UserService.java
@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true) public UserInvitation inviteAgain(UserInvitationResendRequest form, BindingResult result, AuthorizedUser authorizedUser) throws MessagingException { LocalDateTime now = LocalDateTime.now(); UserInvitation invitation = userInvitationRepository.findOneForUpdateByToken(form.getToken()); invitation.setExpiredAt(now.plusHours(72)); invitation.setUpdatedAt(now);// ww w .ja v a 2s.c o m invitation.setUpdatedBy(authorizedUser.toString()); invitation = userInvitationRepository.saveAndFlush(invitation); Blog blog = blogService.getBlogById(Blog.DEFAULT_ID); String websiteTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage()); String signupLink = ServletUriComponentsBuilder.fromCurrentContextPath().path("/_admin/signup") .queryParam("token", invitation.getToken()).buildAndExpand().toString(); final Context ctx = new Context(LocaleContextHolder.getLocale()); ctx.setVariable("websiteTitle", websiteTitle); ctx.setVariable("authorizedUser", authorizedUser); ctx.setVariable("signupLink", signupLink); ctx.setVariable("invitation", invitation); final MimeMessage mimeMessage = mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart message.setSubject(MessageFormat.format( messageSourceAccessor.getMessage("InvitationMessageTitle", LocaleContextHolder.getLocale()), authorizedUser.toString(), websiteTitle)); message.setFrom(authorizedUser.getEmail()); message.setTo(invitation.getEmail()); final String htmlContent = templateEngine.process("user-invite", ctx); message.setText(htmlContent, true); // true = isHtml mailSender.send(mimeMessage); return invitation; }
From source file:net.resheim.eclipse.timekeeper.ui.Activator.java
/** * Must be called by the UI-thread//from www.java 2s .co m * * @param idleTimeMillis */ private void handleReactivation(long idleTimeMillis) { // We want only one dialog open. if (dialogIsOpen) { return; } synchronized (this) { if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) { // If we have an active task ITask task = TasksUi.getTaskActivityManager().getActiveTask(); if (task != null && Activator.getValue(task, Activator.START) != null) { dialogIsOpen = true; String tickString = Activator.getValue(task, Activator.TICK); LocalDateTime started = getActiveSince(); LocalDateTime ticked = LocalDateTime.parse(tickString); LocalDateTime lastTick = ticked; // Subtract the IDLE_INTERVAL time the computer _was_ // idle while counting up to the threshold. During this // period fields were updated. Thus must be adjusted for. ticked = ticked.minusNanos(IDLE_INTERVAL); String time = DurationFormatUtils.formatDuration(lastIdleTime, "H:mm:ss", true); StringBuilder sb = new StringBuilder(); if (task.getTaskKey() != null) { sb.append(task.getTaskKey()); sb.append(": "); } sb.append(task.getSummary()); MessageDialog md = new MessageDialog(Display.getCurrent().getActiveShell(), "Disregard idle time?", null, MessageFormat.format( "The computer has been idle since {0}, more than {1}. The active task \"{2}\" was started on {3}. Deactivate the task and disregard the idle time?", ticked.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US)), time, sb.toString(), started.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US))), MessageDialog.QUESTION, new String[] { "No", "Yes" }, 1); int open = md.open(); dialogIsOpen = false; if (open == 1) { // Stop task, subtract initial idle time TasksUi.getTaskActivityManager().deactivateTask(task); reduceTime(task, ticked.toLocalDate().toString(), IDLE_INTERVAL / 1000); } else { // Continue task, add idle time LocalDateTime now = LocalDateTime.now(); long seconds = lastTick.until(now, ChronoUnit.MILLIS); accumulateTime(task, ticked.toLocalDate().toString(), seconds); Activator.setValue(task, Activator.TICK, now.toString()); } } } } }
From source file:com.swcguild.capstoneproject.dao.BlogDaoDbImplTest.java
/** * Test of updatePinPost method, of class BlogDaoDbImpl. *///from www .j av a 2 s .co m @Test public void testUpdatePinPost() { System.out.println("updatePinPost"); PinPost pinPost = new PinPost("Cali", "Shawn", "Won by 14", LocalDateTime.now().toString(), "2016-01-01"); dao.updatePinPost(pinPost); assertEquals("Cali", pinPost.getTitle()); }
From source file:org.ow2.proactive.workflow_catalog.rest.service.WorkflowRevisionServiceTest.java
private void createWorkflow(String name, String projectName, String fileName, Optional<Long> wId, Optional<String> layout) throws IOException { String layoutStr = layout.orElse(""); when(bucketRepository.findOne(anyLong())).thenReturn(mock(Bucket.class)); when(genericInformationRepository.save(any(List.class))).thenReturn(Lists.newArrayList()); when(variableRepository.save(any(List.class))).thenReturn(Lists.newArrayList()); when(workflowRevisionRepository.save(any(WorkflowRevision.class))) .thenReturn(new WorkflowRevision(EXISTING_ID, EXISTING_ID, name, projectName, LocalDateTime.now(), layoutStr, Lists.newArrayList(), Lists.newArrayList(), getWorkflowAsByteArray(fileName))); if (wId.isPresent()) { when(workflowRepository.findOne(anyLong())) .thenReturn(new Workflow(mock(Bucket.class), Lists.newArrayList())); }/*w ww. java 2 s .co m*/ WorkflowMetadata actualWFMetadata = workflowRevisionService.createWorkflowRevision(DUMMY_ID, wId, getWorkflowAsByteArray(fileName), layout); verify(workflowRevisionRepository, times(1)).save(any(WorkflowRevision.class)); assertEquals(name, actualWFMetadata.name); assertEquals(projectName, actualWFMetadata.projectName); assertEquals(EXISTING_ID, actualWFMetadata.bucketId); assertEquals(EXISTING_ID, actualWFMetadata.revisionId); if (layout.isPresent()) { assertEquals(layout.get(), actualWFMetadata.layout); } }
From source file:net.resheim.eclipse.timekeeper.ui.Activator.java
/** * Returns the number of milliseconds the active task has been active * * @return the active milliseconds or "0" *///ww w . j a v a 2 s . c o m public long getActiveTime() { LocalDateTime activeSince = getActiveSince(); if (activeSince != null) { LocalDateTime now = LocalDateTime.now(); return activeSince.until(now, ChronoUnit.MILLIS); } return 0; }
From source file:de.steilerdev.myVerein.server.controller.admin.EventManagementController.java
/** * This function saves an event. The function is invoked by POSTint the parameters to the URI /api/admin/event. * @param eventFlag This flag either stores the ID of the event, or true, if a new event is created. * @param eventName The name of the event. * @param eventDescription The description of the event. * @param startDate The start date, formatted according to the pattern d/MM/y, defined within the Java 8 DateTimeFormatter. * @param startTime The start time, formatted according to the pattern H:m, defined within the Java 8 DateTimeFormatter. * @param endDate The end date, formatted according to the pattern d/MM/y, defined within the Java 8 DateTimeFormatter. * @param endTime The end time, formatted according to the pattern H:m, defined within the Java 8 DateTimeFormatter. * @param location The name of the location of the event. * @param locationLat The latitude of the location of the event. * @param locationLng The longitude of the location of the event. * @param invitedDivisions A comma separated list of invited divisions. * @param currentUser The currently logged in user. * @return An HTTP response with a status code together with a JSON map object, containing an 'errorMessage', or a 'successMessage' respectively. If the operation was successful the id of the event is accessible via 'eventID'. *//* w w w . j ava 2s. c o m*/ @RequestMapping(method = RequestMethod.POST, produces = "application/json") public ResponseEntity<Map<String, String>> saveEvent(@RequestParam String eventFlag, @RequestParam String eventName, @RequestParam String eventDescription, @RequestParam String startDate, @RequestParam String startTime, @RequestParam String endDate, @RequestParam String endTime, @RequestParam String location, @RequestParam String locationLat, @RequestParam String locationLng, @RequestParam String invitedDivisions, @CurrentUser User currentUser) { logger.trace("[" + currentUser + "] Saving event"); Map<String, String> responseMap = new HashMap<>(); Event event; if (eventFlag.isEmpty()) { logger.warn("[" + currentUser + "] The event flag is empty"); responseMap.put("errorMessage", "The event flag is not allowed to be empty"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } else if (eventFlag.equals("true")) { logger.debug("[" + currentUser + "] A new event is created"); event = new Event(); } else { logger.debug("[" + currentUser + "] The event with id " + eventFlag + " is altered"); event = eventRepository.findEventById(eventFlag); if (event == null) { logger.warn("[" + currentUser + "] Unable to find the specified event with id " + eventFlag); responseMap.put("errorMessage", "Unable to find the specified event"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } else if (!currentUser.isAllowedToAdministrate(event)) { logger.warn( "[" + currentUser + "] The user is not allowed to alter the selected event " + eventFlag); responseMap.put("errorMessage", "You are not allowed to edit the selected event"); return new ResponseEntity<>(responseMap, HttpStatus.FORBIDDEN); } } event.setName(eventName); event.setDescription(eventDescription); if (startDate.isEmpty() || startTime.isEmpty() || endDate.isEmpty() || endTime.isEmpty()) { logger.warn("[" + currentUser + "] The date and times defining the event (ID " + eventFlag + ") are not allowed to be empty."); responseMap.put("errorMessage", "The date and times defining the event are not allowed to be empty"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } else { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/y'T'H:m"); try { event.setStartDateTime(LocalDateTime.parse(startDate + "T" + startTime, formatter)); } catch (DateTimeParseException e) { logger.warn("[" + currentUser + "] Unrecognized date format " + startDate + "T" + startTime); responseMap.put("errorMessage", "Unrecognized date or time format within start time"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } try { event.setEndDateTime(LocalDateTime.parse(endDate + "T" + endTime, formatter)); } catch (DateTimeParseException e) { logger.warn("[" + currentUser + "] Unrecognized date format " + endDate + "T" + endTime); responseMap.put("errorMessage", "Unrecognized date or time format within end time"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } } event.setLocation(location); if (!locationLat.isEmpty()) { try { event.setLocationLat(Double.parseDouble(locationLat)); } catch (NumberFormatException e) { logger.warn("[" + currentUser + "] Unable to paste lat " + locationLat); responseMap.put("errorMessage", "Unable to parse latitude coordinate"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } } if (!locationLng.isEmpty()) { try { event.setLocationLng(Double.parseDouble(locationLng)); } catch (NumberFormatException e) { logger.warn("[" + currentUser + "] Unable to paste lng " + locationLng); responseMap.put("errorMessage", "Unable to parse longitude coordinate"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } } if (!invitedDivisions.isEmpty()) { String[] divArray = invitedDivisions.split(","); for (String division : divArray) { Division div = divisionRepository.findByName(division); if (div == null) { logger.warn("[" + currentUser + "] Unrecognized division (" + division + ")"); responseMap.put("errorMessage", "Division " + division + " does not exist"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } event.addDivision(div); } event.updateInvitedUser(divisionRepository); } else if (event.getInvitedDivision() != null && !event.getInvitedDivision().isEmpty()) { event.updateInvitedUser(divisionRepository); } //Updating several fields. event.setEventAdmin(currentUser); event.setLastChanged(LocalDateTime.now()); event.updateMultiDate(); try { eventRepository.save(event); logger.info("[" + currentUser + "] Successfully saved event " + eventFlag); responseMap.put("successMessage", "Successfully saved the event"); responseMap.put("eventID", event.getId()); return new ResponseEntity<>(responseMap, HttpStatus.OK); } catch (ConstraintViolationException e) { logger.warn( "[" + currentUser + "] A database constraint was violated while saving the event " + eventFlag); responseMap.put("errorMessage", "A database constraint was violated while saving the event"); return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST); } }
From source file:com.gnadenheimer.mg3.utils.Utils.java
public Boolean exectueBackUp(String backupDirectory) { try {/*from ww w.j a v a 2 s . c o m*/ //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); //String backupfile = backupDirectory + "\\BackUp_" + sdf.format(new LocalDateTime()); String backupfile = backupDirectory + "\\BackUp_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")); Connection conn = DriverManager.getConnection(getPersistenceMap().get("javax.persistence.jdbc.url"), getPersistenceMap().get("javax.persistence.jdbc.user"), getPersistenceMap().get("javax.persistence.jdbc.password")); try (CallableStatement cs = conn.prepareCall("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)")) { cs.setString(1, backupfile); cs.execute(); cs.close(); } catch (Exception ex) { LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex); App.showException(Thread.currentThread().getStackTrace()[1].getMethodName(), ex.getMessage(), ex); } App.showInfo("BackUp", "BackUp guardado con exito en: " + backupfile); return true; } catch (Exception ex) { LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex); App.showException(Thread.currentThread().getStackTrace()[1].getMethodName(), ex.getMessage(), ex); return false; } }
From source file:com.swcguild.capstoneproject.dao.BlogDaoDbImplTest.java
/** * Test of getPinPostById method, of class BlogDaoDbImpl. *///w w w. j a va2 s.co m @Test public void testGetPinPostById() { System.out.println("getPinPostById"); PinPost expResult = new PinPost("Cali", "Shawn", "Won by 14", LocalDateTime.now().toString(), "2016-01-01"); dao.addPinPost(expResult); int pinPostId = expResult.getPinPostID(); PinPost result = dao.getPinPostById(pinPostId); assertTrue( expResult.getAuthor().equals(result.getAuthor()) && expResult.getTitle().equals(result.getTitle())); }
From source file:nc.noumea.mairie.appock.services.impl.CommandeServiceImpl.java
@Override public void valideCommande(Commande commande) { AppUser currentUser = authHelper.getCurrentUser(); commande.setValidationUser(currentUser.getNomComplet()); commande.setDateValidationCommande(LocalDateTime.now()); commande.setEtatCommande(EtatCommande.RECEPTIONNE); commandeRepository.save(commande);/*from w w w . java 2 s .co m*/ }