List of usage examples for java.util Calendar DAY_OF_YEAR
int DAY_OF_YEAR
To view the source code for java.util Calendar DAY_OF_YEAR.
Click Source Link
get
and set
indicating the day number within the current year. From source file:com.layer.atlas.AtlasMessagesList.java
public void updateValues() { if (conv == null) return;//from w ww.j av a 2 s . c o m long started = System.currentTimeMillis(); List<Message> messages = client.getMessages(conv); cells.clear(); if (messages.isEmpty()) return; latestReadMessage = null; latestDeliveredMessage = null; ArrayList<Cell> messageItems = new ArrayList<AtlasMessagesList.Cell>(); for (Message message : messages) { // System messages have `null` user ID if (message.getSender().getUserId() == null) continue; messageItems.clear(); buildCellForMessage(message, messageItems); cells.addAll(messageItems); } updateDeliveryStatus(messages); // calculate heads/tails int currentItem = 0; int clusterId = currentItem; String currentUser = null; long lastMessageTime = 0; Calendar calLastMessage = Calendar.getInstance(); Calendar calCurrent = Calendar.getInstance(); long clusterTimeSpan = 60 * 1000; // 1 minute long oneHourSpan = 60 * 60 * 1000; // 1 hour for (int i = 0; i < cells.size(); i++) { Cell item = cells.get(i); boolean newCluster = false; if (!item.messagePart.getMessage().getSender().getUserId().equals(currentUser)) { newCluster = true; } Date sentAt = item.messagePart.getMessage().getSentAt(); if (sentAt == null) sentAt = new Date(); if (sentAt.getTime() - lastMessageTime > clusterTimeSpan) { newCluster = true; } if (newCluster) { clusterId = currentItem; if (i > 0) cells.get(i - 1).clusterTail = true; } // check time header is needed if (sentAt.getTime() - lastMessageTime > oneHourSpan) { item.timeHeader = true; } calCurrent.setTime(sentAt); if (calCurrent.get(Calendar.DAY_OF_YEAR) != calLastMessage.get(Calendar.DAY_OF_YEAR)) { item.timeHeader = true; } item.clusterHeadItemId = clusterId; item.clusterItemId = currentItem++; currentUser = item.messagePart.getMessage().getSender().getUserId(); lastMessageTime = sentAt.getTime(); calLastMessage.setTime(sentAt); if (false && debug) Log.d(TAG, "updateValues() item: " + item); } cells.get(cells.size() - 1).clusterTail = true; // last one is always a tail if (debug) Log.d(TAG, "updateValues() parts finished in: " + (System.currentTimeMillis() - started)); messagesAdapter.notifyDataSetChanged(); }
From source file:ezbake.data.elastic.IT_EzElasticIntegrationTest.java
@Test public void testRangeDateFacets() throws Exception { // Prepare: Setup Thrift Client and add some docs final SimpleDateFormat dtg = new SimpleDateFormat("ddHHmm'Z' MM yy"); client = pool.getClient(SERVICE_NAME, EzElastic.Client.class); client.setTypeMapping(TEST_TYPE, getMappingForTest(), fakeSecurity); client.bulkPut(Arrays.asList(jeffersonMemorialDoc, whiteHouseDoc, columbiaDoc, lincolnMemorialDoc), fakeSecurity);/*from w ww. j ava2s. c o m*/ Calendar calendar = new GregorianCalendar(); calendar.add(Calendar.DAY_OF_YEAR, -1); long last24Time = DateUtils.round(calendar, Calendar.HOUR).getTimeInMillis(); calendar.add(Calendar.DAY_OF_YEAR, -1); long last48Time = DateUtils.round(calendar, Calendar.HOUR).getTimeInMillis(); calendar.add(Calendar.DAY_OF_YEAR, -1); long last72Time = DateUtils.round(calendar, Calendar.HOUR).getTimeInMillis(); List<Facet> rangeDateFacets = Collections .singletonList(EzElasticTestUtils.generateDateBucketFacet(last24Time, last48Time, last72Time)); // Action: Create and execute a match all query with date bucket facets final Query query = new Query(QueryBuilders.matchAllQuery().toString()); query.setType(TEST_TYPE).setFacets(rangeDateFacets).setPage(new Page(0, (short) 10)); final SearchResult results = client.query(query, fakeSecurity); // Assert: All records should be a match and the facet buckets should be organized as expected assertEquals(4, results.getTotalHits()); assertFalse(results.getFacets().isEmpty()); assertTrue(results.getFacets().containsKey("Report Date")); final FacetResult facetResult = results.getFacets().get("Report Date"); for (final RangeFacetEntry entry : facetResult.getRangeFacetResult().getEntries()) { if (dtg.parse(entry.getRangeFrom()).getTime() >= last24Time || dtg.parse(entry.getRangeFrom()).getTime() >= last48Time || dtg.parse(entry.getRangeFrom()).getTime() >= last72Time) { assertEquals(3, entry.getCount()); } else { assertEquals(4, entry.getCount()); } } pool.returnToPool(client); }
From source file:com.aurel.track.linkType.MsProjectLinkTypeBL.java
/** * Returns number of saturdays from interval. Start date included always, endDate only if includeLastDay == true! * @param startDateParam// ww w . j a v a 2s. com * @param endDateParam * @param includeLastDay * @return */ public static Integer getNumberOfSaturdaysFromInterval(Date startDateParam, Date endDateParam, boolean includeLastDay) { Date realEndDate = endDateParam; if (includeLastDay) { Calendar cal = Calendar.getInstance(); cal.setTime(realEndDate); cal.add(Calendar.DAY_OF_YEAR, 1); realEndDate = cal.getTime(); } Calendar calendar = Calendar.getInstance(); calendar.setTime(startDateParam); int numOfSaturdays = 0; while (!calendar.getTime().after(realEndDate)) { if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { numOfSaturdays++; } calendar.add(Calendar.DAY_OF_MONTH, 1); } return numOfSaturdays; }
From source file:bamboo.trove.rule.RuleChangeUpdateManager.java
private WorkLog findDocumentsDateRule(CdxRule dateBasedRule, String notLastIndexed) throws SolrServerException, IOException { WorkLog workLog = new WorkLog(dateBasedRule.getId()); // these are from no change to the rule so we are checking date coming into or going out of range boolean urlSearchNeeded = false; // ******************* // Access dates CdxDateRange accessDates = dateBasedRule.getAccessed(); if (accessDates != null && accessDates.hasData()) { if (accessDates.contains(CdxRestrictionService.TODAY)) { // now is in range so we need to search by url urlSearchNeeded = true;/*from w w w .j a v a 2 s .com*/ } else { // Rule is no longer applicable. Look for records set by the rule to re-process them SolrQuery query = createQuery(SolrEnum.RULE + ":" + dateBasedRule.getId()); query.addFilterQuery(notLastIndexed); processQuery(query, workLog); // Job done... this rule will no longer apply to anything in the index return workLog; } } // ******************* // Embargoes if (dateBasedRule.getPeriod() != null && !dateBasedRule.getPeriod().isZero()) { // Any capture dates older than TODAY - embargo period should be checked for possible release Calendar c = Calendar.getInstance(); c.setTime(CdxRestrictionService.TODAY); c.add(Calendar.YEAR, -dateBasedRule.getPeriod().getYears()); c.add(Calendar.MONTH, -dateBasedRule.getPeriod().getMonths()); c.add(Calendar.DAY_OF_YEAR, -dateBasedRule.getPeriod().getDays()); SolrQuery query = createQuery(SolrEnum.RULE + ":" + dateBasedRule.getId()); query.addFilterQuery(SolrEnum.DATE + ":[* TO " + format.format(c.getTime()) + "]"); query.addFilterQuery(notLastIndexed); processQuery(query, workLog); } // ******************* // URL based search if (urlSearchNeeded) { SolrQuery query = convertRuleToSearch(dateBasedRule, notLastIndexed); processQuery(query, workLog); } return workLog; }
From source file:es.udc.fic.test.model.CerrarMangaTest.java
public void addData() { //Creamos una sola regata con la instancia de todos los objetos en memoria regata = new Regata(); regata.setNombre("Mock Regata"); regata.setDescripcion("Mock Desc"); regataDao.save(regata);//from w w w. j av a2 s. c o m Tipo tipoCruceros = new Tipo("Cruceros", "Desc Cruceros", false); tipoDao.save(tipoCruceros); Tipo tipoLanchas = new Tipo("Lanchas", "Desc Lanchas", false); tipoDao.save(tipoLanchas); b1 = new Barco(204566, "Juan Sebastian El Cano", tipoCruceros, (float) 1.5, "X6"); inscripcionService.inscribir(regata, b1, "Iago Surez"); b2 = new Barco(199012, "El Holandes Errante", tipoCruceros, (float) 1.8, "X2"); inscripcionService.inscribir(regata, b2, "Samu Paredes"); b3 = new Barco(201402, "La Perla Negra", tipoCruceros, (float) 1.0, "X8"); inscripcionService.inscribir(regata, b3, "Adrian Pallas"); b4 = new Barco(202102, "La Pinta", tipoCruceros, (float) 2.0, "X7"); inscripcionService.inscribir(regata, b4, "Pedro Cabalar"); b5 = new Barco(182345, "Venus", tipoCruceros, (float) 1.5, "X7"); //Ponemos otro tipo para ver como funciona la clasificacion inscripcionService.inscribir(regata, b5, "Jesus Lopez"); b6 = new Barco(206745, "Apolo", tipoLanchas, null, "Motora"); 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); // COMPROBAMOS LAS DESCALIFICACIONES QUE NO ACARREAN EL MAX DE PUNT. manga1 = new Manga(dia1, regata, null, 100); List<Posicion> posManga1 = new ArrayList<Posicion>(); //NAN -> 0 penal //ZFP -> 20% penal //SCP RDG DPI -> Penal en tiempo //Cruceros // ZFP (3000 + 1.5* 100 )* 1.20 = 3780s -> Tercero posManga1.add(new Posicion((long) 3000, Posicion.Penalizacion.ZFP, manga1, b1, null)); //SCP (3300 + 1.5 * 100) + 150s = 3600s -> Segundo posManga1.add(new Posicion((long) 3300, Posicion.Penalizacion.SCP, manga1, b2, (long) 150)); //NAN (3400 + 1.0 * 100) = 3500s -> Primero posManga1.add(new Posicion((long) 3400, Posicion.Penalizacion.NAN, manga1, b3, (long) 0)); //RDG (3750 + 2.0 *100 ) = 3950s -> Cuarto posManga1.add(new Posicion((long) 3750, Posicion.Penalizacion.RDG, manga1, b4, (long) 0)); //DPI (3800+60) +(1.5 *100) = 4010s -> Quinto posManga1.add(new Posicion((long) 3800, Posicion.Penalizacion.DPI, manga1, b5, (long) 60)); //Lanchas //Primero -> Puntos 1 posManga1.add(new Posicion((long) 3300, Posicion.Penalizacion.ZFP, manga1, b6, (long) 0)); manga1.setPosiciones(posManga1); mangaService.cerrarYGuardarManga(manga1); regata.addManga(manga1); //Comprobamos que los puntos son correctos //Guardamos las posiciones por tipos posPorBarco = new HashMap<Barco, Posicion>(); for (Posicion p : manga1.getPosiciones()) { //Aadimos la posicionActual posPorBarco.put(p.getBarco(), p); } // COMPROBAMOS LAS DESCALIFICACIONES QUE ACARREAN EL MAX DE PUNT. manga2 = new Manga(dia2, regata, null, 100); List<Posicion> posManga2 = new ArrayList<Posicion>(); //DNC DNS -> No Salio // DNF RET DSQ -> No termino / Retirado / Descalificado // DNE DGM -> Descalificaciones Graves // BFD -> Bandera negra //Velas Ligeras // ZFP 3600s -> Primero (unico el llegar) posManga2.add(new Posicion((long) 3000, Posicion.Penalizacion.ZFP, manga1, b1, (long) 0)); //DNF No termino -> Ultimo -> 6 Puntos posManga2.add(new Posicion((long) 3300, Posicion.Penalizacion.DNF, manga1, b2, null)); //DNE Descalificado -> Ultimo -> 6 Puntos posManga2.add(new Posicion((long) 3400, Posicion.Penalizacion.DNE, manga1, b3, null)); //DNE Descalificado -> Ultimo -> 6 Puntos posManga2.add(new Posicion((long) 3750, Posicion.Penalizacion.DNE, manga1, b4, null)); //DGM Descalificado -> Ultimo -> 6 Puntos posManga2.add(new Posicion((long) 3800, Posicion.Penalizacion.DGM, manga1, b5, null)); //Lanchas //RET Retirado -> Puntos 2 posManga2.add(new Posicion((long) 3300, Posicion.Penalizacion.RET, manga1, b6, null)); manga2.setPosiciones(posManga2); mangaService.cerrarYGuardarManga(manga2); regata.addManga(manga2); }
From source file:com.hangum.tadpole.commons.admin.core.editors.sqlaudit.AdminSQLAuditEditor.java
/** * ?? .//from w ww . j ava 2 s . co m */ private void initUIData() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, -7); dateTimeStart.setDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); callbackui(); }
From source file:edu.ucsb.nceas.MCTestCase.java
/** * Create a unique docid for testing insert and update. Does not * include the 'revision' part of the id. * /* www .j av a2s .c o m*/ * @return a String docid based on the current date and time */ protected String generateDocumentId() { try { Thread.sleep(1010); } catch (InterruptedException ie) { debug("Could not sleep: " + ie.getMessage()); } StringBuffer docid = new StringBuffer(prefix); docid.append("."); // Create a calendar to get the date formatted properly String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000); SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]); pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); Calendar calendar = new GregorianCalendar(pdt); Date trialTime = new Date(); calendar.setTime(trialTime); docid.append(calendar.get(Calendar.YEAR)); docid.append(calendar.get(Calendar.DAY_OF_YEAR)); docid.append(calendar.get(Calendar.HOUR_OF_DAY)); docid.append(calendar.get(Calendar.MINUTE)); docid.append(calendar.get(Calendar.SECOND)); return docid.toString(); }
From source file:es.ficonlan.web.backend.test.eventservice.EventServiceTest.java
@Test public void changeNewsDataTest() throws ServiceException { Session anonymousSession = userService.newAnonymousSession(); Session s = userService.login(anonymousSession.getSessionId(), ADMIN_LOGIN, ADMIN_PASS); NewsItem news = new NewsItem("Nueva noticia", Calendar.getInstance(), "http://ficonlan/nuevaNoticia", 2); Calendar dateStart = Calendar.getInstance(); Calendar dateEnd = Calendar.getInstance(); Event event = new Event(0, "FicOnLan 2014", "FicOnLan 2014", 150, dateStart, dateEnd, dateStart, dateEnd, null, null, null, null, null); eventService.createEvent(s.getSessionId(), event); eventService.addNews(s.getSessionId(), event.getEventId(), news); Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_YEAR, 1); NewsItem newsData = new NewsItem("Nueva noticia2", c, "http://ficonlan/nuevaNoticia2", 3); newsData.setNewsItemId(news.getNewsItemId()); eventService.changeNewsData(s.getSessionId(), newsData.getNewsItemId(), newsData); assertTrue(news.getTitle().contentEquals("Nueva noticia2")); assertTrue(news.getContent().contentEquals("http://ficonlan/nuevaNoticia2")); assertTrue(news.getPublishDate().compareTo(c) == 0); assertTrue(news.getPriorityHours() == 3); }
From source file:com.aurel.track.linkType.MsProjectLinkTypeBL.java
/** * Returns number of sundays from interval. Start date included always, endDate only if includeLastDay == true! * @param startDateParam/* w ww . ja va2s .c om*/ * @param endDateParam * @param includeLastDay * @return */ public static Integer getNumberOfSundaysFromInterval(Date startDateParam, Date endDateParam, boolean includeLastDay) { Date realEndDate = endDateParam; if (includeLastDay) { Calendar cal = Calendar.getInstance(); cal.setTime(realEndDate); cal.add(Calendar.DAY_OF_YEAR, 1); realEndDate = cal.getTime(); } Calendar calendar = Calendar.getInstance(); calendar.setTime(startDateParam); int numOfSunday = 0; while (!calendar.getTime().after(realEndDate)) { if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { numOfSunday++; } calendar.add(Calendar.DAY_OF_MONTH, 1); } return numOfSunday; }
From source file:arc.noaa.weather.activities.MainActivity.java
public ParseResult parseLongTermJson(String result) { int i;/*from w w w. jav a2 s . co m*/ try { JSONObject reader = new JSONObject(result); final String code = reader.optString("cod"); if ("404".equals(code)) { if (longTermWeather == null) { longTermWeather = new ArrayList<>(); longTermTodayWeather = new ArrayList<>(); longTermTomorrowWeather = new ArrayList<>(); } return ParseResult.CITY_NOT_FOUND; } longTermWeather = new ArrayList<>(); longTermTodayWeather = new ArrayList<>(); longTermTomorrowWeather = new ArrayList<>(); JSONArray list = reader.getJSONArray("list"); for (i = 0; i < list.length(); i++) { Weather weather = new Weather(); JSONObject listItem = list.getJSONObject(i); JSONObject main = listItem.getJSONObject("main"); weather.setDate(listItem.getString("dt")); weather.setTemperature(main.getString("temp")); weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description")); JSONObject windObj = listItem.optJSONObject("wind"); if (windObj != null) { weather.setWind(windObj.getString("speed")); weather.setWindDirectionDegree(windObj.getDouble("deg")); } weather.setPressure(main.getString("pressure")); weather.setHumidity(main.getString("humidity")); JSONObject rainObj = listItem.optJSONObject("rain"); String rain = ""; if (rainObj != null) { rain = getRainString(rainObj); } else { JSONObject snowObj = listItem.optJSONObject("snow"); if (snowObj != null) { rain = getRainString(snowObj); } else { rain = "0"; } } weather.setRain(rain); final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id"); weather.setId(idString); final String dateMsString = listItem.getString("dt") + "000"; Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(Long.parseLong(dateMsString)); weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY))); Calendar today = Calendar.getInstance(); if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) { longTermTodayWeather.add(weather); } else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) { longTermTomorrowWeather.add(weather); } else { longTermWeather.add(weather); } } SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this) .edit(); editor.putString("lastLongterm", result); editor.commit(); } catch (JSONException e) { Log.e("JSONException Data", result); e.printStackTrace(); return ParseResult.JSON_EXCEPTION; } return ParseResult.OK; }