List of usage examples for java.util Calendar HOUR
int HOUR
To view the source code for java.util Calendar HOUR.
Click Source Link
get
and set
indicating the hour of the morning or afternoon. From source file:ru.org.linux.tracker.TrackerController.java
@RequestMapping("/tracker") public ModelAndView tracker(@RequestParam(value = "filter", defaultValue = "all") String filterAction, @RequestParam(value = "offset", required = false) Integer offset, HttpServletRequest request) throws Exception { if (offset == null) { offset = 0;/* w w w . j av a2s . c o m*/ } else { if (offset < 0 || offset > 300) { throw new UserErrorException("? offset"); } } TrackerFilterEnum trackerFilter = getFilterValue(filterAction); Map<String, Object> params = new HashMap<>(); params.put("mine", trackerFilter == TrackerFilterEnum.MINE); params.put("offset", offset); params.put("filter", trackerFilter.getValue()); if (trackerFilter != TrackerFilterEnum.ALL) { params.put("addition_query", "&filter=" + trackerFilter.getValue()); } else { params.put("addition_query", ""); } Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); if (trackerFilter == TrackerFilterEnum.MINE) { calendar.add(Calendar.MONTH, -6); } else { calendar.add(Calendar.HOUR, -24); } Timestamp dateLimit = new Timestamp(calendar.getTimeInMillis()); Template tmpl = Template.getTemplate(request); int messages = tmpl.getProf().getMessages(); int topics = tmpl.getProf().getTopics(); params.put("topics", topics); User user = tmpl.getCurrentUser(); if (trackerFilter == TrackerFilterEnum.MINE) { if (!tmpl.isSessionAuthorized()) { throw new UserErrorException("Not authorized"); } params.put("title", "? ?? ( )"); } else { params.put("title", "? ??"); } params.put("msgs", trackerDao.getTrackAll(trackerFilter, user, dateLimit, topics, offset, messages)); if (tmpl.isModeratorSession() && trackerFilter != TrackerFilterEnum.MINE) { params.put("newUsers", userDao.getNewUsers()); params.put("deleteStats", deleteInfoDao.getRecentStats()); } return new ModelAndView("tracker", params); }
From source file:co.carlosandresjimenez.android.gotit.notification.AlarmReceiver.java
/** * Sets a repeating alarm that runs once a day at approximately 8:30 a.m. When the * alarm fires, the app broadcasts an Intent to this WakefulBroadcastReceiver. * * @param context/*from w ww .ja v a2s . c o m*/ */ public void setAlarm(Context context) { // If the alarm has been set, cancel it. if (alarmMgr != null) { alarmIntent.cancel(); alarmMgr.cancel(alarmIntent); } alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmReceiver.class); alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0); int userFrequencySetting = Utility.getNotificationFrequency(context); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.HOUR, userFrequencySetting); // Set the alarm to fire in X hours according to the device's // clock and user settings, and to repeat according to user settings alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), userFrequencySetting * ONE_HOUR_MILLISECONDS, alarmIntent); ComponentName receiver = new ComponentName(context, BootReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); }
From source file:cn.mljia.common.notify.utils.DateUtils.java
/** * ???//from ww w . ja v a2s . c o m * * @param date * 1 * @param otherDate * 2 * @param withUnit * ??Calendar field? * @return 0, 0 ??0 */ public static int compareDate(Date date, Date otherDate, int withUnit) { Calendar dateCal = Calendar.getInstance(); dateCal.setTime(date); Calendar otherDateCal = Calendar.getInstance(); otherDateCal.setTime(otherDate); switch (withUnit) { case Calendar.YEAR: dateCal.clear(Calendar.MONTH); otherDateCal.clear(Calendar.MONTH); case Calendar.MONTH: dateCal.set(Calendar.DATE, 1); otherDateCal.set(Calendar.DATE, 1); case Calendar.DATE: dateCal.set(Calendar.HOUR_OF_DAY, 0); otherDateCal.set(Calendar.HOUR_OF_DAY, 0); case Calendar.HOUR: dateCal.clear(Calendar.MINUTE); otherDateCal.clear(Calendar.MINUTE); case Calendar.MINUTE: dateCal.clear(Calendar.SECOND); otherDateCal.clear(Calendar.SECOND); case Calendar.SECOND: dateCal.clear(Calendar.MILLISECOND); otherDateCal.clear(Calendar.MILLISECOND); case Calendar.MILLISECOND: break; default: throw new IllegalArgumentException("withUnit ?? " + withUnit + " ????"); } return dateCal.compareTo(otherDateCal); }
From source file:com.ebay.oss.bark.service.DqScheduleServiceImpl.java
public void createJobToRunBySchedule() { for (DqSchedule schedule : scheduleRepo.getAll()) { long now = new Date().getTime(); long startTime = schedule.getStarttime(); if (now < startTime) { continue; }/* w w w . ja v a 2 s . co m*/ Calendar c = Calendar.getInstance(); Date date = new Date(startTime); c.setTime(date); int type = schedule.getScheduleType(); if (type == ScheduleType.DAILY) { c.add(Calendar.DATE, 1); } else if (type == ScheduleType.HOURLY) { c.add(Calendar.HOUR, 1); } else if (type == ScheduleType.WEEKLY) { c.add(Calendar.DATE, 7); } else if (type == ScheduleType.MONTHLY) { c.add(Calendar.MONTH, 1); } else { continue; } DqJob job = new DqJob(); job.setModelList(schedule.getModelList()); job.setStarttime(startTime); job.setStatus(0); job.setId(schedule.getModelList() + "_" + startTime); // this is the job.id generation logic job.setJobType(schedule.getJobType()); int result = jobRepo.newJob(job); if (result == 0) { logger.info("===================new model failure"); continue; } startTime = c.getTime().getTime(); schedule.setStarttime(startTime); scheduleRepo.save(schedule); } }
From source file:com.ebay.oss.griffin.service.DqScheduleServiceImpl.java
void createJobToRunBySchedule() { for (DqSchedule schedule : scheduleRepo.getAll()) { long now = new Date().getTime(); long startTime = schedule.getStarttime(); if (now < startTime) { continue; }//from w ww . java2s . com Calendar c = Calendar.getInstance(); Date date = new Date(startTime); c.setTime(date); int type = schedule.getScheduleType(); if (type == ScheduleType.DAILY) { c.add(Calendar.DATE, 1); } else if (type == ScheduleType.HOURLY) { c.add(Calendar.HOUR, 1); } else if (type == ScheduleType.WEEKLY) { c.add(Calendar.DATE, 7); } else if (type == ScheduleType.MONTHLY) { c.add(Calendar.MONTH, 1); } else { continue; } startTime = c.getTime().getTime(); schedule.setStarttime(startTime); DqJob job = new DqJob(); job.setModelList(schedule.getModelList()); job.setStarttime(startTime); job.setStatus(0); job.setId(schedule.getModelList() + "_" + startTime); // this is the job.id generation logic job.setJobType(schedule.getJobType()); int result = jobRepo.newJob(job); if (result == 0) { logger.info("===================new model failure"); continue; } scheduleRepo.save(schedule); } }
From source file:eu.smartfp7.foursquare.AttendanceCrawler.java
/** * We use the entire hour to do all the calls. This method calculates the * amount of time the program has to sleep in order to finish crawling * every venue before the end of the current hour. * It does not account for already crawled venues: sleep time decreases * as the hour progresses./*from ww w . j av a2 s. c om*/ * Crawling all venues takes thus approximately 40 minutes. * */ public static void intelligentWait(int total_venues, long current_time, long avg_time_spent_crawling) { try { double time = (DateUtils.truncate(new Date(current_time + 3600000), Calendar.HOUR).getTime() - current_time) / (double) total_venues; if (Math.round(time) < avg_time_spent_crawling) avg_time_spent_crawling = 0; Thread.sleep(Math.round(time) - avg_time_spent_crawling); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:net.solarnetwork.node.dao.jdbc.AbstractJdbcDatumDao.java
/** * Execute a SQL update to delete data that has already been "uploaded" and * is older than a specified number of hours. * //w w w . j a v a 2 s .com * <p> * This executes SQL from the {@code sqlDeleteOld} property, setting a * single timestamp parameter as the current time minus {@code hours} hours. * The general idea is for the SQL to join to some "upload" table to find * the rows in the "datum" table that have been uploaded and are older than * the specified number of hours. For example: * </p> * * <pre> * DELETE FROM solarnode.sn_some_datum p WHERE p.id IN * (SELECT pd.id FROM solarnode.sn_some_datum pd * INNER JOIN solarnode.sn_some_datum_upload u * ON u.power_datum_id = pd.id WHERE pd.created < ?) * </pre> * * @param hours * the number of hours hold to delete * @return the number of rows deleted */ protected int deleteUploadedDataOlderThanHours(final int hours) { return getJdbcTemplate().update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { String sql = getSqlResource(SQL_RESOURCE_DELETE_OLD); log.debug("Preparing SQL to delete old datum [{}] with hours [{}]", sql, hours); PreparedStatement ps = con.prepareStatement(sql); Calendar c = Calendar.getInstance(); c.add(Calendar.HOUR, -hours); ps.setTimestamp(1, new Timestamp(c.getTimeInMillis()), c); return ps; } }); }
From source file:com.frey.repo.DateUtil.java
/** * ??20090807/*from w w w .j ava2 s. c o m*/ */ public static String yesterdayDate() { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.DATE, cal.get(Calendar.DATE) - 1); return convertDate2String2(cal.getTime()); }
From source file:org.kuali.mobility.sakai.service.SakaiSiteServiceImpl.java
@SuppressWarnings("unchecked") public Home findSakaiHome(String user, String shortDate) { try {// w w w . ja va 2 s . co m String url = configParamService.findValueByName("Sakai.Url.Base") + "user_prefs.json"; ResponseEntity<InputStream> is = oncourseOAuthService.oAuthGetRequest(user, url, "text/html"); String prefsJson = IOUtils.toString(is.getBody(), "UTF-8"); Set<String> visibleSiteIds = new HashSet<String>(); try { JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(prefsJson); JSONArray itemArray = jsonObj.getJSONArray("user_prefs_collection"); if (itemArray != null) { for (Iterator<JSONObject> iter = itemArray.iterator(); iter.hasNext();) { JSONObject object = iter.next(); visibleSiteIds.add(object.getString("siteId")); } } } catch (Exception e) { LOG.error(e.getMessage(), e); } Set<String> calendarCourseIds = new HashSet<String>(); try { Calendar todayDate = Calendar.getInstance(); Calendar tomorrowDate = Calendar.getInstance(); if (shortDate != null) { try { todayDate.setTime(Constants.DateFormat.queryStringDateFormat.getFormat().parse(shortDate)); } catch (Exception e) { } } todayDate.set(Calendar.HOUR, 0); todayDate.set(Calendar.MINUTE, 0); todayDate.set(Calendar.SECOND, 0); todayDate.set(Calendar.MILLISECOND, 0); tomorrowDate.setTime(todayDate.getTime()); tomorrowDate.add(Calendar.DATE, 1); ListViewEvents listViewEvents = calendarEventOAuthService.retrieveViewEventsList(user, todayDate.getTime(), todayDate.getTime(), todayDate.getTime(), null); List<ListData> events = listViewEvents.getEvents(); if (events.size() > 0) { ListData list = events.get(0); List<CalendarViewEvent> viewEvents = list.getEvents(); for (CalendarViewEvent event : viewEvents) { if (event.getOncourseSiteId() != null) { calendarCourseIds.add(event.getOncourseSiteId().toLowerCase()); } } } } catch (Exception e) { LOG.error(e.getMessage(), e); } url = configParamService.findValueByName("Sakai.Url.Base") + "site.json"; is = oncourseOAuthService.oAuthGetRequest(user, url, "text/html"); String siteJson = IOUtils.toString(is.getBody(), "UTF-8"); Home home = new Home(); List<Term> courses = home.getCourses(); List<Site> projects = home.getProjects(); List<Site> other = home.getOther(); List<Site> today = home.getTodaysCourses(); Map<String, Term> courseMap = new HashMap<String, Term>(); Map<String, Site> courseSiteMap = new HashMap<String, Site>(); List<String> courseSiteIdList = new ArrayList<String>(); JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(siteJson); JSONArray itemArray = jsonObj.getJSONArray("site_collection"); for (Iterator<JSONObject> iter = itemArray.iterator(); iter.hasNext();) { JSONObject object = iter.next(); String id = object.getString("id"); if (!visibleSiteIds.contains(id)) { continue; } Site item = new Site(); item.setId(id); item.setTitle(object.getString("title")); item.setDescription(object.getString("shortDescription").replace(" ", " ")); String type = object.getString("type"); if ("course".equals(type)) { Object jsonProps = object.get("props"); String term = null; if (jsonProps instanceof JSONObject) { JSONObject props = (JSONObject) jsonProps; try { term = props.getString("term"); term = term.toLowerCase(); String[] split = term.split(" "); term = ""; for (String s : split) { s = s.substring(0, 1).toUpperCase() + s.substring(1); term = term + s + " "; } term.trim(); } catch (Exception e) { } } item.setTerm(term); Term termObj = courseMap.get(term); if (termObj == null) { termObj = new Term(); termObj.setTerm(term); courseMap.put(term, termObj); } termObj.getCourses().add(item); courseSiteMap.put(item.getId(), item); courseSiteIdList.add(item.getId()); if (calendarCourseIds.contains(item.getId().toLowerCase())) { today.add(item); } } else if ("project".equals(type)) { projects.add(item); } else { other.add(item); } } // try { // List<ViewDetailedEvent> listViewEvents = calendarEventOAuthService.retrieveCourseEvents(user, courseSiteIdList); // for (ViewDetailedEvent event : listViewEvents) { // Site site = courseSiteMap.get(event.getOncourseSiteId()); // if (event.getRecurrenceMessage() != null && !event.getRecurrenceMessage().isEmpty()) { // site.setMeetingTime(event.getRecurrenceMessage()); // } else { // site.setMeetingTime(event.getDisplayDate()); // } // site.setLocation(event.getLocation()); // site.setBuildingCode(event.getLocationId()); // } // } catch (Exception e) { // LOG.error(e.getMessage(), e); // } for (Map.Entry<String, Term> entry : courseMap.entrySet()) { courses.add(entry.getValue()); } Collections.sort(courses); Collections.reverse(courses); return home; } catch (Exception e) { LOG.error(e.getMessage(), e); return new Home(); } }
From source file:es.udc.fic.test.model.ClasificacionServiceTest.java
@Test public void getClasificacionTest() { //Creamos una sola regata con la instancia de todos los objetos en memoria Regata regata = new Regata(); regata.setNombre("Mock Regata"); regata.setDescripcion("Mock Desc"); regataDao.save(regata);//www . j a v a 2s . com Tipo tipoCatamaran = new Tipo("Catamarn", "Desc Catamarn", false); tipoDao.save(tipoCatamaran); Tipo tipoCrucero = new Tipo("Crucero", "Desc Crucero", false); tipoDao.save(tipoCrucero); Tipo tipoLigero = new Tipo("Vela ligera", "Desc Vela ligera", true); tipoDao.save(tipoLigero); Barco b1 = new Barco(204566, "Juan Sebastian El Cano", tipoCatamaran, new Float(1.5), "Lagoon 421"); inscripcionService.inscribir(regata, b1, "Iago Surez"); Barco b2 = new Barco(199012, "El Holandes Errante", tipoCrucero, new Float(2.5), "SWAN 66 FD"); inscripcionService.inscribir(regata, b2, "Samu Paredes"); Barco b3 = new Barco(201402, "La Perla Negra", tipoCrucero, new Float(1.5), "X6"); inscripcionService.inscribir(regata, b3, "Adrian Pallas"); Barco b4 = new Barco(202102, "La Pinta", tipoCrucero, new Float(1.5), "X6"); inscripcionService.inscribir(regata, b4, "Pedro Cabalar"); Barco b5 = new Barco(182345, "Venus", tipoLigero, null, "Laser Standar"); inscripcionService.inscribir(regata, b5, "Jesus Lopez"); Barco b6 = new Barco(206745, "Apolo", tipoLigero, null, "Laser Radial"); inscripcionService.inscribir(regata, b6, "Diego Bascoy"); Calendar dia1 = Calendar.getInstance(); dia1.add(Calendar.DAY_OF_YEAR, -18); Calendar dia2 = Calendar.getInstance(); dia2.add(Calendar.DAY_OF_YEAR, -18); dia2.add(Calendar.HOUR, 2); Calendar dia3 = Calendar.getInstance(); dia3.add(Calendar.DAY_OF_YEAR, -17); Manga manga1 = new Manga(dia1, regata, null, 100); Manga manga2 = new Manga(dia2, regata, null, 100); Manga manga3 = new Manga(dia3, regata, null, 100); List<Posicion> posManga1 = new ArrayList<Posicion>(); posManga1.add(new Posicion(new Long(3600), Posicion.Penalizacion.ZFP, manga1, b1, (long) 0)); posManga1.add(new Posicion(new Long(3700), Posicion.Penalizacion.NAN, manga1, b2, (long) 0)); posManga1.add(new Posicion(new Long(3750), Posicion.Penalizacion.ZFP, manga1, b3, (long) 0)); posManga1.add(new Posicion(new Long(3900), Posicion.Penalizacion.NAN, manga1, b4, (long) 0)); posManga1.add(new Posicion(new Long(3400), Posicion.Penalizacion.NAN, manga1, b5, (long) 0)); posManga1.add(new Posicion(new Long(2400), Posicion.Penalizacion.SCP, manga1, b6, (long) 0)); manga1.setPosiciones(posManga1); mangaService.cerrarYGuardarManga(manga1); regata.addManga(manga1); List<Posicion> posManga2 = new ArrayList<Posicion>(); posManga2.add(new Posicion(new Long(3400), Posicion.Penalizacion.ZFP, manga2, b1, (long) 0)); posManga2.add(new Posicion(new Long(3600), Posicion.Penalizacion.NAN, manga2, b2, (long) 0)); posManga2.add(new Posicion(new Long(3950), Posicion.Penalizacion.ZFP, manga2, b3, (long) 0)); posManga2.add(new Posicion(new Long(3200), Posicion.Penalizacion.NAN, manga2, b4, (long) 0)); posManga2.add(new Posicion(new Long(3100), Posicion.Penalizacion.ZFP, manga2, b5, (long) 0)); posManga2.add(new Posicion(new Long(2800), Posicion.Penalizacion.SCP, manga2, b6, (long) 0)); manga2.setPosiciones(posManga2); mangaService.cerrarYGuardarManga(manga2); regata.addManga(manga2); List<Posicion> posManga3 = new ArrayList<Posicion>(); posManga3.add(new Posicion(new Long(13500), Posicion.Penalizacion.SCP, manga3, b1, (long) 0)); posManga3.add(new Posicion(new Long(13200), Posicion.Penalizacion.NAN, manga3, b2, (long) 0)); posManga3.add(new Posicion(new Long(13350), Posicion.Penalizacion.NAN, manga3, b3, (long) 0)); posManga3.add(new Posicion(new Long(13900), Posicion.Penalizacion.ZFP, manga3, b4, (long) 0)); posManga3.add(new Posicion(new Long(14400), Posicion.Penalizacion.NAN, manga3, b5, (long) 0)); posManga3.add(new Posicion(new Long(15400), Posicion.Penalizacion.SCP, manga3, b6, (long) 0)); manga3.setPosiciones(posManga3); mangaService.cerrarYGuardarManga(manga3); regata.addManga(manga3); // //Mostrar los datos: // for(List<Posicion> lp : posicionesGeneralFinal){ // int total = 0; // System.out.print(lp.get(0).getBarco().getVela() + ": "); // for(Posicion p : lp){ // System.out.print(p.getPuntos() + " | "); // total += p.getPuntos(); // } // System.out.println("Tot: " + total); // } //Testeamos la clasificacion Final por Tipo Tipo tipo = tipoCrucero; List<List<Posicion>> posicionesFinalTipo = regataService.getClasificacion(regata, null, tipo); //Comprobamos que estn todos los barcos y que no estn repetido assertEquals(inscripcionService.getInscripcionesByTipo(regata, tipo).size(), posicionesFinalTipo.size()); //Comprobamos que hay tantas posiciones como mangas for (List<Posicion> posBarco : posicionesFinalTipo) { assertEquals(posBarco.size(), regata.getMangas().size()); } //Comprobamos que todas las posiciones de la misma sublista pertenecen // al mismo Barco. for (List<Posicion> posBarco : posicionesFinalTipo) { Barco barcoAct = posBarco.get(0).getBarco(); for (Posicion p : posBarco) { assertEquals(barcoAct, p.getBarco()); } } Calendar fechaAnterior = null; //Comprobamos que las listas internas estn ordenadas por la fecha de // la manga for (List<Posicion> posBarco : posicionesFinalTipo) { for (int i = 0; i < posBarco.size(); i++) { Calendar fechaActual = posBarco.get(i).getManga().getFecha(); if (i > 0) { //Comparamos los calendars: assertTrue(fechaAnterior.before(fechaActual)); } fechaAnterior = fechaActual; } } int puntActual; int puntAnterior = 0; //Comprobamos que el resultado viene bien ordenado por la puntuacion for (List<Posicion> posBarco : posicionesFinalTipo) { puntActual = 0; for (Posicion p : posBarco) { puntActual += p.getPuntos(); } assertTrue(puntActual >= puntAnterior); puntAnterior = puntActual; } for (List<Posicion> posBarco : posicionesFinalTipo) { for (Posicion posicion : posBarco) { assertEquals(tipo, posicion.getBarco().getTipo()); } } //Testeamos la clasificacion General por Dia Calendar dia = dia2; List<List<Posicion>> posicionesDiaGeneral = regataService.getClasificacion(regata, dia, null); for (List<Posicion> posBarco : posicionesDiaGeneral) { for (Posicion posicion : posBarco) { assertTrue(TimeUtil.compareByDay(dia, posicion.getManga().getFecha())); } } //Testeamos la clisificacion de un Tipo en un Dia Tipo tipoEspecifico = tipoCrucero; Calendar diaEspecifico = dia2; List<List<Posicion>> posicionesDiaTipo = regataService.getClasificacion(regata, diaEspecifico, tipoEspecifico); for (List<Posicion> posBarco : posicionesDiaTipo) { for (Posicion posicion : posBarco) { assertEquals(tipoEspecifico, posicion.getBarco().getTipo()); assertTrue(TimeUtil.compareByDay(diaEspecifico, posicion.getManga().getFecha())); } } }