/** * Grab random holiday from the equivalence class that falls between the two dates * * @param earliest the earliest date parameter as defined in the model * @param latest the latest date parameter as defined in the model * @return a holiday that falls between the dates */ public String getRandomHoliday(String earliest, String latest) { String dateString = ""; DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime earlyDate = parser.parseDateTime(earliest); DateTime lateDate = parser.parseDateTime(latest); List<Holiday> holidays = new LinkedList<>(); int min = Integer.parseInt(earlyDate.toString().substring(0, 4)); int max = Integer.parseInt(lateDate.toString().substring(0, 4)); int range = max - min + 1; int randomYear = (int) (Math.random() * range) + min; for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) { holidays.add(s); } Collections.shuffle(holidays); for (Holiday holiday : holidays) { dateString = convertToReadableDate(holiday.forYear(randomYear)); if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) { break; } } return dateString; }
// @@author A0124206W // checks if explicit mentioned dates in the form of MM/dd/yyyy and // MM/dd/yyyy HH:mm are valid. private boolean isValidExplicitDate(String dateString) throws Exception { logger.log(Level.FINE, "checking date: " + dateString); dateString = dateString.replace(DATE_SPLITTER_SLASH, DATE_SPLITTER_DOT); if (!dateString.contains(DATE_SPLITTER_DOT)) { // is not an explicit date return true; } // check if date has time and if there is exactly one date if (dateString.contains(DATE_SPLITTER_COLON) && (dateString.length() <= NUM_CHAR_DATE_TIME_INPUT)) { timeFormatter.parseDateTime(dateString); } else if (dateString.length() <= NUM_CHAR_DATE_INPUT) { timeFormatter.parseDateTime(dateString + DUMMY_TIME); } else { // there is more than 1 date (should be 2) String[] dateStringArray = splitDates(dateString); if (dateStringArray.length != DATE_GROUP_TWO_DATE) { throw new Exception(); } else { isValidExplicitDate(dateStringArray[PARSED_DATE_TEXT_FIRST]); isValidExplicitDate(dateStringArray[PARSED_DATE_TEXT_SECOND]); } } return true; }
/** * @param isNullable isNullable * @param earliest lower boundary date * @param latest upper boundary date * @param onlyBusinessDays only business days * @return a list of boundary dates */ public List<String> positiveCase( boolean isNullable, String earliest, String latest, boolean onlyBusinessDays) { List<String> values = new LinkedList<>(); if (earliest.equalsIgnoreCase(latest)) { values.add(earliest); if (isNullable) { values.add(""); } return values; } DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime earlyDate = parser.parseDateTime(earliest); DateTime lateDate = parser.parseDateTime(latest); String earlyDay = parser.print(earlyDate); String nextDay = getNextDay(earlyDate.toString().substring(0, 10), onlyBusinessDays); String prevDay = getPreviousDay(lateDate.toString().substring(0, 10), onlyBusinessDays); String lateDay = parser.print(lateDate); values.add(earlyDay); values.add(nextDay); values.add(prevDay); values.add(lateDay); if (isNullable) { values.add(""); } return values; }
private void ensureOpen() throws IOException { if (table == null) { table = DataIO.table(new File(file), null); rowsIterator = (TableIterator<String[]>) table.rows().iterator(); /* * If tStart is null then the reader try to read all the value in the file, nb time step constant. */ if (tStart == null) { String secondTime = null; // get the first time in the file. if (rowsIterator.hasNext()) { String[] row = rowsIterator.next(); tStart = row[1]; } // get the time of the second row in the file. if (rowsIterator.hasNext()) { String[] row = rowsIterator.next(); secondTime = row[1]; } // the dt is equal to the fifference of the time of 2 rows. tTimestep = formatter.parseDateTime(secondTime).getMinuteOfDay() - formatter.parseDateTime(tStart).getMinuteOfDay(); // close and reopen to read the row. rowsIterator.close(); rowsIterator = (TableIterator<String[]>) table.rows().iterator(); } } }
@PostConstruct public void createSampleData() { // create sample task groups TaskGroup inbox = persist(prepareTaskGroup(1L, "Inbox")); TaskGroup shoppingList = persist(prepareTaskGroup(2L, "Shopping list")); TaskGroup atHome = persist(prepareTaskGroup(3L, "At home")); TaskGroup atWork = persist(prepareTaskGroup(4L, "At work")); // create sample tasks persist(prepareTask(1L, "Buy some fruits", shoppingList, TaskPriority.NORMAL, null, null)); persist( prepareTask( 2L, "Write article for personal blog", atHome, TaskPriority.IMPORTANT, DATE_FORMATTER.parseDateTime("2012-06-11"), null)); persist( prepareTask( 3L, "Ask Claudia about project progress", atWork, TaskPriority.NORMAL, DATE_FORMATTER.parseDateTime("2012-06-15"), null)); persist( prepareTask( 4L, "Call to Tom Simson for help", inbox, TaskPriority.NORMAL, DATE_FORMATTER.parseDateTime("2012-06-12"), TIME_FORMATTER.parseDateTime("14:00"))); }
// Iterate through data and if tuple datetime is within window pass to the x/y arrays // Returns nothing, but gets x/y arrays for the Regression calculations public void getArrays() throws SQLException { String dateObjectString; DateTime dateObject; DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); DateTime queryTimeObject = format.parseDateTime(queryTime); Double tupDateMS = null; Double tupValue = null; // Initialize arrays List<Double> xValuesAL = new ArrayList<Double>(); // The X values of the data set points 'datetime List<Double> yValuesAL = new ArrayList<Double>(); // The Y values of the data set points 'value'; // GET DATA // prepare cnx vars in data object dataObject.prepareCNXVariables(startDate, endDate, sensorID); // build query based on interpolation dataObject.updateQuery(rows, startDate, endDate, sensorID, queryTime); // get data from map ResultSet data = dataObject.getData(); // check tuples to make sure there is tuple before and after querytime checkTuples(data); // ITERATE OVER RESULT SET AND ADD TO ARRAY LIST dates and VALUES // Loop through RS and fetch the tuple values before and after querytime Integer rowCount = getRowCount(data); if (data.first()) { // make sure there is 1 tuple for either: before and on/after OR after and on/before if ((preTup == 1 && (postTup == 1 || sameTup == 1)) || (postTup == 1 && (preTup == 1 || sameTup == 1))) { for (int i = 0; i < rowCount; i++) { dateObjectString = data.getString("datetime"); String valueString = data.getString("value"); Double valueDouble = Double.parseDouble(valueString); if (dateObjectString.endsWith(".0")) { dateObjectString = dateObjectString.substring(0, dateObjectString.length() - 2); } dateObject = format.parseDateTime(dateObjectString); double dateMS = dateObject.getMillis(); tupDateMS = dateMS; tupValue = valueDouble; // Add before and after values to ArrayList xValuesAL.add(tupDateMS); yValuesAL.add(tupValue); data.next(); } } else { System.out.println("\nAdjust queryTime to be within temporal field window"); } } // Converts ArrayList into actual Array to be used by calculation. // This will be useful if I restructure so window can be number of rows. xValues = new Double[xValuesAL.size()]; for (int i = 0; i < xValuesAL.size(); i++) xValues[i] = xValuesAL.get(i); yValues = new Double[yValuesAL.size()]; for (int i = 0; i < yValuesAL.size(); i++) yValues[i] = yValuesAL.get(i); }
/** * Parses arbitrarily formatted Strings representing dates or dates and times to a {@link * org.joda.time.DateTime} objects. It first attempts parse with international standards, assuming * the dates are either dd MM yyyy or yyyy MM dd. If that fails it will try American formats where * the month precedes the days of the month. * * @param dateString abitrarily formatted date or date and time string * @return {@link org.joda.time.DateTime} representation of the dateString */ public static DateTime parseToUTC(String dateString) { if (MILLIS.matcher(dateString).find()) { return new DateTime(Long.parseLong(dateString)); } try { return DEFAULT_FORMATTER.parseDateTime(dateString); } catch (Exception e) { return ALT_FORMATTER.parseDateTime(dateString); } }
private ArrayList<AbstractFacet> extractStepFacets(final ApiData apiData) { ArrayList<AbstractFacet> facets = new ArrayList<AbstractFacet>(); /* burnJson is a JSONArray that contains a seperate JSONArray and calorie counts for each day */ JSONObject bodymediaResponse = JSONObject.fromObject(apiData.json); JSONArray daysArray = bodymediaResponse.getJSONArray("days"); if (bodymediaResponse.has("lastSync")) { DateTime d = form.parseDateTime(bodymediaResponse.getJSONObject("lastSync").getString("dateTime")); // Get timezone map from UpdateInfo context TimezoneMap tzMap = (TimezoneMap) updateInfo.getContext("tzMap"); // Insert lastSync into the updateInfo context so it's accessible to the updater updateInfo.setContext("lastSync", d); for (Object o : daysArray) { if (o instanceof JSONObject) { JSONObject day = (JSONObject) o; BodymediaStepsFacet steps = new BodymediaStepsFacet(apiData.updateInfo.apiKey.getId()); super.extractCommonFacetData(steps, apiData); steps.totalSteps = day.getInt("totalSteps"); steps.date = day.getString("date"); steps.json = day.getString("hours"); steps.lastSync = d.getMillis(); DateTime date = formatter.parseDateTime(day.getString("date")); steps.date = dateFormatter.print(date.getMillis()); if (tzMap != null) { // Create a LocalDate object which just captures the date without any // timezone assumptions LocalDate ld = new LocalDate(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth()); // Use tzMap to convert date into a datetime with timezone information DateTime realDateStart = tzMap.getStartOfDate(ld); // Set the start and end times for the facet. The start time is the leading midnight // of date according to BodyMedia's idea of what timezone you were in then. // Need to figure out what end should be... steps.start = realDateStart.getMillis(); int minutesLength = 1440; steps.end = steps.start + DateTimeConstants.MILLIS_PER_MINUTE * minutesLength; } else { TimeZone timeZone = metadataService.getTimeZone(apiData.updateInfo.getGuestId(), date.getMillis()); long fromMidnight = TimeUtils.fromMidnight(date.getMillis(), timeZone); long toMidnight = TimeUtils.toMidnight(date.getMillis(), timeZone); steps.start = fromMidnight; steps.end = toMidnight; } facets.add(steps); } else throw new JSONException("Days array is not a proper JSONObject"); } } return facets; }
public static int getDaysBetween(final String date1, final String date2, String format) { try { final DateTimeFormatter fmt = DateTimeFormat.forPattern(format) .withChronology(LenientChronology.getInstance(GregorianChronology.getInstance())); return Days.daysBetween(fmt.parseDateTime(date1), fmt.parseDateTime(date2)).getDays(); } catch (Exception ex) { ex.printStackTrace(); return 0; } }
public static DateTime parseDateTime(String dateTimeString) throws ParseException { DateTime parsedDateTime = null; try { parsedDateTime = ISO_DATE_TIME.parseDateTime(dateTimeString); } catch (Exception e) {; } if (parsedDateTime == null) { try { parsedDateTime = YEAR_MONTH_DAY_TIME.parseDateTime(dateTimeString); } catch (Exception e) {; } } return parsedDateTime; }
@RequestMapping(value = "/add", method = RequestMethod.POST) public String addPatchFile( @RequestParam("source") String source, @RequestParam("createDate") String createDate, @ModelAttribute("patchFile") PatchFile patchFile, BindingResult result) { DateTimeFormatter fmt = DateTimeFormat.forStyle("SS"); fmt.parseDateTime(createDate); patchFile.setCreationDate(fmt.parseDateTime(createDate).toDate()); patchFile.setFileList(patchFile.getFilesAsString()); patchFileService.addPatchFile( patchFile, securityContextHolderStrategy.getContext().getAuthentication().getName()); return "redirect:/index"; }
@SuppressWarnings("unchecked") @RequestMapping("/importar/web") public ModelAndView importarWeb(String pedidoJson, String dataEnvio) throws JsonParseException, JsonMappingException, IOException, GeneralSecurityException, MessagingException { logger.info("===> importarWeb(" + dataEnvio + "): " + pedidoJson); ObjectMapper mapper = new ObjectMapper(); Map<String, String> map = mapper.readValue(pedidoJson, Map.class); Pedido pedido = new Pedido(); pedido.setNomeCliente(map.get("Nome completo")); pedido.setEmailMLFormulario(map.get("E-mail cadastrado no MercadoLivre")); pedido.setEmailAlternativo(map.get("E-mail alternativo")); pedido.setEndereco(map.get("Endereço")); pedido.setNumero(map.get("Número")); pedido.setComplemento(map.get("Complemento")); pedido.setBairro(map.get("Bairro")); pedido.setCidade(map.get("Cidade")); pedido.setUf(map.get("UF")); String cep = tratarCep(map.get("CEP")); pedido.setCep(cep); pedido.setFormaEnvio(FormaEnvio.getEnum(map.get("Forma de envio"))); pedido.setItens(map.get("Quais foram os itens e a quantidade adquiridos?")); pedido.setTema(map.get("Qual é o tema a ser desenvolvido na arte?")); pedido.setCorPredominante(map.get("Qual é a cor predominante da sua arte?")); pedido.setMensagem(map.get("Qual a mensagem ou nome a ser personalizado?")); pedido.setPossuiFoto("Sim".equalsIgnoreCase(map.get("Deseja colocar alguma fotografia?"))); pedido.setTelefone(map.get("Qual seu telefone fixo para contato?")); pedido.setDetalhes(map.get("Adicione mais detalhes de como você quer a sua personalização")); pedido.setUsuarioML(map.get("Usuário ML (não altere este campo)")); DateTimeFormatter formatDataEvento = DateTimeFormat.forPattern("YYYYY-MM-dd"); DateTime dataEvento = formatDataEvento.parseDateTime(map.get("Qual a data do evento?")); pedido.setDataEvento(dataEvento.toDate()); DateTimeFormatter formatDataEnvio = DateTimeFormat.forPattern("dd/MM/YYYY"); DateTime dataEnvioFormulario = formatDataEnvio.parseDateTime(dataEnvio); pedido.setDataEnvioFormulario(dataEnvioFormulario.toDate()); pedidoService.salvarFormulario(pedido); return new ModelAndView("redirect:/pedido/edit/" + pedido.getId()); }
public static String getWeekRange(String dateCode) { DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd"); DateTimeFormatter outformatter = DateTimeFormat.forPattern("dd.MM"); DateTime endWeek = formatter.parseDateTime(dateCode); DateTime startWeek = endWeek.minusDays(6); return outformatter.print(startWeek) + "-" + outformatter.print(endWeek); }
@Override public Object adapt(Object value, Map<String, Object> context) { if (value == null || !(value instanceof String)) { return value; } String format = this.get("format", DEFAULT_FORMAT); DateTimeFormatter fmt = DateTimeFormat.forPattern(format); DateTime dt; try { dt = fmt.parseDateTime((String) value); } catch (Exception e) { throw new IllegalArgumentException("Invalid value: " + value, e); } String type = this.get("type", null); if ("LocalDate".equals(type)) { return dt.toLocalDate(); } if ("LocalTime".equals(type)) { return dt.toLocalTime(); } if ("LocalDateTime".equals(type)) { return dt.toLocalDateTime(); } return dt; }
private Person ingestPerson(org.atlasapi.remotesite.pa.profiles.bindings.Person paPerson) { Person person = new Person(); person.setCanonicalUri(PERSON_URI_PREFIX + paPerson.getId()); Name name = paPerson.getName(); // First and Last name are optional in the dtd so check both are // non-null to avoid strange names. if (!Strings.isNullOrEmpty(name.getFirstname()) && !Strings.isNullOrEmpty(name.getLastname())) { person.withName(name.getFirstname() + " " + name.getLastname()); } person.setGivenName(name.getFirstname()); person.setFamilyName(name.getLastname()); person.setGender(paPerson.getGender()); if (paPerson.getBorn() != null) { person.setBirthDate(dateTimeFormatter.parseDateTime(paPerson.getBorn())); } person.setBirthPlace(paPerson.getBornIn()); person.setDescription(paPerson.getEarlyLife() + "\n\n" + paPerson.getCareer()); person.addQuote(paPerson.getQuote()); person.setPublisher(Publisher.PA_PEOPLE); person.setImages(extractImages(paPerson.getPictures())); person.setImage(getPrimary(person.getImages())); setDirectEquivalentToPAPerson(person, paPerson.getId()); return person; }
public static String formatUTCToLocal(String datetime) { String returnTimeDate = ""; DateTime dtUTC = null; DateTimeZone timezone = DateTimeZone.getDefault(); DateTimeFormatter formatDT = DateTimeFormat.forPattern("MMM dd, yyyy hh:mma"); try { DateTime dateDateTime1 = formatDT.parseDateTime(datetime); DateTime now = new DateTime(); DateTime nowUTC = new LocalDateTime(now).toDateTime(DateTimeZone.UTC); long instant = now.getMillis(); long instantUTC = nowUTC.getMillis(); long offset = instantUTC - instant; // convert to local time dtUTC = dateDateTime1.withZoneRetainFields(DateTimeZone.UTC); // dtUTC = dateDateTime1.toDateTime(timezone); dtUTC = dtUTC.plusMillis((int) offset); returnTimeDate = dtUTC.toString(formatDT); } catch (Exception e) { returnTimeDate = "null"; e.printStackTrace(); } return returnTimeDate; }
public List<ExternalWorklog> parseWorklog() throws IOException { final CSVReader reader = new CSVReader(new StringReader(csv), ',', '"', "#", true, true, true, true, false); final String[] header = reader.getAllFieldsInLine(); verifyHeader(header); final DateTimeFormatter dateFormat = DateTimeFormat.forPattern("yyyy-MM-dd"); final List<ExternalWorklog> result = Lists.newArrayList(); for (; ; ) { final ExternalWorklog worklogItem = new ExternalWorklog(); final String[] line; try { line = reader.getAllFieldsInLine(); } catch (EOFException e) { break; } worklogItem.setStartDate(dateFormat.parseDateTime(line[0]).toDate()); worklogItem.setAuthor( userNameMapper.getUsernameForLoginName(StringUtils.strip(line[2] + " " + line[1]))); worklogItem.setTimeSpent((long) (UNITS_PER_HOUR * Double.parseDouble(line[5]))); worklogItem.setComment(line[6]); result.add(worklogItem); } return result; }
private Date getDate(DateTimeFormatter parser, String text) { try { return parser.parseDateTime(text).toDate(); } catch (Exception e) { return null; } }
public SUTime.Temporal apply(String text) { // TODO: TIMEZONE? DateTime dateTime = null; try { dateTime = formatter.parseDateTime(text); } catch (org.joda.time.IllegalFieldValueException e) { logger.warning( "WARNING: Invalid temporal \"" + text + "\" (" + e.getMessage() + "). Skipping and continuing..."); return null; } assert (dateTime != null); if (hasDate && hasTime) { return new SUTime.GroundedTime(dateTime); // return new SUTime.IsoDateTime( new SUTime.IsoTime(dateTime.getHourOfDay(), // dateTime.getMinuteOfHour(), dateTime.getSecondOfMinute()); // Date d = new SUTime.IsoDate(dateTime.getYear(), dateTime.getMonthOfYear(), // dateTime.getDayOfMonth()) ); } else if (hasTime) { // TODO: Millisecs? return new SUTime.IsoTime( dateTime.getHourOfDay(), dateTime.getMinuteOfHour(), dateTime.getSecondOfMinute()); } else if (hasDate) { return new SUTime.IsoDate( dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfMonth()); } else { return null; } }
private static DateTime parseDateTimeHelper(DateTimeFormatter formatter, String datetimeString) { try { return formatter.parseDateTime(datetimeString); } catch (IllegalArgumentException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT.toErrorCode(), e); } }
public DateTime getStartDate(UpdateInfo updateInfo, ObjectType ot) throws Exception { ApiKey apiKey = updateInfo.apiKey; // The updateStartDate for a given object type is stored in the apiKeyAttributes // as BodyMedia.<objectName>.updateStartDate. In the case of a failure the updater will store // the date // that failed and start there next time. In the case of a successfully completed update it // will store // the lastSync date returned from BodyMedia along with each API call. String updateKeyName = "BodyMedia." + ot.getName() + ".updateStartDate"; String updateStartDate = guestService.getApiKeyAttribute(apiKey, updateKeyName); // The first time we do this there won't be an apiKeyAttribute yet. In that case get the // registration date for the user and store that. if (updateStartDate == null) { OAuthConsumer consumer = setupConsumer(updateInfo.apiKey); String api_key = guestService.getApiKeyAttribute(updateInfo.apiKey, "bodymediaConsumerKey"); updateStartDate = getUserRegistrationDate(updateInfo, api_key, consumer); // Store in the apiKeyAttribute for next time guestService.setApiKeyAttribute(updateInfo.apiKey, updateKeyName, updateStartDate); } try { return formatter.parseDateTime(updateStartDate); } catch (IllegalArgumentException e) { return TimeUtils.dateFormatter.parseDateTime(updateStartDate); } }
protected DateTime parseLocal(JsonParser jp) throws IOException, JsonProcessingException { String str = jp.getText().trim(); if (str.length() == 0) { // [JACKSON-360] return null; } return _localDateTimeFormat.parseDateTime(str); }
public void setMetaData(SectionDataIfc section) { if (section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE) != null) { Integer authortype = new Integer(section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE)); setSectionAuthorType(authortype); if (section .getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE) .equals(SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.toString())) { if (section.getSectionMetaDataByLabel(SectionDataIfc.NUM_QUESTIONS_DRAWN) != null) { Integer numberdrawn = new Integer(section.getSectionMetaDataByLabel(SectionDataIfc.NUM_QUESTIONS_DRAWN)); setNumberToBeDrawn(numberdrawn); } if (section.getSectionMetaDataByLabel(SectionDataIfc.POOLID_FOR_RANDOM_DRAW) != null) { Long poolid = new Long(section.getSectionMetaDataByLabel(SectionDataIfc.POOLID_FOR_RANDOM_DRAW)); setPoolIdToBeDrawn(poolid); } if (section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW) != null) { String poolname = section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW); setPoolNameToBeDrawn(poolname); String randomDrawDate = section.getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_RANDOM_DRAW_DATE); if (randomDrawDate != null && !"".equals(randomDrawDate)) { try { // The Date Time is in ISO format DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); DateTime drawDate = fmt.parseDateTime(randomDrawDate); // We need the locale to localize the output string Locale loc = new ResourceLoader().getLocale(); String drawDateString = DateTimeFormat.fullDate().withLocale(loc).print(drawDate); String drawTimeString = DateTimeFormat.fullTime().withLocale(loc).print(drawDate); setRandomQuestionsDrawDate(drawDateString); setRandomQuestionsDrawTime(drawTimeString); } catch (Exception e) { log.error("Unable to parse date text: " + randomDrawDate, e); } } } } } else { setSectionAuthorType(SectionDataIfc.QUESTIONS_AUTHORED_ONE_BY_ONE); } if (section.getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_ORDERING) != null) { Integer questionorder = new Integer(section.getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_ORDERING)); setQuestionOrdering(questionorder); } else { setQuestionOrdering(SectionDataIfc.AS_LISTED_ON_ASSESSMENT_PAGE); } }
@Test public void testMapToPersonList() { Person a = new Person("A", Gender.FEMALE, formatter.parseDateTime("01/01/80")); Person b = new Person("B", Gender.MALE, formatter.parseDateTime("01/03/30")); List<String> data = new ArrayList<>(); data.add(" A , Female , 01/01/80"); data.add(" B , Male, 01/03/30"); List<Person> result = AddressBookFactory.mapToPersonList(data); assertEquals("We expect 2 persons in list", 2, result.size()); assertEquals("We expect first person to be A", a, result.get(0)); assertEquals("We expect second person to be B", b, result.get(1)); }
/** * Parse the value from the given text, using the specified format. * * @param text the text to format * @throws IllegalArgumentException */ public void setAsText(String text) throws IllegalArgumentException { if (allowEmpty && !StringUtils.hasText(text)) { // Treat empty String as null value. setValue(null); } else { setValue(new LocalDateTime(formatter.parseDateTime(text))); } }
@Test @UseWithField(field = "boundaryDatesMode", valuesFrom = FROM_ENUM, value = "") @Templates("plain") public void testBoundaryDatesMode() { calendarAttributes.set(CalendarAttributes.boundaryDatesMode, boundaryDatesMode.value); DayPicker dayPicker = popupCalendar.openPopup().getDayPicker(); MetamerPage.waitRequest(popupCalendar, WaitRequestType.XHR).setDateTime(firstOfNovember2012); PopupFooterControls footerControls = popupCalendar.openPopup().getFooterControls(); HeaderControls headerControls = popupCalendar.openPopup().getHeaderControls(); DateTime yearAndMonth; String firstOfNovember2012String = firstOfNovember2012.toString(dateTimeFormatter); switch (boundaryDatesMode) { case INACTIVE: case NULL: try { MetamerPage.waitRequest(dayPicker.getBoundaryDays().get(0), WaitRequestType.NONE) .select(); fail("Item should not be selected."); } catch (TimeoutException ex) { // ok } // apply and check, that the date has not changed footerControls = popupCalendar.openPopup().getFooterControls(); MetamerPage.waitRequest(footerControls, WaitRequestType.NONE).applyDate(); assertEquals(popupCalendar.getInput().getStringValue(), firstOfNovember2012String); break; case SCROLL: // scroll to 28th of October 2012 try { MetamerPage.waitRequest(dayPicker.getBoundaryDays().get(0), WaitRequestType.NONE) .select(); fail("Item should not be selected."); } catch (TimeoutException ex) { // ok } yearAndMonth = headerControls.getYearAndMonth(); assertEquals(yearAndMonth.getYear(), 2012); assertEquals(yearAndMonth.getMonthOfYear(), 10); // apply and check, that the date has not changed footerControls = popupCalendar.openPopup().getFooterControls(); MetamerPage.waitRequest(footerControls, WaitRequestType.NONE).applyDate(); assertEquals(popupCalendar.getInput().getStringValue(), firstOfNovember2012String); break; case SELECT: // select 28th of October 2012 CalendarDay day = dayPicker.getBoundaryDays().get(0); MetamerPage.waitRequest(day.getDayElement(), WaitRequestType.NONE).click(); yearAndMonth = headerControls.getYearAndMonth(); assertEquals(yearAndMonth.getYear(), 2012); assertEquals(yearAndMonth.getMonthOfYear(), 10); MetamerPage.waitRequest(footerControls, WaitRequestType.XHR).applyDate(); DateTime parsedDateTime = dateTimeFormatter.parseDateTime(popupCalendar.getInput().getStringValue()); assertEquals(parsedDateTime.getYear(), 2012); assertEquals(parsedDateTime.getMonthOfYear(), 10); assertEquals(parsedDateTime.getDayOfMonth(), 28); break; } }
/** Extract a date from the given string. Assertion fails when invalid date has been provided. */ protected Date getDateFromISOString(String isoString) { DateTimeFormatter dateFormat = ISODateTimeFormat.dateTime(); try { return dateFormat.parseDateTime(isoString).toDate(); } catch (IllegalArgumentException iae) { fail("Illegal date provided: " + isoString); return null; } }
@Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String jsonString = json.getAsJsonPrimitive().getAsString(); if (Strings.isNullOrEmpty(jsonString)) { return null; } return fmt.parseDateTime(jsonString).toDate(); }
@Override public DateTime deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException { DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); String date = jsonparser.getText(); return format.parseDateTime(date); }
/** * Do get. * * @param request the request * @param response the response * @throws ServletException the servlet exception * @throws IOException Signals that an I/O exception has occurred. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // maak een lijst van dagen: dayofweek, date, hoogste laagste, open, slot, vorige slot // deze waarden halen we uit een properties file // sorted on date // we gaan max 3 weken terug // 1 = maandag, 5 = vrijdag // Set the attribute and Forward to hello.jsp List<String> files = FileUtils.getFiles(Constants.INTRADAY_KOERSENDIR, "csv", false); DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd"); int days = files.size(); Map<Integer, Map<Integer, String>> matrix = new HashMap<Integer, Map<Integer, String>>(); int weekNumberOld = 0; Map<Integer, String> week = null; int weekNumber = 0; if (days < numberOfDays) { numberOfDays = days; } for (int i = days - numberOfDays; i < days; i++) { String file = files.get(i); DateTime dt = formatter.parseDateTime(file); weekNumber = dt.getWeekOfWeekyear(); if (weekNumber != weekNumberOld) { if (week != null) { matrix.put(-weekNumberOld, week); } weekNumberOld = weekNumber; week = new HashMap<Integer, String>(); week.put(1, ""); week.put(2, ""); week.put(3, ""); week.put(4, ""); week.put(5, ""); } week.put(dt.getDayOfWeek(), file); System.out.println( "file: " + file + " dayofweek: " + dt.getDayOfWeek() + dt.getWeekOfWeekyear()); } if (!matrix.containsKey(weekNumber)) { matrix.put(-weekNumber, week); } request.setAttribute("matrix", matrix); request.setAttribute("dir", "intraday"); getServletConfig() .getServletContext() .getRequestDispatcher("/intradayoverview.jsp") .forward(request, response); } catch (Exception ex) { ex.printStackTrace(); } }