List of usage examples for org.joda.time LocalDate toString
@ToString
public String toString()
From source file:com.roflcode.fitnessChallenge.FetchFitbitActivities.java
License:Apache License
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { logger = serviceProvider.getLoggerService(FetchFitbitActivities.class); logger.debug("get fitbit activities ------------------------------"); String stackmobUserID = request.getParams().get("stackmob_user_id"); String startDateStr = request.getParams().get("start_date"); String endDateStr = request.getParams().get("end_date"); if (endDateStr == "") { endDateStr = startDateStr;/*w ww . ja v a 2 s . c o m*/ } if (stackmobUserID == null || stackmobUserID.isEmpty()) { HashMap<String, String> errParams = new HashMap<String, String>(); errParams.put("error", "stackmobUserID was empty or null"); return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request } FitbitApiClientAgent agent = AgentInitializer.GetInitializedAgent(serviceProvider, stackmobUserID); if (agent == null) { HashMap<String, String> errParams = new HashMap<String, String>(); errParams.put("error", "could not initialize fitbit client agent"); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errParams); // http 500 internal error } HashMap<String, String> credentials = AgentInitializer.GetStoredFitbitCredentials(serviceProvider, stackmobUserID); String fitbitUserID = credentials.get("fitbituserid"); LocalUserDetail user = new LocalUserDetail(stackmobUserID); FitbitUser fitbitUser = new FitbitUser(fitbitUserID); //LocalDate today = new LocalDate(DateTimeZone.UTC); DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy"); DateTime dt = formatter.parseDateTime(startDateStr); LocalDate startDate = new LocalDate(dt); dt = formatter.parseDateTime(endDateStr); LocalDate endDate = new LocalDate(dt); //TimeZone tz = TimeZone.getTimeZone("GMT-8:00"); //LocalDate today = new LocalDate(DateTimeZone.forTimeZone(tz)); //LocalDate today = new LocalDate(DateTimeZone.forTimeZone(tz)); //LocalDate yesterday = today.minusDays(1); logger.debug("entering date loop " + startDate.toString() + " end: " + endDate.toString()); for (LocalDate date = startDate; date.isBefore(endDate) || date.isEqual(endDate); date = date.plusDays(1)) { logger.debug("date: " + date.toString()); Activities activities; try { activities = agent.getActivities(user, fitbitUser, date); } catch (FitbitAPIException ex) { logger.error("failed to get activities", ex); HashMap<String, String> errParams = new HashMap<String, String>(); errParams.put("error", "could not get activities"); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errParams); // http 500 internal error } ActivitiesSummary summary = activities.getSummary(); // private Integer floors = null; // private Double elevation = null; // private List<ActivityDistance> distances; DataService dataService = serviceProvider.getDataService(); DateMidnight dateMidnight = date.toDateMidnight(); long millis = dateMidnight.getMillis(); List<SMCondition> query; List<SMObject> result; // build a query query = new ArrayList<SMCondition>(); query.add(new SMEquals("theusername", new SMString(stackmobUserID))); query.add(new SMEquals("activity_date", new SMInt(millis))); // execute the query try { boolean newActivity = false; SMValue activityId; result = dataService.readObjects("activity", query); SMObject activityObject; //activity was in the datastore, so update if (result != null && result.size() == 1) { activityObject = result.get(0); List<SMUpdate> update = new ArrayList<SMUpdate>(); update.add(new SMSet("active_score", new SMInt((long) summary.getActiveScore()))); update.add(new SMSet("steps", new SMInt((long) summary.getSteps()))); update.add(new SMSet("floors", new SMInt((long) summary.getFloors()))); update.add(new SMSet("sedentary_minutes", new SMInt((long) summary.getSedentaryMinutes()))); update.add(new SMSet("lightly_active_minutes", new SMInt((long) summary.getLightlyActiveMinutes()))); update.add( new SMSet("fairly_active_minutes", new SMInt((long) summary.getFairlyActiveMinutes()))); update.add(new SMSet("very_active_minutes", new SMInt((long) summary.getVeryActiveMinutes()))); activityId = activityObject.getValue().get("activity_id"); logger.debug("update object"); dataService.updateObject("activity", activityId, update); logger.debug("updated object"); } else { Map<String, SMValue> activityMap = new HashMap<String, SMValue>(); activityMap.put("theusername", new SMString(stackmobUserID)); activityMap.put("activity_date", new SMInt(millis)); activityMap.put("activity_date_str", new SMString(date.toString())); activityMap.put("active_score", new SMInt((long) summary.getActiveScore())); activityMap.put("steps", new SMInt((long) summary.getSteps())); activityMap.put("floors", new SMInt((long) summary.getFloors())); activityMap.put("sedentary_minutes", new SMInt((long) summary.getSedentaryMinutes())); activityMap.put("lightly_active_minutes", new SMInt((long) summary.getLightlyActiveMinutes())); activityMap.put("fairly_active_minutes", new SMInt((long) summary.getFairlyActiveMinutes())); activityMap.put("very_active_minutes", new SMInt((long) summary.getVeryActiveMinutes())); activityObject = new SMObject(activityMap); logger.debug("create object"); activityObject = dataService.createObject("activity", activityObject); logger.debug("created object"); activityId = activityObject.getValue().get("activity_id"); newActivity = true; } } catch (InvalidSchemaException e) { HashMap<String, String> errMap = new HashMap<String, String>(); errMap.put("error", "invalid_schema"); errMap.put("detail", e.toString()); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error } catch (DatastoreException e) { HashMap<String, String> errMap = new HashMap<String, String>(); errMap.put("error", "datastore_exception"); errMap.put("detail", e.toString()); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error } catch (Exception e) { HashMap<String, String> errMap = new HashMap<String, String>(); errMap.put("error", "unknown"); errMap.put("detail", e.toString()); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error } } Map<String, Object> returnMap = new HashMap<String, Object>(); returnMap.put("success?", "think so"); // returnMap.put("activity_id", activityId); // returnMap.put("newActivity", newActivity); //returnMap.put("activitiesJson", activities); logger.debug("completed get activities"); return new ResponseToProcess(HttpURLConnection.HTTP_OK, returnMap); }
From source file:com.sandata.lab.common.utils.date.DateUtil.java
License:Open Source License
public static String convertJodaDateTimetoString(LocalDate localDate, LocalTime localTime, String dateFormat) { LocalDateTime localDateTime = new LocalDateTime(localDate.toString() + "T" + localTime.toString()); DateTimeFormatter fmt = DateTimeFormat.forPattern(dateFormat); return localDateTime.toString(fmt); }
From source file:com.sonicle.webtop.calendar.CalendarManager.java
License:Open Source License
private <T> List<T> calculateRecurringInstances_OLD(Connection con, RecurringInstanceMapper<T> instanceMapper, DateTime fromDate, DateTime toDate, DateTimeZone userTimezone, int limit) throws WTException { RecurrenceDAO recDao = RecurrenceDAO.getInstance(); RecurrenceBrokenDAO recbDao = RecurrenceBrokenDAO.getInstance(); ArrayList<T> instances = new ArrayList<>(); int eventId = instanceMapper.getEventId(); DateTime eventStartDate = instanceMapper.getEventStartDate(); DateTime eventEndDate = instanceMapper.getEventEndDate(); // Retrieves reccurence and broken dates (if any) ORecurrence orec = recDao.selectByEvent(con, eventId); if (orec == null) { logger.warn("Unable to retrieve recurrence for event [{}]", eventId); } else {/*from www . ja v a 2 s .c om*/ if (fromDate == null) fromDate = orec.getStartDate(); if (toDate == null) toDate = orec.getStartDate().plusYears(1); /* List<ORecurrenceBroken> obrecs = recbDao.selectByEventRecurrence(con, eventId, orec.getRecurrenceId()); //TODO: ritornare direttamente l'hashmap da jooq // Builds a hashset of broken dates for increasing performances HashMap<String, ORecurrenceBroken> brokenDates = new HashMap<>(); for (ORecurrenceBroken obrec : obrecs) { brokenDates.put(obrec.getEventDate().toString(), obrec); } */ Map<LocalDate, ORecurrenceBroken> obrecs = recbDao.selectByEventRecurrence(con, eventId, orec.getRecurrenceId()); HashSet<String> brokenDates = new HashSet<>(); for (LocalDate ld : obrecs.keySet()) { brokenDates.add(ld.toString()); } try { // Calculate event length in order to generate events like original one int eventDays = CalendarUtils.calculateLengthInDays(eventStartDate, eventEndDate); RRule rr = new RRule(orec.getRule()); // Calcutate recurrence set for required dates range PeriodList periods = ICal4jUtils.calculateRecurrenceSet(eventStartDate, eventEndDate, orec.getStartDate(), rr, fromDate, toDate, userTimezone); // Recurrence start is useful to skip undesired dates at beginning. // If event does not starts at recurrence real beginning (eg. event // start on MO but first recurrence begin on WE), ical4j lib includes // those dates in calculated recurrence set, as stated in RFC // (http://tools.ietf.org/search/rfc5545#section-3.8.5.3). LocalDate rrStart = ICal4jUtils .calculateRecurrenceStart(orec.getStartDate(), rr.getRecur(), userTimezone).toLocalDate(); //LocalDate rrStart = ICal4jUtils.calculateRecurrenceStart(eventStartDate, rr.getRecur(), userTimezone).toLocalDate(); //TODO: valutare se salvare la data gi aggiornata LocalDate rrEnd = orec.getUntilDate().toLocalDate(); // Iterates returned recurring periods and builds cloned events... int count = -1; for (net.fortuna.ical4j.model.Period per : (Iterable<net.fortuna.ical4j.model.Period>) periods) { count++; if ((limit != -1) && (count > limit)) break; final LocalDate perStart = ICal4jUtils.toJodaDateTime(per.getStart()).toLocalDate(); final LocalDate perEnd = ICal4jUtils.toJodaDateTime(per.getEnd()).toLocalDate(); if (brokenDates.contains(perStart.toString())) continue; // Skip broken dates... if ((perStart.compareTo(rrStart) >= 0) && (perEnd.compareTo(rrEnd) <= 0)) { // Skip unwanted dates at beginning final DateTime newStart = eventStartDate.withDate(perStart); final DateTime newEnd = eventEndDate.withDate(newStart.plusDays(eventDays).toLocalDate()); final String key = EventKey.buildKey(eventId, eventId, perStart); instances.add(instanceMapper.createInstance(key, newStart, newEnd)); } } } catch (DAOException ex) { throw wrapException(ex); } catch (ParseException ex) { throw new WTException(ex, "Unable to parse rrule"); } } return instances; }
From source file:com.sonicle.webtop.core.Service.java
License:Open Source License
public void processManageIMChat(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { UserProfile up = getEnv().getProfile(); DateTimeZone utz = up.getTimeZone(); try {/*from w ww . j a va 2s. c o m*/ String crud = ServletUtils.getStringParameter(request, "crud", true); if (crud.equals("presence")) { String chatId = ServletUtils.getStringParameter(request, "chatId", true); if (xmppCli != null) { if (!XMPPClient.isInstantChat(chatId)) throw new WTException("Presence feature non available for a grupchat"); String friendFullId = null; String presenceStatus = null; FriendPresence presence = xmppCli.getChatPresence(chatId); if (presence == null) { presenceStatus = EnumUtils.toSerializedName(PresenceStatus.OFFLINE); } else { friendFullId = presence.getFriendFullJid(); presenceStatus = EnumUtils.toSerializedName(presence.getPresenceStatus()); } new JsonResult(new JsIMPresenceStatus(friendFullId, presenceStatus)).printTo(out); } else { throw new WTException("XMPPClient not available"); } } else if (crud.equals("dates")) { String chatId = ServletUtils.getStringParameter(request, "chatId", true); int year = ServletUtils.getIntParameter(request, "year", true); List<String> items = new ArrayList<>(); List<LocalDate> dates = coreMgr.listIMMessageDates(chatId, year, utz); for (LocalDate date : dates) { items.add(date.toString()); } new JsonResult(items).printTo(out); } else if (crud.equals("send")) { String chatId = ServletUtils.getStringParameter(request, "chatId", true); String text = ServletUtils.getStringParameter(request, "text", true); String lastSeenDate = ServletUtils.getStringParameter(request, "lastSeenDate", null); LocalDate lastSeen = (lastSeenDate == null) ? null : DateTimeUtils.parseYmdHmsWithZone(lastSeenDate, "00:00:00", utz).toLocalDate(); if (xmppCli != null) { EntityBareJid chatJid = XMPPHelper.asEntityBareJid(chatId); List<JsGridIMMessage> items = new ArrayList<>(); ChatMessage message = xmppCli.sendTextMessage(chatJid, text); if (message == null) throw new Exception("Message is null"); if (lastSeen != null) { final LocalDate mesDate = message.getTimestampDate(utz); if (!mesDate.equals(lastSeen)) { final String msgId = ChatMessage.buildUniqueId(chatJid, "dummy-date", message.getTimestamp()); items.add(JsGridIMMessage.asDateAction(msgId, mesDate)); } } items.add(new JsGridIMMessage(true, message, getEnv().getProfile().getTimeZone())); new JsonResult(items, items.size()).printTo(out); } else { throw new WTException("XMPPClient not available"); } } } catch (Exception ex) { logger.error("Error in ManageIMChat", ex); new JsonResult(ex).printTo(out); } }
From source file:com.welflex.model.hibernate.LocalDateUserType.java
License:Apache License
public String objectToSQLString(Object value, Dialect dialect) throws Exception { LocalDate localDate = (LocalDate) value; return localDate.toString(); }
From source file:courtscheduler.persistence.CourtScheduleInfo.java
License:Apache License
/** * toString method which outputs the values stored in the same format in which it was read in. * This is to say that the output could also be used as the input. * * @return/*from w ww.j a va 2 s . c o m*/ */ public String toString() { StringBuilder result = new StringBuilder(); result.append("; " + FileSystems.getDefault().getPath(filepath).toAbsolutePath() + EOL); if (conferenceStartDate != null) result.append("conference_start=" + conferenceStartDate.toString() + EOL); if (conferenceEndDate != null) result.append("conference_end=" + conferenceEndDate.toString() + EOL); result.append("court_count=" + numberOfCourts + EOL); result.append("timeslots_start=" + timeslotMidnightOffsetInMinutes + EOL); result.append("timeslots_count=" + numberOfTimeSlotsPerDay + EOL); result.append("timeslot_duration_minutes=" + timeslotDurationInMinutes + EOL); for (LocalDate holiday : holidays) { result.append("holiday = " + holiday.toString() + EOL); } return result.toString(); }
From source file:courtscheduler.persistence.CourtScheduleIO.java
License:Apache License
private void printMatch(XSSFRow dataRow, Match match, CourtScheduleInfo info) { int cellNumber = 0; // TEAM/*from w ww .j a v a 2s. c o m*/ String teamName1 = match.getTeam1().getTeamName(); dataRow.createCell(cellNumber++).setCellValue(teamName1); // VS String vs = "vs."; dataRow.createCell(cellNumber++).setCellValue(vs); // OPPONENT String teamName2 = match.getTeam2().getTeamName(); dataRow.createCell(cellNumber++).setCellValue(teamName2); // CONFERENCE String conference = match.getConference(); dataRow.createCell(cellNumber++).setCellValue(conference); // DAY Integer matchDateIndex = match.getMatchSlot().getDay(); LocalDate matchDate = info.getConferenceStartDate().plusDays(matchDateIndex); String day = matchDate.dayOfWeek().getAsText(); dataRow.createCell(cellNumber++).setCellValue(day); // DATE String date = matchDate.toString(); if (Main.LOG_LEVEL > 1) { date = date + " [" + matchDateIndex + "]"; } dataRow.createCell(cellNumber++).setCellValue(date); // TIME Integer matchTime = match.getMatchSlot().getTime(); String time = info.getHumanReadableTime(matchTime); if (Main.LOG_LEVEL > 1) { time = time + " [" + matchTime + "]"; } dataRow.createCell(cellNumber++).setCellValue(time); // COURT Integer courtId = match.getMatchSlot().getCourt(); // normal people like their courts indexed from one, not zero, // so add one if we're printing for the client dataRow.createCell(cellNumber++).setCellValue(courtId + (Main.LOG_LEVEL > 1 ? 0 : 1)); if (!match.getCanPlayInCurrentSlot()) { dataRow.createCell(cellNumber).setCellValue("WARNING: Team is scheduled when they cannot play"); } else if (match.wasPostProcessed()) { dataRow.createCell(cellNumber) .setCellValue("VERIFY: Check that this match meets DH/B2B/NST constraints"); } }
From source file:de.appsolve.padelcampus.utils.BookingUtil.java
public void addWeekView(HttpServletRequest request, LocalDate selectedDate, List<Facility> selectedFacilities, ModelAndView mav, Boolean onlyFutureTimeSlots, Boolean preventOverlapping) throws JsonProcessingException { //calculate date configuration for datepicker LocalDate today = new LocalDate(DEFAULT_TIMEZONE); LocalDate firstDay = today.dayOfMonth().withMinimumValue(); LocalDate lastDay = getLastBookableDay(request).plusDays(1); List<CalendarConfig> calendarConfigs = calendarConfigDAO.findBetween(firstDay, lastDay); Collections.sort(calendarConfigs); Map<String, DatePickerDayConfig> dayConfigs = getDayConfigMap(firstDay, lastDay, calendarConfigs); List<Booking> confirmedBookings = bookingDAO.findBlockedBookingsBetween(firstDay, lastDay); //calculate available time slots List<TimeSlot> timeSlots = new ArrayList<>(); List<LocalDate> weekDays = new ArrayList<>(); for (int i = 1; i <= CalendarWeekDay.values().length; i++) { LocalDate date = selectedDate.withDayOfWeek(i); weekDays.add(date);/*from ww w . jav a 2 s. c o m*/ if ((!onlyFutureTimeSlots || !date.isBefore(today)) && lastDay.isAfter(date)) { try { //generate list of bookable time slots timeSlots.addAll(getTimeSlotsForDate(date, calendarConfigs, confirmedBookings, onlyFutureTimeSlots, preventOverlapping)); } catch (CalendarConfigException e) { //safe to ignore } } } SortedSet<Offer> offers = new TreeSet<>(); List<TimeRange> rangeList = new ArrayList<>(); //Map<TimeRange, List<TimeSlot>> rangeList = new TreeMap<>(); for (TimeSlot slot : timeSlots) { Set<Offer> slotOffers = slot.getConfig().getOffers(); offers.addAll(slotOffers); TimeRange range = new TimeRange(); range.setStartTime(slot.getStartTime()); range.setEndTime(slot.getEndTime()); if (rangeList.contains(range)) { range = rangeList.get(rangeList.indexOf(range)); } else { rangeList.add(range); } List<TimeSlot> slotis = range.getTimeSlots(); slotis.add(slot); range.setTimeSlots(slotis); } Collections.sort(rangeList); List<Offer> selectedOffers = new ArrayList<>(); if (selectedFacilities.isEmpty()) { selectedOffers = offerDAO.findAll(); } else { for (Facility facility : selectedFacilities) { selectedOffers.addAll(facility.getOffers()); } } Collections.sort(selectedOffers); mav.addObject("dayConfigs", objectMapper.writeValueAsString(dayConfigs)); mav.addObject("maxDate", lastDay.toString()); mav.addObject("Day", selectedDate); mav.addObject("NextMonday", selectedDate.plusDays(8 - selectedDate.getDayOfWeek())); mav.addObject("PrevSunday", selectedDate.minusDays(selectedDate.getDayOfWeek())); mav.addObject("WeekDays", weekDays); mav.addObject("RangeMap", rangeList); mav.addObject("Offers", offers); mav.addObject("SelectedOffers", selectedOffers); mav.addObject("SelectedFacilities", selectedFacilities); mav.addObject("Facilities", facilityDAO.findAll()); }
From source file:de.appsolve.padelcampus.utils.RankingUtil.java
public void updateRanking() { for (Customer customer : customerDAO.findAll()) { LocalDate date = LocalDate.now(); for (Gender gender : Gender.values()) { try { List<Ranking> existingRankings = rankingBaseDAO.findByGenderAndDate(gender, date, customer); LOG.info(String.format( "updating ranking for [customer: %s, gender: %s, date: %s, ranking count: %s] - start", customer, gender, date.toString(), existingRankings.size())); List<Game> games = getGamesInLastYearSince(gender, date, customer); List<Ranking> rankings = getRanking(games, gender, date); rankings.forEach(r -> r.setCustomer(customer)); rankingBaseDAO.delete(existingRankings); rankingBaseDAO.saveOrUpdate(rankings); LOG.info(String.format( "updating ranking for [customer: %s, gender: %s, date: %s, ranking count: %s] - end", customer, gender, date.toString(), rankings.size())); } catch (Exception e) { LOG.error(e, e);//from w ww . j a va 2 s. c om } System.gc(); } System.gc(); } }
From source file:de.appsolve.padelcampus.utils.RankingUtil.java
private List<Ranking> updateRanking(Gender gender, LocalDate date) { try {/* w w w.ja v a 2s . c o m*/ LOG.info(String.format("updating ranking for [gender: %s, date: %s] - start", gender, date.toString())); List<Game> games = getGamesInLastYearSince(gender, date); List<Ranking> rankings = getRanking(games, gender, date); List<Ranking> existingRankings = rankingDAO.findByGenderAndDate(gender, date); rankingDAO.delete(existingRankings); rankingDAO.saveOrUpdate(rankings); LOG.info(String.format("updating ranking for [gender: %s, date: %s] - end", gender, date.toString())); return rankings; } catch (Exception e) { LOG.error(e, e); return null; } }