List of usage examples for java.time LocalDate parse
public static LocalDate parse(CharSequence text)
From source file:svc.data.citations.datasources.tyler.TylerCitationDataSourceTest.java
@SuppressWarnings("unchecked") @Test//from ww w.ja v a 2 s .c o m public void returnsCitationsGivenCitationNumberAndDOB() { final String CITATIONNUMBER = "F3453"; final LocalDate DOB = LocalDate.parse("2000-06-01"); mockTylerConfiguration.rootUrl = "http://myURL.com"; mockTylerConfiguration.apiKey = "1234"; final Citation CITATION = new Citation(); CITATION.id = 3; final List<Citation> CITATIONS = Lists.newArrayList(CITATION); final List<TylerCitation> tylerCitations = Lists.newArrayList(); Mockito.doReturn(tylerCitations).when(tylerCitationsResponseSpy).getBody(); when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(HttpEntity.class), any(ParameterizedTypeReference.class))).thenReturn(tylerCitationsResponseSpy); when(mockCitationTransformer.fromTylerCitations(tylerCitations)).thenReturn(CITATIONS); when(mockCitationFilter.RemoveCitationsWithExpiredDates(CITATIONS)).thenReturn(CITATIONS); List<Citation> citations = mockTylerCitationDataSource.getByCitationNumberAndDOB(CITATIONNUMBER, DOB); assertThat(citations.get(0).id, is(3)); }
From source file:de.lgblaumeiser.ptm.rest.BookingRestController.java
@RequestMapping(method = RequestMethod.POST, value = "/{dayString}") public ResponseEntity<?> addBooking(@PathVariable String dayString, @RequestBody BookingBody newData) { LocalDate day = LocalDate.parse(dayString); Activity activity = services.activityStore().retrieveById(valueOf(newData.activityId)) .orElseThrow(IllegalStateException::new); Booking newBooking = services.bookingService().addBooking(day, newData.user, activity, parse(newData.starttime), newData.comment); if (newData.endtime != null) { newBooking = services.bookingService().endBooking(newBooking, parse(newData.endtime)); }//from ww w.ja v a2s . co m URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{day}/{id}") .buildAndExpand(day.format(ISO_LOCAL_DATE), newBooking.getId()).toUri(); return ResponseEntity.created(location).build(); }
From source file:org.openmhealth.shimmer.common.controller.LegacyDataPointSearchController.java
/** * Endpoint for retrieving data from shims. * * @param username User ID record for which to retrieve data, if not approved this will throw ShimException. * <p>/* w w w.j av a2 s . c o m*/ * TODO: finish javadoc! * @return The shim data response wrapper with data from the shim. */ @RequestMapping(value = "/data/{shim}/{dataType}", produces = APPLICATION_JSON_VALUE) public ShimDataResponse data(@RequestParam(value = "username") String username, @PathVariable("shim") String shim, @PathVariable("dataType") String dataTypeKey, @RequestParam(value = "normalize", defaultValue = "true") boolean normalize, @RequestParam(value = "dateStart", defaultValue = "") String dateStart, @RequestParam(value = "dateEnd", defaultValue = "") String dateEnd) throws ShimException { setPassThroughAuthentication(username, shim); ShimDataRequest shimDataRequest = new ShimDataRequest(); shimDataRequest.setDataTypeKey(dataTypeKey); shimDataRequest.setNormalize(normalize); if (!dateStart.isEmpty()) { shimDataRequest.setStartDateTime(LocalDate.parse(dateStart).atStartOfDay().atOffset(UTC)); } if (!dateEnd.isEmpty()) { shimDataRequest.setEndDateTime(LocalDate.parse(dateEnd).atStartOfDay().atOffset(UTC)); } AccessParameters accessParameters = accessParametersRepo.findByUsernameAndShimKey(username, shim, new Sort(Sort.Direction.DESC, "dateCreated")); if (accessParameters == null) { throw new ShimException("User '" + username + "' has not authorized shim: '" + shim + "'"); } shimDataRequest.setAccessParameters(accessParameters); return shimRegistry.getShim(shim).getData(shimDataRequest); }
From source file:com.marklogic.tableauextract.ExtractFromJSON.java
/** * Read JSON output from MarkLogic REST extension or *.xqy file and insert * the output into a Tabeleau table/*w ww.ja va 2 s .c o m*/ * * @param table * @throws TableauException */ private static void insertData(Table table) throws TableauException, FileNotFoundException, ParseException, IOException { TableDefinition tableDef = table.getTableDefinition(); Row row = new Row(tableDef); URL url = new URL("http://localhost:8060/json.xqy"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(bufferedReader); JSONArray claims = (JSONArray) jsonObject.get("claims"); @SuppressWarnings("unchecked") Iterator<JSONObject> i = claims.iterator(); while (i.hasNext()) { JSONObject innerObject = i.next(); String idString = (String) innerObject.get("id"); row.setInteger(0, Integer.parseInt(idString.substring(0, 6))); row.setCharString(1, (String) innerObject.get("ssn")); row.setCharString(2, (String) innerObject.get("type")); String payString = (String) innerObject.get("payment_amount"); if (payString == null || payString.isEmpty()) payString = "0.0"; row.setDouble(3, Double.parseDouble(payString)); String dtString = (String) innerObject.get("claim_date"); if (dtString == null || dtString.isEmpty()) dtString = "1999-01-01"; LocalDate claimDate = (LocalDate.parse(dtString)); row.setDate(4, claimDate.getYear(), claimDate.getMonthValue(), claimDate.getDayOfMonth()); table.insert(row); } /* row.setDateTime( 0, 2012, 7, 3, 11, 40, 12, 4550); // Purchased row.setCharString(1, "Beans"); // Product row.setString( 2, "uniBeans"); // uProduct row.setDouble( 3, 1.08); // Price row.setDate( 6, 2029, 1, 1); // Expiration date row.setCharString(7, "Bohnen"); // Produkt for ( int i = 0; i < 10; ++i ) { row.setInteger(4, i * 10); // Quantity row.setBoolean(5, i % 2 == 1); // Taxed } */ }
From source file:org.ojbc.adapters.analyticsstaging.custody.dao.TestAnalyticalDatastoreDAOImpl.java
@Test public void testSaveBooking() throws Exception { int personPk = analyticalDatastoreDAO.savePerson(getStaticPerson()); assertEquals(1, personPk);/* w w w. j av a2 s . co m*/ Booking booking = new Booking(); booking.setPersonId(personPk); booking.setBookingDate(LocalDate.parse("2013-12-17")); booking.setBookingTime(LocalTime.parse("09:30:00")); booking.setScheduledReleaseDate(LocalDate.parse("2014-12-17")); booking.setFacilityId(1); booking.setSupervisionUnitTypeId(2); booking.setBookingNumber("bookingNumber"); booking.setInmateJailResidentIndicator(true); int bookingPk = analyticalDatastoreDAO.saveBooking(booking); assertEquals(1, bookingPk); analyticalDatastoreDAO.deleteBooking(bookingPk); Booking matchingBooking = analyticalDatastoreDAO.getBookingByBookingNumber("bookingNumber"); assertNull(matchingBooking); personPk = analyticalDatastoreDAO.savePerson(getStaticPerson()); booking.setPersonId(personPk); //Perform an subsequent save and confirm the same PK booking.setBookingId(bookingPk); int updatedbookingId = analyticalDatastoreDAO.saveBooking(booking); assertEquals(updatedbookingId, bookingPk); }
From source file:rapture.dp.invocable.calendar.steps.CalendarLookupStep.java
@Override public String invoke(CallingContext ctx) { DecisionApi decision = Kernel.getDecision(); try {/*from www. ja v a 2s. co m*/ decision.setContextLiteral(ctx, getWorkerURI(), "STEPNAME", getStepName()); String dateStr = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "DATE")); String calendar = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "CALENDAR")); String translator = StringUtils .stripToNull(decision.getContextValue(ctx, getWorkerURI(), "TRANSLATOR")); if (translator == null) translator = StringUtils .stripToNull(decision.getContextValue(ctx, getWorkerURI(), "DEFAULT_TRANSLATOR")); LocalDate date = (dateStr == null) ? LocalDate.now() : LocalDate.parse(dateStr); // Translate the date to a name - eg Good Friday, Yom Kippur, Thanksgiving // Expected format is a map of dates (with or without years) to names or lists of names // Example: // { // "31Dec" : ["New Tear's Eve", "Hogmanay"] , // "05Sep2016" : "Labor Day", // "04Sep2017" : "Labor Day" // "2015-01-01" : "New Year's Day" // } Map<String, Object> calendarTable = new HashMap<>(); if (calendar != null) { String calendarJson = StringUtils.stripToNull(Kernel.getDoc().getDoc(ctx, calendar)); if (calendarJson != null) { calendarTable = JacksonUtil.getMapFromJson(calendarJson); } } // Translate the date to a name - eg Good Friday, Yom Kippur, Thanksgiving Map<String, Object> translationTable = new HashMap<>(); if (translator != null) { String translationJson = StringUtils.stripToNull(Kernel.getDoc().getDoc(ctx, translator)); if (translationJson != null) { translationTable = JacksonUtil.getMapFromJson(translationJson); } } List<String> lookup = new ArrayList<>(); String languageTag = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "LOCALE")); Locale locale = (languageTag == null) ? Locale.getDefault() : Locale.forLanguageTag(languageTag); for (DateTimeFormatter formatter : ImmutableList.of(DateTimeFormatter.ISO_LOCAL_DATE, DateTimeFormatter.ofPattern("ddMMMuuuu", locale), DateTimeFormatter.ofPattern("ddMMM", locale), DateTimeFormatter.ofPattern("MMMdduuuu", locale), DateTimeFormatter.ofPattern("MMMdd", locale), DateTimeFormatter.ofPattern("uuuuMMMdd", locale))) { String formattedDate = date.format(formatter); Object transList = translationTable.get(formattedDate); if (transList != null) { if (transList instanceof Iterable) { for (Object o : (Iterable) transList) { lookup.add(o.toString()); } } else lookup.add(transList.toString()); } lookup.add(formattedDate); } lookup.add(DayOfWeek.from(date).getDisplayName(TextStyle.FULL, locale)); decision.setContextLiteral(ctx, getWorkerURI(), "DATE_TRANSLATIONS", JacksonUtil.jsonFromObject(lookup)); // Calendar table defines the priority. getMapFromJson returns a LinkedHashMap so order is preserved. for (Entry<String, Object> calEntry : calendarTable.entrySet()) { if (lookup.contains(calEntry.getKey())) { decision.setContextLiteral(ctx, getWorkerURI(), "CALENDAR_LOOKUP_ENTRY", JacksonUtil.jsonFromObject(calEntry)); decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), calEntry.getKey() + " matched as " + calEntry.getValue().toString(), false); return calEntry.getValue().toString(); } } decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), getStepName() + ": No matches for " + DateTimeFormatter.ISO_LOCAL_DATE.format(date) + " found in calendar", false); return getNextTransition(); } catch (Exception e) { decision.setContextLiteral(ctx, getWorkerURI(), getStepName(), "Unable to access the calendar : " + e.getLocalizedMessage()); decision.setContextLiteral(ctx, getWorkerURI(), getStepName() + "Error", ExceptionToString.summary(e)); decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), "Problem in " + getStepName() + ": " + ExceptionToString.getRootCause(e).getLocalizedMessage(), true); return getErrorTransition(); } }
From source file:org.openlmis.fulfillment.service.referencedata.PeriodReferenceDataServiceTest.java
@Test public void shouldReturnOrderablesById() { ProcessingPeriodDto period = mockPageResponseEntityAndGetDto(); String startDate = "2018-04-05"; String endDate = "2018-05-05"; List<ProcessingPeriodDto> response = service.search(LocalDate.parse(startDate), LocalDate.parse(endDate)); assertThat(response, hasSize(1));/*from ww w . j ava 2s. c o m*/ assertThat(response, hasItems(period)); verify(restTemplate).exchange(uriCaptor.capture(), eq(HttpMethod.GET), entityCaptor.capture(), refEq(new DynamicPageTypeReference<>(ProcessingPeriodDto.class))); URI uri = uriCaptor.getValue(); assertEquals(serviceUrl + service.getUrl() + "?startDate=" + startDate + "&endDate=" + endDate, uri.toString()); assertAuthHeader(entityCaptor.getValue()); assertNull(entityCaptor.getValue().getBody()); }
From source file:org.openmhealth.shim.withings.mapper.WithingsDailyStepCountDataPointMapper.java
/** * Maps an individual list node from the array in the Withings activity measure endpoint response into a {@link * StepCount} data point./*w ww.ja v a 2s. c om*/ * * @param node activity node from the array "activites" contained in the "body" of the endpoint response * @return a {@link DataPoint} object containing a {@link StepCount} measure with the appropriate values from * the JSON node parameter, wrapped as an {@link Optional} */ @Override Optional<DataPoint<StepCount>> asDataPoint(JsonNode node) { long stepValue = asRequiredLong(node, "steps"); StepCount.Builder stepCountBuilder = new StepCount.Builder(stepValue); Optional<String> dateString = asOptionalString(node, "date"); Optional<String> timeZoneFullName = asOptionalString(node, "timezone"); // We assume that timezone is the same for both the startdate and enddate timestamps, even though Withings only // provides the enddate timezone as the "timezone" property. // TODO: Revisit once Withings can provide start_timezone and end_timezone if (dateString.isPresent() && timeZoneFullName.isPresent()) { LocalDateTime localStartDateTime = LocalDate.parse(dateString.get()).atStartOfDay(); ZoneId zoneId = ZoneId.of(timeZoneFullName.get()); ZonedDateTime zonedDateTime = ZonedDateTime.of(localStartDateTime, zoneId); ZoneOffset offset = zonedDateTime.getOffset(); OffsetDateTime offsetStartDateTime = OffsetDateTime.of(localStartDateTime, offset); LocalDateTime localEndDateTime = LocalDate.parse(dateString.get()).atStartOfDay().plusDays(1); OffsetDateTime offsetEndDateTime = OffsetDateTime.of(localEndDateTime, offset); stepCountBuilder.setEffectiveTimeFrame( TimeInterval.ofStartDateTimeAndEndDateTime(offsetStartDateTime, offsetEndDateTime)); } Optional<String> userComment = asOptionalString(node, "comment"); if (userComment.isPresent()) { stepCountBuilder.setUserNotes(userComment.get()); } StepCount stepCount = stepCountBuilder.build(); DataPoint<StepCount> stepCountDataPoint = newDataPoint(stepCount, null, true, null); return Optional.of(stepCountDataPoint); }
From source file:com.gigglinggnus.controllers.DisplayUtilizationController.java
/** * * @param request servlet request/* w w w . j a v a 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 { String msg = request.getParameter("msg"); EntityManager em = (EntityManager) request.getSession().getAttribute("em"); Clock clk = (Clock) (request.getSession().getAttribute("clock")); Term term = Term.getTermforInstant(em, Instant.now(clk)); LocalDate start = LocalDate.parse(request.getParameter("start")); LocalDate end = LocalDate.parse(request.getParameter("end")); JSONArray json = new JSONArray(); for (LocalDate i = start; i.isBefore(end); i = i.plusDays(1)) { double utilization = term.utilizationForDay(start, clk); JSONObject elem = new JSONObject(); elem.put("day", i); elem.put("utilization", utilization); json.put(elem); } response.getWriter().write(json.toString()); }
From source file:org.silverpeas.core.workflow.api.user.ReplacementListTest.java
@SuppressWarnings("unchecked") @BeforeEach/*from ww w . ja v a 2s.c o m*/ void populate() throws IllegalAccessException { final List<ReplacementImpl> list = new ArrayList<>(); list.add(replacement("1", "2", LocalDate.parse("2019-04-11"), LocalDate.parse("2019-04-11"))); list.add(replacement("3", "4", LocalDate.parse("2019-04-13"), LocalDate.parse("2019-04-13"))); list.add(replacement("5", "6", LocalDate.parse("2019-04-11"), LocalDate.parse("2019-04-13"))); list.add(replacement("1", "3", LocalDate.parse("2019-04-12"), LocalDate.parse("2019-04-13"))); replacements = new ReplacementList(list); }