List of usage examples for java.time Instant parse
public static Instant parse(final CharSequence text)
From source file:fr.ffremont.caching.CacheControlService.java
/** * Utilisation du If-Modified-Since//from w w w.ja v a2s . com * Ma ressource est mise en cache pendant 10sec puis une revalidation lieu pour renouveler les 10sec. * * * @param httpRequest * @return */ @GET @Path("validationtps") public Response validationTps(@Context HttpServletRequest httpRequest) { javax.ws.rs.core.CacheControl cache = new javax.ws.rs.core.CacheControl(); cache.setMaxAge(10); cache.setMustRevalidate(true); cache.setPrivate(false); Instant updated = Instant.parse("2011-12-03T10:15:30Z"); LOG.info("Cache par validation de temps"); Response.ResponseBuilder builder = request.evaluatePreconditions(Date.from(updated)); if (builder == null) { builder = Response.ok("Ma petite donne").lastModified(Date.from(updated)); } builder.cacheControl(cache); return builder.build(); }
From source file:com.torodb.mongodb.core.DefaultBuildProperties.java
public DefaultBuildProperties(String propertiesFile) { PropertiesConfiguration properties;/*from w ww. j a va 2 s . c om*/ try { properties = new PropertiesConfiguration(Resources.getResource(propertiesFile)); } catch (ConfigurationException e) { throw new RuntimeException("Cannot read build properties file '" + propertiesFile + "'"); } fullVersion = properties.getString("version"); Matcher matcher = FULL_VERSION_PATTERN.matcher(fullVersion); if (!matcher.matches()) { throw new RuntimeException("Invalid version string '" + fullVersion + "'"); } majorVersion = Integer.parseInt(matcher.group(1)); minorVersion = Integer.parseInt(matcher.group(2)); subVersion = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0; extraVersion = matcher.group(4); // DateUtils.parseDate may be replaced by SimpleDateFormat if using Java7 try { buildTime = Instant.parse(properties.getString("buildTimestamp")); } catch (DateTimeParseException e) { throw new RuntimeException("buildTimestamp property not in ISO8601 format", e); } gitCommitId = properties.getString("gitCommitId"); gitBranch = properties.getString("gitBranch"); gitRemoteOriginUrl = properties.getString("gitRemoteOriginURL"); javaVersion = properties.getString("javaVersion"); javaVendor = properties.getString("javaVendor"); javaVmSpecificationVersion = properties.getString("javaVMSpecificationVersion"); javaVmVersion = properties.getString("javaVMVersion"); osName = properties.getString("osName"); osArch = properties.getString("osArch"); osVersion = properties.getString("osVersion"); }
From source file:com.orange.ngsi2.model.SubscriptionTest.java
@Test public void serializationSubscriptionTest() throws JsonProcessingException, MalformedURLException { ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter()); SubjectEntity subjectEntity = new SubjectEntity(); subjectEntity.setId(Optional.of("Bcn_Welt")); subjectEntity.setType(Optional.of("Room")); Condition condition = new Condition(); condition.setAttributes(Collections.singletonList("temperature")); condition.setExpression("q", "temperature>40"); SubjectSubscription subjectSubscription = new SubjectSubscription(Collections.singletonList(subjectEntity), condition);// ww w .jav a2 s .co m List<String> attributes = new ArrayList<>(); attributes.add("temperature"); attributes.add("humidity"); Notification notification = new Notification(attributes, new URL("http://localhost:1234")); notification.setThrottling(Optional.of(new Long(5))); notification.setTimesSent(12); notification.setLastNotification(Instant.parse("2015-10-05T16:00:00.10Z")); notification.setHeader("X-MyHeader", "foo"); notification.setQuery("authToken", "bar"); notification.setAttrsFormat(Optional.of(Notification.Format.keyValues)); String json = writer.writeValueAsString(new Subscription("abcdefg", subjectSubscription, notification, Instant.parse("2016-04-05T14:00:00.20Z"), Subscription.Status.active)); assertEquals(jsonString, json); }
From source file:com.gigglinggnus.controllers.ModifyAppointmentController.java
/** * * @param request servlet request//from ww w .j ava 2 s. c o 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 { EntityManager em = (EntityManager) request.getSession().getAttribute("em"); Clock clk = (Clock) (request.getSession().getAttribute("clock")); boolean modified = false; String userId = request.getParameter("userid"); User user = em.find(User.class, userId); String examId = request.getParameter("examid"); Exam exam = em.find(Exam.class, examId); Appointment appt = user.getAppointmentByExam(exam); String startTime = request.getParameter("startTime"); String seatZone = request.getParameter("seatingZone"); String seatNum = request.getParameter("seatNum"); String cancel = request.getParameter("cancel"); try { em.getTransaction().begin(); if (startTime != "") { appt.changeStartTime(Instant.parse(startTime), clk); em.persist(appt); modified = true; } if (seatZone != "") { appt.setSeatingZone(Seating.parse(seatZone)); em.persist(appt); modified = true; } if (seatNum != "") { appt.setSeatNum(Integer.parseInt(seatNum)); em.persist(appt); modified = true; } em.getTransaction().commit(); } catch (Exception e) { em.getTransaction().rollback(); request.setAttribute("msg", e); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } if (cancel != null) { request.setAttribute("msg", "Appointment cancelled"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } if (modified == true) { request.setAttribute("msg", "Appointment modified"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } else { request.setAttribute("msg", "Appointment unchanged"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } }
From source file:de.qaware.chronix.lucene.client.stream.date.DateQueryParser.java
/** * Converts the given date term into a numeric representation * * @param dateTerm the date term, e.g, start:NOW+30DAYS * @return the long representation of the date term * @throws ParseException if the date term could not be evaluated */// ww w . java 2s . c om private long getNumberRepresentation(String dateTerm) throws ParseException { long numberRepresentation; if (StringUtils.isNumeric(dateTerm)) { numberRepresentation = Long.valueOf(dateTerm); } else if (solrDateMathPattern.matcher(dateTerm).matches()) { numberRepresentation = parseDateTerm(dateTerm); } else if (instantDatePattern.matcher(dateTerm).matches()) { numberRepresentation = Instant.parse(dateTerm).toEpochMilli(); } else { throw new ParseException("Could not parse date representation '" + dateTerm + "'", 0); } return numberRepresentation; }
From source file:com.orange.cepheus.broker.persistence.SubscriptionsRepository.java
/** * Get all subscriptions saved/*from www .j a va2 s .co m*/ * @return subscriptions map * @throws SubscriptionPersistenceException */ public Map<String, Subscription> getAllSubscriptions() throws SubscriptionPersistenceException { Map<String, Subscription> subscriptions = new ConcurrentHashMap<>(); try { List<Subscription> subscriptionList = jdbcTemplate.query( "select id, expirationDate, subscribeContext from t_subscriptions", (ResultSet rs, int rowNum) -> { Subscription subscription = new Subscription(); try { subscription.setSubscriptionId(rs.getString("id")); subscription.setExpirationDate(Instant.parse(rs.getString("expirationDate"))); subscription.setSubscribeContext( mapper.readValue(rs.getString("subscribeContext"), SubscribeContext.class)); } catch (IOException e) { throw new SQLException(e); } return subscription; }); subscriptionList .forEach(subscription -> subscriptions.put(subscription.getSubscriptionId(), subscription)); } catch (DataAccessException e) { throw new SubscriptionPersistenceException(e); } return subscriptions; }
From source file:com.coveo.spillway.storage.RedisStorage.java
@Override public Map<LimitKey, Integer> debugCurrentLimitCounters() { Map<LimitKey, Integer> counters = new HashMap<>(); Set<String> keys = jedis.keys(keyPrefix + KEY_SEPARATOR + "*"); for (String key : keys) { int value = Integer.parseInt(jedis.get(key)); String[] keyComponents = StringUtils.split(key, KEY_SEPARATOR); counters.put(new LimitKey(keyComponents[1], keyComponents[2], keyComponents[3], Instant.parse(keyComponents[4])), value); }/*from ww w. j a v a 2 s .c o m*/ return counters; }
From source file:com.orange.cepheus.broker.persistence.RegistrationsRepository.java
/** * Get all saved registrations/*from w w w . ja v a2s . c om*/ * @return registrations map * @throws RegistrationPersistenceException */ public Map<String, Registration> getAllRegistrations() throws RegistrationPersistenceException { Map<String, Registration> registrations = new ConcurrentHashMap<>(); try { List<Registration> registrationList = jdbcTemplate.query( "select id, expirationDate, registerContext from t_registrations", (ResultSet rs, int rowNum) -> { Registration registration = new Registration(); try { registration.setExpirationDate(Instant.parse(rs.getString("expirationDate"))); registration.setRegisterContext( mapper.readValue(rs.getString("registerContext"), RegisterContext.class)); } catch (IOException e) { throw new SQLException(e); } return registration; }); registrationList.forEach(registration -> registrations .put(registration.getRegisterContext().getRegistrationId(), registration)); } catch (DataAccessException e) { throw new RegistrationPersistenceException(e); } return registrations; }
From source file:com.example.test.HibernateBookRepositoryTest.java
private void persistBooks(Supplier<AbstractBook> bookSupplier) throws Exception { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override//from www . ja va 2 s. co m protected void doInTransactionWithoutResult(TransactionStatus ts) { Session session = getCurrentSession(); Category softwareDevelopment = new Category(); softwareDevelopment.setName("Software development"); session.persist(softwareDevelopment); Category systemDesign = new Category(); systemDesign.setName("System design"); session.persist(systemDesign); Author martinFowler = new Author(); martinFowler.setFullName("Martin Fowler"); session.persist(martinFowler); AbstractBook poeaa = bookSupplier.get(); poeaa.setIsbn("007-6092019909"); poeaa.setTitle("Patterns of Enterprise Application Architecture"); poeaa.setPublicationDate(Date.from(Instant.parse("2002-11-15T00:00:00.00Z"))); poeaa.setAuthors(asList(martinFowler)); poeaa.setCategories(asList(softwareDevelopment, systemDesign)); session.persist(poeaa); Author gregorHohpe = new Author(); gregorHohpe.setFullName("Gregor Hohpe"); session.persist(gregorHohpe); Author bobbyWoolf = new Author(); bobbyWoolf.setFullName("Bobby Woolf"); session.persist(bobbyWoolf); AbstractBook eip = bookSupplier.get(); eip.setIsbn("978-0321200686"); eip.setTitle("Enterprise Integration Patterns"); eip.setPublicationDate(Date.from(Instant.parse("2003-10-20T00:00:00.00Z"))); eip.setAuthors(asList(gregorHohpe, bobbyWoolf)); eip.setCategories(asList(softwareDevelopment, systemDesign)); session.persist(eip); Category objectOrientedSoftwareDesign = new Category(); objectOrientedSoftwareDesign.setName("Object-Oriented Software Design"); session.persist(objectOrientedSoftwareDesign); Author ericEvans = new Author(); ericEvans.setFullName("Eric Evans"); session.persist(ericEvans); AbstractBook ddd = bookSupplier.get(); ddd.setIsbn("860-1404361814"); ddd.setTitle("Domain-Driven Design: Tackling Complexity in the Heart of Software"); ddd.setPublicationDate(Date.from(Instant.parse("2003-08-01T00:00:00.00Z"))); ddd.setAuthors(asList(ericEvans)); ddd.setCategories(asList(softwareDevelopment, systemDesign, objectOrientedSoftwareDesign)); session.persist(ddd); Category networkingCloudComputing = new Category(); networkingCloudComputing.setName("Networking & Cloud Computing"); session.persist(networkingCloudComputing); Category databasesBigData = new Category(); databasesBigData.setName("Databases & Big Data"); session.persist(databasesBigData); Author pramodSadalage = new Author(); pramodSadalage.setFullName("Pramod J. Sadalage"); session.persist(pramodSadalage); AbstractBook nosql = bookSupplier.get(); nosql.setIsbn("978-0321826626"); nosql.setTitle("NoSQL Distilled: A Brief Guide to the Emerging World of Polyglot Persistence"); nosql.setPublicationDate(Date.from(Instant.parse("2012-08-18T00:00:00.00Z"))); nosql.setAuthors(asList(pramodSadalage, martinFowler)); nosql.setCategories(asList(networkingCloudComputing, databasesBigData)); session.persist(nosql); } }); System.out.println("##################################################"); }
From source file:com.linecorp.bot.servlet.LineBotCallbackRequestParserTest.java
@Test public void testCallRequest() throws Exception { InputStream resource = getClass().getClassLoader().getResourceAsStream("callback-request.json"); byte[] requestBody = ByteStreams.toByteArray(resource); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("X-Line-Signature", "SSSSIGNATURE"); request.setContent(requestBody);/*from ww w. j a v a 2 s.co m*/ doReturn(true).when(lineSignatureValidator).validateSignature(requestBody, "SSSSIGNATURE"); CallbackRequest callbackRequest = lineBotCallbackRequestParser.handle(request); assertThat(callbackRequest).isNotNull(); final List<Event> result = callbackRequest.getEvents(); final MessageEvent messageEvent = (MessageEvent) result.get(0); final TextMessageContent text = (TextMessageContent) messageEvent.getMessage(); assertThat(text.getText()).isEqualTo("Hello, world"); final String followedUserId = messageEvent.getSource().getUserId(); assertThat(followedUserId).isEqualTo("u206d25c2ea6bd87c17655609a1c37cb8"); assertThat(messageEvent.getTimestamp()).isEqualTo(Instant.parse("2016-05-07T13:57:59.859Z")); }