/** * Base abstract class for entities which will hold definitions for created, last modified by and * created, last modified by date. */ @MappedSuperclass @Audited @EntityListeners(AuditingEntityListener.class) public abstract class AbstractAuditingEntity { @CreatedBy @NotNull @Column(name = "created_by", nullable = false, length = 50, updatable = false) @JsonIgnore private String createdBy; @CreatedDate @NotNull @Column(name = "created_date", nullable = false) @JsonIgnore private ZonedDateTime createdDate = ZonedDateTime.now(); @LastModifiedBy @Column(name = "last_modified_by", length = 50) @JsonIgnore private String lastModifiedBy; @LastModifiedDate @Column(name = "last_modified_date") @JsonIgnore private ZonedDateTime lastModifiedDate = ZonedDateTime.now(); public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public ZonedDateTime getCreatedDate() { return createdDate; } public void setCreatedDate(ZonedDateTime createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public ZonedDateTime getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(ZonedDateTime lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } }
/** * Base abstract class for entities which will hold definitions for created, last modified by and * created, last modified by date. */ public abstract class AbstractAuditingEntity implements Serializable { private static final long serialVersionUID = 1L; @CreatedBy @Field("created_by") @JsonIgnore private String createdBy; @CreatedDate @Field("created_date") @JsonIgnore private ZonedDateTime createdDate = ZonedDateTime.now(); @LastModifiedBy @Field("last_modified_by") @JsonIgnore private String lastModifiedBy; @LastModifiedDate @Field("last_modified_date ") @JsonIgnore private ZonedDateTime lastModifiedDate = ZonedDateTime.now(); public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public ZonedDateTime getCreatedDate() { return createdDate; } public void setCreatedDate(ZonedDateTime createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public ZonedDateTime getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(ZonedDateTime lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } }
/** * This method processes the pending payment using the configured payment gateway (at the time of * writing, only STRIPE) and returns a PaymentResult. In order to preserve the consistency of the * payment, when a non-gateway Exception is thrown, it rethrows an IllegalStateException * * @param reservationId * @param gatewayToken * @param price * @param event * @param email * @param customerName * @param billingAddress * @return PaymentResult * @throws java.lang.IllegalStateException if there is an error after charging the credit card */ public PaymentResult processPayment( String reservationId, String gatewayToken, int price, Event event, String email, CustomerName customerName, String billingAddress) { try { final Charge charge = stripeManager.chargeCreditCard( gatewayToken, price, event, reservationId, email, customerName.getFullName(), billingAddress); log.info("transaction {} paid: {}", reservationId, charge.getPaid()); transactionRepository.insert( charge.getId(), reservationId, ZonedDateTime.now(), price, event.getCurrency(), charge.getDescription(), PaymentProxy.STRIPE.name()); return PaymentResult.successful(charge.getId()); } catch (Exception e) { if (e instanceof StripeException) { return PaymentResult.unsuccessful(stripeManager.handleException((StripeException) e)); } throw new IllegalStateException(e); } }
@Test @Transactional public void getBloodPressureForLast30Days() throws Exception { ZonedDateTime now = ZonedDateTime.now(); ZonedDateTime firstOfMonth = now.withDayOfMonth(1); ZonedDateTime firstDayOfLastMonth = firstOfMonth.minusMonths(1); createBloodPressureByMonth(firstOfMonth, firstDayOfLastMonth); // create security-aware mockMvc restBloodPressureMockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); // Get all the blood pressure readings restBloodPressureMockMvc .perform(get("/api/bloodPressures").with(user("user").roles("USER"))) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$", hasSize(6))); // Get the blood pressure readings for the last 30 days restBloodPressureMockMvc .perform(get("/api/bp-by-days/{days}", 30).with(user("user").roles("USER"))) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.period").value("Last 30 Days")) .andExpect(jsonPath("$.readings.[*].systolic").value(hasItem(120))) .andExpect(jsonPath("$.readings.[*].diastolic").value(hasItem(75))); }
public User createUser(ManagedUserDTO managedUserDTO) { User user = new User(); user.setLogin(managedUserDTO.getLogin()); user.setFirstName(managedUserDTO.getFirstName()); user.setLastName(managedUserDTO.getLastName()); user.setEmail(managedUserDTO.getEmail()); if (managedUserDTO.getLangKey() == null) { user.setLangKey("en"); // default language is English } else { user.setLangKey(managedUserDTO.getLangKey()); } if (managedUserDTO.getAuthorities() != null) { Set<Authority> authorities = new HashSet<>(); managedUserDTO .getAuthorities() .stream() .forEach(authority -> authorities.add(authorityRepository.findOne(authority))); user.setAuthorities(authorities); } String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword()); user.setPassword(encryptedPassword); user.setResetKey(RandomUtil.generateResetKey()); user.setResetDate(ZonedDateTime.now()); user.setActivated(true); userRepository.save(user); log.debug("Created Information for User: {}", user); return user; }
@Test public void verifyExpiredAccessToken() throws Exception { final Principal principal = org.jasig.cas.authentication.TestUtils.getPrincipal(ID, new HashMap<String, Object>()); final Authentication authentication = new OAuthAuthentication(ZonedDateTime.now(), principal); final DefaultAccessTokenFactory expiringAccessTokenFactory = new DefaultAccessTokenFactory(); expiringAccessTokenFactory.setExpirationPolicy( new ExpirationPolicy() { @Override public boolean isExpired(final TicketState ticketState) { return true; } }); final AccessTokenImpl accessToken = (AccessTokenImpl) expiringAccessTokenFactory.create(TestUtils.getService(), authentication); oAuth20ProfileController.getTicketRegistry().addTicket(accessToken); final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.PROFILE_URL); mockRequest.setParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getId()); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); oAuth20ProfileController.handleRequest(mockRequest, mockResponse); assertEquals(200, mockResponse.getStatus()); assertEquals( "{\"error\":\"" + OAuthConstants.EXPIRED_ACCESS_TOKEN + "\"}", mockResponse.getContentAsString()); }
@Test public void should_fail_if_dateTime_as_string_parameter_is_null() { expectException( IllegalArgumentException.class, "The String representing the ZonedDateTime to compare actual with should not be null"); assertThat(ZonedDateTime.now()).isBeforeOrEqualTo((String) null); }
@Override public boolean isExpired(final TicketState ticketState) { return ticketState == null || ticketState .getCreationTime() .plus(this.timeToKillInMilliSeconds, ChronoUnit.MILLIS) .isBefore(ZonedDateTime.now(ZoneOffset.UTC)); }
@Test public void testFindNotActivatedUsersByCreationDateBefore() { userService.removeNotActivatedUsers(); ZonedDateTime now = ZonedDateTime.now(); List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3)); assertThat(users).isEmpty(); }
/** User test utility */ public class TestUser { private static TestUser instance; private static User user1; // Date are initialized with java.sql.Timestamp as JPA get a Timestamp instance private static final Date now = Timestamp.from(ZonedDateTime.now().toInstant()); private static final Date yesterday = Timestamp.from(ZonedDateTime.now().minusDays(1).toInstant()); public static TestUser getInstance() { if (instance != null) return instance; EntityManager entityManager = Persistence.createEntityManagerFactory(UserPersistenceUnit.NAME).createEntityManager(); entityManager.getTransaction().begin(); Address address = new Address("21 Blue street", "Chicago", "78801", "John", "Doe", "M.", null, "FRA"); user1 = new User( "*****@*****.**", "test", "John", "Doe", "+33616161616", null, yesterday, "fr_FR", null); user1.setGender("M."); entityManager.persist(address); entityManager.persist(user1); Role adminRole = new Role(RoleName.admin); Role userRole = new Role(RoleName.user); entityManager.persist(adminRole); entityManager.persist(userRole); entityManager.getTransaction().commit(); instance = new TestUser(); entityManager.close(); return instance; } public User firstUser() { return user1; } }
/** * Gets availability times of the server. * * @param httpServletRequest the http servlet request * @param httpServletResponse the http servlet response * @return the availability */ @RequestMapping(value = "/getAvailability", method = RequestMethod.GET) @ResponseBody public Map<String, Object> getAvailability( final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) { final Map<String, Object> model = new HashMap<>(); final Duration diff = Duration.between(this.upTimeStartDate, ZonedDateTime.now(ZoneOffset.UTC)); model.put("upTime", diff.getSeconds()); return model; }
@Override public boolean validate(Auction auction) { Auction auctionDatabase = repository .getById(auction.getId()) .orElseThrow(() -> new AuctionNotFoundException(auction.getId())); return auctionDatabase.getEndingTime().isAfter(ZonedDateTime.now(ZoneOffset.UTC)); }
@Override public boolean isExpired(final TicketState ticketState) { if (ticketState == null) { return true; } final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); final ZonedDateTime expirationTime = ticketState.getLastTimeUsed().plus(this.timeToKillInSeconds, ChronoUnit.SECONDS); return now.isAfter(expirationTime); }
/** * Not activated users should be automatically deleted after 3 days. * * <p> * * <p>This is scheduled to get fired everyday, at 01:00 (am). */ @Scheduled(cron = "0 0 1 * * ?") public void removeNotActivatedUsers() { ZonedDateTime now = ZonedDateTime.now(); List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3)); for (User user : users) { log.debug("Deleting not activated user {}", user.getLogin()); userRepository.delete(user); } }
public void migrateEventsToCurrentVersion() { eventRepository .findAll() .stream() .filter(e -> ZonedDateTime.now(e.getZoneId()).isBefore(e.getEnd())) .forEach(this::migrateEventToCurrentVersion); fillReservationsLanguage(); fillTicketsGender(); fillDefaultOptions(); }
@Test public void verifyAccessStrategyWithStarEndDate() throws Exception { final RegexRegisteredService r = new RegexRegisteredService(); r.setServiceId("^https://.+"); r.setName("verifyAAccessStrategyWithStarEndDate"); r.setId(62); final TimeBasedRegisteredServiceAccessStrategy authz = new TimeBasedRegisteredServiceAccessStrategy(true, false); authz.setStartingDateTime(ZonedDateTime.now(ZoneOffset.UTC).plusDays(1).toString()); authz.setEndingDateTime(ZonedDateTime.now(ZoneOffset.UTC).plusDays(10).toString()); authz.setUnauthorizedRedirectUrl(new URI("https://www.github.com")); r.setAccessStrategy(authz); final RegisteredService r2 = this.dao.save(r); final RegisteredService r3 = this.dao.findServiceById(r2.getId()); assertEquals(r2, r3); }
public Optional<User> requestPasswordReset(String mail) { return userRepository .findOneByEmail(mail) .filter(user -> user.getActivated()) .map( user -> { user.setResetKey(RandomUtil.generateResetKey()); user.setResetDate(ZonedDateTime.now()); userRepository.save(user); return user; }); }
public static void main(String[] args) { System.out.println("Hello World!"); /* Issue1: Display total amount of free memory available to the JVM/User */ System.out.println("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); /* Issue2: Display the current date to the user */ System.out.print( java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME .format(java.time.ZonedDateTime.now()) .replaceFirst(".....$", "GMT") + ": "); // replace UTC offset with GMT }
public PaymentResult processOfflinePayment(String reservationId, int price, Event event) { String transactionId = UUID.randomUUID().toString(); transactionRepository.insert( transactionId, reservationId, ZonedDateTime.now(event.getZoneId()), price, event.getCurrency(), "Offline payment confirmation", PaymentProxy.OFFLINE.toString()); return PaymentResult.successful(transactionId); }
public NetworkMockup() { this.initialFactTemplate = defTemplate("initial-fact", ""); defFacts("initial-fact", "", Arrays.asList(new TemplateContainer<>(initialFactTemplate))); { final Template dummyFact = this.defTemplate("dummy-fact", "used as default value for FACT-ADDRESS"); @SuppressWarnings("unchecked") final FactIdentifier dummyFactIdentifier = new org.jamocha.function.fwa.Assert<>( this, new TemplateContainer[] {new TemplateContainer<>(dummyFact)}) .evaluate(); for (final SlotType type : EnumSet.allOf(SlotType.class)) { switch (type) { case BOOLEAN: defaultValues.put(type, Boolean.FALSE); break; case DATETIME: defaultValues.put(type, ZonedDateTime.now()); break; case DOUBLE: defaultValues.put(type, Double.valueOf(0.0)); break; case LONG: defaultValues.put(type, Long.valueOf(0)); break; case NIL: defaultValues.put(type, null); break; case STRING: defaultValues.put(type, ""); break; case SYMBOL: defaultValues.put(type, this.getScope().getOrCreateSymbol("nil")); break; case FACTADDRESS: defaultValues.put(type, dummyFactIdentifier); break; case BOOLEANS: case DATETIMES: case DOUBLES: case FACTADDRESSES: case LONGS: case NILS: case STRINGS: case SYMBOLS: defaultValues.put(type, Array.newInstance(type.getJavaClass(), 0)); break; } } } }
@Override public void onApplicationEvent(BeforeConvertEvent<Object> event) { Object obj = event.getSource(); Instant utcInstantTime = ZonedDateTime.now(ZoneOffset.UTC).toInstant(); if (AuditorModel.class.isAssignableFrom(obj.getClass())) { AuditorModel entity = (AuditorModel) obj; if (entity.isNew()) { entity.setCreatedDate(Date.from(utcInstantTime)); entity.setLastModifiedDate(Date.from(utcInstantTime)); } else { entity.setLastModifiedDate(Date.from(utcInstantTime)); } } }
@Test public void assertThatResetKeyMustBeValid() { User user = userService.createUserInformation( "johndoe", "johndoe", "John", "Doe", "john.doe@localhost", "en-US"); ZonedDateTime daysAgo = ZonedDateTime.now().minusHours(25); user.setActivated(true); user.setResetDate(daysAgo); user.setResetKey("1234"); userRepository.save(user); Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); assertThat(maybeUser.isPresent()).isFalse(); userRepository.delete(user); }
@Test public void logoutResourceDeletesSessionCookie() throws Exception { NewCookie cookie = cookieFactory.getSessionCookie(User.named("Me"), ZonedDateTime.now(clock).plusDays(1)); Response response = sessionLogoutResource.logout(cookie); assertThat(response.getStatus()).isEqualTo(303); String resultCookie = response.getMetadata().getFirst("Set-Cookie").toString(); assertThat(resultCookie) .contains("HttpOnly") .contains("Secure") .contains("Path=/admin;") .contains("session=expired;"); }
@Test public void verifyOKWithAuthorizationHeader() throws Exception { final Map<String, Object> map = new HashMap<>(); map.put(NAME, VALUE); final List<String> list = Arrays.asList(VALUE, VALUE); map.put(NAME2, list); final Principal principal = org.jasig.cas.authentication.TestUtils.getPrincipal(ID, map); final Authentication authentication = new OAuthAuthentication(ZonedDateTime.now(), principal); final AccessTokenImpl accessToken = (AccessTokenImpl) accessTokenFactory.create(TestUtils.getService(), authentication); oAuth20ProfileController.getTicketRegistry().addTicket(accessToken); final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.PROFILE_URL); mockRequest.addHeader("Authorization", OAuthConstants.BEARER_TOKEN + ' ' + accessToken.getId()); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); oAuth20ProfileController.handleRequest(mockRequest, mockResponse); assertEquals(200, mockResponse.getStatus()); assertEquals(CONTENT_TYPE, mockResponse.getContentType()); final ObjectMapper mapper = new ObjectMapper(); final String expected = "{\"id\":\"" + ID + "\",\"attributes\":[{\"" + NAME + "\":\"" + VALUE + "\"},{\"" + NAME2 + "\":[\"" + VALUE + "\",\"" + VALUE + "\"]}]}"; final JsonNode expectedObj = mapper.readTree(expected); final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString()); assertEquals(expectedObj.get("id").asText(), receivedObj.get("id").asText()); final JsonNode expectedAttributes = expectedObj.get("attributes"); final JsonNode receivedAttributes = receivedObj.get("attributes"); assertEquals( expectedAttributes.findValue(NAME).asText(), receivedAttributes.findValue(NAME).asText()); assertEquals(expectedAttributes.findValues(NAME2), receivedAttributes.findValues(NAME2)); }
@Override public void run() { System.out.println("notifications job running"); List<User> users = userService.queryUsers(Filters.eq("notifications", true)); for (User user : users) { String query = user.getNotificationQuery(); query = query + "&createdOn[$gt]=" + user.getLastNotificationAt(); List<Document> documents = adService.queryAds(query); if (!documents.isEmpty()) { List<BaseAd> adsList = adService.getListAs(BaseAd.class, documents); twilioService.sendSMS(user.getMobile(), "New ads for your query"); user.setLastNotificationAt(ZonedDateTime.now().toEpochSecond()); userService.updateUser(user); } } }
@Override protected OptionContract createLatest(SecurityIdentifier security) { Option found = null; for (Option option : options) { if (option.symbol.equals(security.getSymbol())) { found = option; } } if (found == null) { return null; } return new OptionContractImpl( security, ZonedDateTime.now(), found.type, found.expiry, 25.5D, found.name); }
@Test public void testPlaceMOCOrders() { String corrId = "123"; int longSize = 100; int shortSize = 200; ZonedDateTime currentDateTime = ZonedDateTime.of(2016, 3, 3, 5, 5, 1, 0, ZoneId.systemDefault()); ZonedDateTime orderTime = ZonedDateTime.now(); strategy.ibClient = mockIbClient; doReturn(corrId).when(strategy).getUUID(); doReturn(longSize).when(strategy).getOrderSize(longTicker); doReturn(shortSize).when(strategy).getOrderSize(shortTicker); doReturn(orderTime).when(strategy).getNextBusinessDay(currentDateTime); when(mockIbClient.getNextOrderId()).thenReturn("100", "101", "102", "103", "104", "105"); TradeOrder expectedLongOrder = new TradeOrder("100", longTicker, longSize, TradeDirection.BUY); expectedLongOrder.setType(TradeOrder.Type.MARKET_ON_CLOSE); expectedLongOrder.setReference("EOD-Pair-Strategy:123:Entry:Long*"); TradeOrder expectedLongExitOrder = new TradeOrder("101", longTicker, longSize, TradeDirection.SELL); expectedLongExitOrder.setType(TradeOrder.Type.MARKET_ON_OPEN); expectedLongExitOrder.setGoodAfterTime(orderTime); expectedLongExitOrder.setReference("EOD-Pair-Strategy:123:Exit:Long*"); expectedLongOrder.addChildOrder(expectedLongExitOrder); TradeOrder expectedShortOrder = new TradeOrder("102", shortTicker, shortSize, TradeDirection.SELL_SHORT); expectedShortOrder.setType(TradeOrder.Type.MARKET_ON_CLOSE); expectedShortOrder.setReference("EOD-Pair-Strategy:123:Entry:Short*"); TradeOrder expectedShortExitOrder = new TradeOrder("103", shortTicker, shortSize, TradeDirection.BUY_TO_COVER); expectedShortExitOrder.setType(TradeOrder.Type.MARKET_ON_OPEN); expectedShortExitOrder.setGoodAfterTime(orderTime); expectedShortExitOrder.setReference("EOD-Pair-Strategy:123:Exit:Short*"); expectedShortOrder.addChildOrder(expectedShortExitOrder); strategy.placeMOCOrders(longTicker, shortTicker, currentDateTime); verify(mockIbClient).placeOrder(expectedLongOrder); verify(mockIbClient).placeOrder(expectedShortOrder); }
private static void newAPI() { LocalDate soloFecha = LocalDate.now(); LocalTime soloHora = LocalTime.now(); LocalDateTime todo = LocalDateTime.now(); ZonedDateTime zonedDateTime = ZonedDateTime.now(); System.out.println("La fecha " + soloFecha); System.out.println("La hora " + soloHora); System.out.println("La fecha hora " + todo); System.out.println("La fecha hora y zona " + zonedDateTime); LocalDate myFecha = LocalDate.of(2015, Month.JULY, 2); LocalTime myHora = LocalTime.of(9, 21); System.out.println("Ayer fue: " + myFecha); System.out.println("La hora fue: " + myHora); }
public Optional<User> completePasswordReset(String newPassword, String key) { log.debug("Reset user password for reset key {}", key); return userRepository .findOneByResetKey(key) .filter( user -> { ZonedDateTime oneDayAgo = ZonedDateTime.now().minusHours(24); return user.getResetDate().isAfter(oneDayAgo); }) .map( user -> { user.setPassword(passwordEncoder.encode(newPassword)); user.setResetKey(null); user.setResetDate(null); userRepository.save(user); return user; }); }
@Test public void assertThatUserCanResetPassword() { User user = userService.createUserInformation( "johndoe", "johndoe", "John", "Doe", "john.doe@localhost", "en-US"); String oldPassword = user.getPassword(); ZonedDateTime daysAgo = ZonedDateTime.now().minusHours(2); String resetKey = RandomUtil.generateResetKey(); user.setActivated(true); user.setResetDate(daysAgo); user.setResetKey(resetKey); userRepository.save(user); Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); assertThat(maybeUser.isPresent()).isTrue(); assertThat(maybeUser.get().getResetDate()).isNull(); assertThat(maybeUser.get().getResetKey()).isNull(); assertThat(maybeUser.get().getPassword()).isNotEqualTo(oldPassword); userRepository.delete(user); }