List of usage examples for java.util Date from
public static Date from(Instant instant)
From source file:org.apache.james.jmap.utils.FilterToSearchQueryTest.java
@Test public void filterConditionShouldMapWhenAfter() { ZonedDateTime after = ZonedDateTime.now(); SearchQuery expectedSearchQuery = new SearchQuery(); expectedSearchQuery/*from w ww .j a v a 2 s . co m*/ .andCriteria(SearchQuery.internalDateAfter(Date.from(after.toInstant()), DateResolution.Second)); SearchQuery searchQuery = new FilterToSearchQuery().convert(FilterCondition.builder().after(after).build()); assertThat(searchQuery).isEqualTo(expectedSearchQuery); }
From source file:com.example.geomesa.cassandra.CassandraQuickStart.java
static FeatureCollection createNewFeatures(SimpleFeatureType simpleFeatureType, int numNewFeatures) { DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(); String id;/*from w w w . ja v a 2 s . c om*/ Object[] NO_VALUES = {}; String[] PEOPLE_NAMES = { "Addams", "Bierce", "Clemens" }; Long SECONDS_PER_YEAR = 365L * 24L * 60L * 60L; Random random = new Random(5771); ZonedDateTime MIN_DATE = ZonedDateTime.of(2014, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); Double MIN_X = -78.0; Double MIN_Y = -39.0; Double DX = 2.0; Double DY = 2.0; for (int i = 0; i < numNewFeatures; i++) { // create the new (unique) identifier and empty feature shell id = "Observation." + Integer.toString(i); SimpleFeature simpleFeature = SimpleFeatureBuilder.build(simpleFeatureType, NO_VALUES, id); // be sure to tell GeoTools explicitly that you want to use the ID you provided simpleFeature.getUserData().put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE); // populate the new feature's attributes // string value simpleFeature.setAttribute("Who", PEOPLE_NAMES[i % PEOPLE_NAMES.length]); // long value simpleFeature.setAttribute("What", i); // location: construct a random point within a 2-degree-per-side square double x = MIN_X + random.nextDouble() * DX; double y = MIN_Y + random.nextDouble() * DY; Geometry geometry = WKTUtils.read("POINT(" + x + " " + y + ")"); // date-time: construct a random instant within a year simpleFeature.setAttribute("Where", geometry); ZonedDateTime dateTime = MIN_DATE.plusSeconds((int) Math.round(random.nextDouble() * SECONDS_PER_YEAR)); simpleFeature.setAttribute("When", Date.from(dateTime.toInstant())); // another string value // "Why"; left empty, showing that not all attributes need values // accumulate this new feature in the collection featureCollection.add(simpleFeature); } return featureCollection; }
From source file:com.github.lburgazzoli.camel.CaseToIncidentProcessor.java
private Date zonedDateTimeToDate(ZonedDateTime zdt) { return zdt != null ? Date.from(zdt.withZoneSameInstant(ZoneId.of("UTC")).toInstant()) : null; }
From source file:org.thingsboard.server.service.security.model.token.JwtTokenFactory.java
public JwtToken createRefreshToken(SecurityUser securityUser) { if (StringUtils.isBlank(securityUser.getEmail())) { throw new IllegalArgumentException("Cannot create JWT Token without username/email"); }//from w w w . j a v a 2s .c o m ZonedDateTime currentTime = ZonedDateTime.now(); UserPrincipal principal = securityUser.getUserPrincipal(); Claims claims = Jwts.claims().setSubject(principal.getValue()); claims.put(SCOPES, Collections.singletonList(Authority.REFRESH_TOKEN.name())); claims.put(USER_ID, securityUser.getId().getId().toString()); claims.put(IS_PUBLIC, principal.getType() == UserPrincipal.Type.PUBLIC_ID); String token = Jwts.builder().setClaims(claims).setIssuer(settings.getTokenIssuer()) .setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(currentTime.toInstant())) .setExpiration(Date.from(currentTime.plusSeconds(settings.getRefreshTokenExpTime()).toInstant())) .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()).compact(); return new AccessJwtToken(token, claims); }
From source file:currency.converter.openexchangerate.OpenExchangeCurrencyConverter.java
/** * Saves currency exchange rate history of the logged in user * /* www. j a v a2s . co m*/ * @param rates Currency rates to be saved * @param baseCurrency Base currency which was used in the search * @param amount Amount of base currency * @param dateOfRate Date when the search was performed * @param userName Username of the user who has searched the exchange rate * * @throws InvalidParameterException for invalid arguments */ private void saveExchangeRate(CurrencyRateModel rates, String baseCurrency, double amount, LocalDate dateOfRate, String userName) throws InvalidParameterException { Currency currency = getCurrency(baseCurrency); Date date = Date.from(dateOfRate.atStartOfDay(ZoneId.systemDefault()).toInstant()); CurrencyHistory currencyHistory = new CurrencyHistory(currency.getId(), amount, date, userName); historyRepository.save(currencyHistory); // Save rates saveCurrencyRates(currencyHistory, rates, baseCurrency); }
From source file:org.apache.james.transport.mailets.DSNBounceTest.java
@Test public void serviceShouldSendMultipartMailContainingTextPart() throws Exception { FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME) .mailetContext(fakeMailContext).build(); dsnBounce.init(mailetConfig);//from w w w . ja va 2 s . com MailAddress senderMailAddress = new MailAddress("sender@domain.com"); FakeMail mail = FakeMail.builder().sender(senderMailAddress).attribute("delivery-error", "Delivery error") .mimeMessage(MimeMessageBuilder.mimeMessageBuilder().setText("My content")).name(MAILET_NAME) .recipient("recipient@domain.com").lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z"))) .build(); dsnBounce.service(mail); String hostname = InetAddress.getLocalHost().getHostName(); String expectedContent = "Hi. This is the James mail server at " + hostname + ".\nI'm afraid I wasn't able to deliver your message to the following addresses.\nThis is a permanent error; I've given up. Sorry it didn't work out. Below\nI include the list of recipients and the reason why I was unable to deliver\nyour message.\n\n" + "Failed recipient(s):\n" + "recipient@domain.com\n" + "\n" + "Error message:\n" + "Delivery error\n" + "\n"; List<SentMail> sentMails = fakeMailContext.getSentMails(); assertThat(sentMails).hasSize(1); SentMail sentMail = sentMails.get(0); MimeMessage sentMessage = sentMail.getMsg(); MimeMultipart content = (MimeMultipart) sentMessage.getContent(); BodyPart bodyPart = content.getBodyPart(0); assertThat(bodyPart.getContentType()).isEqualTo("text/plain; charset=us-ascii"); assertThat(bodyPart.getContent()).isEqualTo(expectedContent); }
From source file:org.noorganization.instalist.server.api.TagResource.java
/** * Get a single tag./*from w w w . j av a2 s .co m*/ * @param _groupId The id of the group containing the tag. * @param _tagUUID The uuid of the requested tag. */ @GET @TokenSecured @Path("{taguuid}") @Produces({ "application/json" }) public Response getTag(@PathParam("groupid") int _groupId, @PathParam("taguuid") String _tagUUID) throws Exception { UUID toFind; try { toFind = UUID.fromString(_tagUUID); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } EntityManager manager = DatabaseHelper.getInstance().getManager(); ITagController tagController = ControllerFactory.getTagController(manager); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); Tag current = tagController.findByGroupAndUUID(group, toFind); if (current == null) { if (tagController.findDeletedByGroupAndUUID(group, toFind) == null) { manager.close(); return ResponseFactory.generateNotFound(new Error().withMessage("Tag was not " + "found.")); } manager.close(); return ResponseFactory.generateGone(new Error().withMessage("Tag was deleted " + "before.")); } manager.close(); TagInfo rtn = new TagInfo().withDeleted(false); rtn.setUUID(current.getUUID()); rtn.setName(current.getName()); rtn.setLastChanged(Date.from(current.getUpdated())); return ResponseFactory.generateOK(rtn); }
From source file:org.apache.james.jmap.utils.FilterToSearchQueryTest.java
@Test public void filterConditionShouldMapWhenBefore() { ZonedDateTime before = ZonedDateTime.now(); SearchQuery expectedSearchQuery = new SearchQuery(); expectedSearchQuery/*from w ww . ja v a 2 s. c o m*/ .andCriteria(SearchQuery.internalDateBefore(Date.from(before.toInstant()), DateResolution.Second)); SearchQuery searchQuery = new FilterToSearchQuery() .convert(FilterCondition.builder().before(before).build()); assertThat(searchQuery).isEqualTo(expectedSearchQuery); }
From source file:org.gameontext.map.auth.PlayerClient.java
/** * Obtain a JWT for the player id that can be used to invoke player REST services. * * We can create this, because we have access to the private certificate * required to sign such a JWT.// w ww. j av a2 s . com * * @param playerId The id to build the JWT for * @return The JWT as a string. * @throws IOException */ private String buildClientJwtForId(String playerId) throws IOException { // grab the key if needed if (signingKey == null) getKeyStoreInfo(); Claims onwardsClaims = Jwts.claims(); // Set the subject using the "id" field from our claims map. onwardsClaims.setSubject(playerId); // We'll use this claim to know this is a user token onwardsClaims.setAudience("client"); // we set creation time to 24hrs ago, to avoid timezone issues // client JWT has 24 hrs validity from now. Instant timePoint = Instant.now(); onwardsClaims.setIssuedAt(Date.from(timePoint.minus(hours24))); onwardsClaims.setExpiration(Date.from(timePoint.plus(hours24))); // finally build the new jwt, using the claims we just built, signing it // with our signing key, and adding a key hint as kid to the encryption // header, which is optional, but can be used by the receivers of the // jwt to know which key they should verifiy it with. String newJwt = Jwts.builder().setHeaderParam("kid", "playerssl").setClaims(onwardsClaims) .signWith(SignatureAlgorithm.RS256, signingKey).compact(); return newJwt; }
From source file:org.codice.ddf.registry.federationadmin.service.impl.RegistryPublicationServiceImpl.java
@Override public void update(Metacard metacard) throws FederationAdminException { List<String> publishedLocations = RegistryUtility.getListOfStringAttribute(metacard, RegistryObjectMetacardType.PUBLISHED_LOCATIONS); if (publishedLocations.isEmpty()) { return;//from ww w . j a va 2 s. c o m } Set<String> locations = publishedLocations.stream().map(registryId -> getSourceIdFromRegistryId(registryId)) .filter(Objects::nonNull).collect(Collectors.toCollection(HashSet::new)); if (CollectionUtils.isNotEmpty(locations)) { try { LOGGER.info("Updating publication for registry entry {}:{} at {}", metacard.getTitle(), RegistryUtility.getRegistryId(metacard), String.join(",", locations)); federationAdminService.updateRegistryEntry(metacard, locations); } catch (FederationAdminException e) { // This should not happen often but could occur if the remote registry removed the metacard // that was to be updated. In that case performing an add will fix the problem. If the // failure // was for another reason like the site couldn't be contacted then the add will fail // also and the end result will be the same. federationAdminService.addRegistryEntry(metacard, locations); } metacard.setAttribute(new AttributeImpl(RegistryObjectMetacardType.LAST_PUBLISHED, Date.from(ZonedDateTime.now().toInstant()))); federationAdminService.updateRegistryEntry(metacard); } }