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:mekhq.campaign.mission.Contract.java
/** * Only do this at the time the contract is set up, otherwise amounts may change after * the ink is signed, which is a no-no.//from w w w. ja v a 2 s . c o m * @param c */ public void calculateContract(Campaign c) { //calculate base amount baseAmount = (long) (paymentMultiplier * getLength() * c.getContractBase()); //calculate overhead switch (overheadComp) { case OH_HALF: overheadAmount = (long) (0.5 * c.getOverheadExpenses() * getLength()); break; case OH_FULL: overheadAmount = 1 * c.getOverheadExpenses() * getLength(); break; default: overheadAmount = 0; } //calculate support amount if (c.getCampaignOptions().usePeacetimeCost() && c.getCampaignOptions().getUnitRatingMethod() .equals(mekhq.campaign.rating.UnitRatingMethod.CAMPAIGN_OPS)) { supportAmount = (long) ((straightSupport / 100.0) * c.getPeacetimeCost() * getLength()); } else { long maintCosts = 0; for (Unit u : c.getUnits()) { if (u.getEntity() instanceof Infantry && !(u.getEntity() instanceof BattleArmor)) { continue; } maintCosts += u.getWeeklyMaintenanceCost(); } maintCosts *= 4; supportAmount = (long) ((straightSupport / 100.0) * maintCosts * getLength()); } //calculate transportation costs if (null != getPlanet()) { JumpPath jumpPath = c.calculateJumpPath(c.getCurrentPlanet(), getPlanet()); // FM:Mercs transport payments take into account owned transports and do not use CampaignOps dropship costs. // CampaignOps doesn't care about owned transports and does use its own dropship costs. boolean campaignOps = c.getCampaignOptions().useEquipmentContractBase(); transportAmount = (long) ((transportComp / 100.0) * 2 * c.calculateCostPerJump(campaignOps, campaignOps) * jumpPath.getJumps()); } //calculate transit amount for CO if (c.getCampaignOptions().usePeacetimeCost() && c.getCampaignOptions().getUnitRatingMethod() .equals(mekhq.campaign.rating.UnitRatingMethod.CAMPAIGN_OPS)) { //contract base * transport period * reputation * employer modifier transitAmount = (long) (c.getContractBase() * (((c.calculateJumpPath(c.getCurrentPlanet(), getPlanet()).getJumps()) * 2) / 4) * (c.getUnitRatingMod() * .2 + .5) * 1.2); } else { transitAmount = 0; } signingAmount = (long) ((signBonus / 100.0) * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount)); advanceAmount = (long) ((advancePct / 100.0) * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount)); if (mrbcFee) { feeAmount = (long) (0.05 * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount)); } else { feeAmount = 0; } // only adjust the start date for travel if the start date is currently null boolean adjustStartDate = false; if (null == startDate) { startDate = c.getCalendar().getTime(); adjustStartDate = true; } GregorianCalendar cal = new GregorianCalendar(); cal.setTime(startDate); if (adjustStartDate && null != c.getPlanet(planetId)) { int days = (int) Math.ceil(c.calculateJumpPath(c.getCurrentPlanet(), getPlanet()) .getTotalTime(Utilities.getDateTimeDay(cal), c.getLocation().getTransitTime())); while (days > 0) { cal.add(Calendar.DAY_OF_YEAR, 1); days--; } startDate = cal.getTime(); } int months = getLength(); while (months > 0) { cal.add(Calendar.MONTH, 1); months--; } endDate = cal.getTime(); }
From source file:it.sayservice.platform.smartplanner.cache.annotated.AnnotatedReader.java
public void buildTimetable(String router, String agencyId, boolean setTripsIds, List<AnnotatedTimetable> timetables) throws Exception { AgencyCacheIndex aci = new AgencyCacheIndex(agencyId); aci.setVersion(1);// w w w . j a va 2 s.c o m ObjectMapper mapper = new ObjectMapper(); String cacheDir = System.getenv("OTP_HOME") + System.getProperty("file.separator") + router + System.getProperty("file.separator") + "cache" + System.getProperty("file.separator") + "client"; String agencyDir = cacheDir + System.getProperty("file.separator") + agencyId; File dir = new File(agencyDir); if (!dir.exists()) { dir.mkdir(); } else { for (File f : dir.listFiles()) { f.delete(); } } Map<String, WeekdayFilter> weekdayFilter = handler.readAgencyWeekDay(router, agencyId); Map<String, WeekdayException> weekdayException = handler.readAgencyWeekDayExceptions(router, agencyId); Multimap<String, ExtendedAnnotatedColumn> extendedAnnotatedColumn = createExtendedAnnotatedColumns( timetables); SetMultimap<String, String> tripsSymbolicRouteId = TreeMultimap.create(); List<SymbolicRouteDayInfoHashCalendar> agencySrdihs = Lists.newArrayList(); for (String rId : extendedAnnotatedColumn.keySet()) { System.out.println("Generating " + rId); Map<String, AnnotatedColumn> tripsColumns = Maps.newTreeMap(); Map<String, AnnotatedTimetable> tripsTable = Maps.newTreeMap(); Map<String, AnnotatedTimetable> serviceTable = Maps.newTreeMap(); AnnotatedTimetable baseTable = null; Multimap<String, String> daysTrips = ArrayListMultimap.create(); SetMultimap<String, String> daysServices = TreeMultimap.create(); Map<String, AnnotatedTimetable> daysTable = Maps.newTreeMap(); Map<String, String> daysHashes = Maps.newTreeMap(); Map<String, String> tripsRoutes = Maps.newTreeMap(); for (ExtendedAnnotatedColumn ac : extendedAnnotatedColumn.get(rId)) { baseTable = ac.getSource(); String tripId = agencyId + "_" + ac.getTripId(); tripsSymbolicRouteId.put(tripId, rId); tripsRoutes.put(ac.getTripId(), ac.getRouteId()); tripsColumns.put(tripId, ac); tripsTable.put(tripId, ac.getSource()); String serviceId = agencyId + "_" + ac.getServiceId(); serviceTable.put(serviceId, ac.getSource()); WeekdayFilter filter = weekdayFilter.get(serviceId); if (filter == null) { System.out.println("ServiceId not found: " + serviceId); } Set<String> days = Sets.newHashSet(); DateFormat df = new SimpleDateFormat("yyyyMMdd"); String from = filter.getFromDate(); String to = filter.getToDate(); Calendar fromDate = new GregorianCalendar(); Calendar toDate = new GregorianCalendar(); fromDate.setTime(df.parse(from)); toDate.setTime(df.parse(to)); Calendar date = new GregorianCalendar(); date.setTime(fromDate.getTime()); String prevDay = null; while (df.format(date.getTime()).compareTo(to) <= 0) { String day = df.format(date.getTime()); boolean sameDay = day.equals(prevDay); if (!sameDay) { int dotw = convertDayOfTheWeek(date.get(Calendar.DAY_OF_WEEK)); if (filter.getDays()[dotw]) { days.add(day); } } prevDay = day; date.setTime(new Date(date.getTime().getTime())); date.add(Calendar.DAY_OF_YEAR, 1); } WeekdayException ex = weekdayException.get(serviceId); if (ex != null) { for (String toAdd : ex.getAdded()) { days.add(toAdd); } for (String toRemove : ex.getRemoved()) { days.remove(toRemove); } } ac.setDays(Lists.newArrayList(days)); for (String day : days) { daysTable.put(day, baseTable); daysTrips.put(day, tripId); daysServices.put(day, serviceId); } } Map<String, CacheTable> hashTable = Maps.newTreeMap(); SymbolicRouteDayInfoHashCalendar srdihs = new SymbolicRouteDayInfoHashCalendar(); srdihs.setAgencyId(agencyId); agencySrdihs.add(srdihs); Map<String, String> srdihsCalendar = Maps.newTreeMap(); Map<String, SymbolicRouteDayInfo> srdihsValues = Maps.newTreeMap(); srdihs.setCalendar(srdihsCalendar); srdihs.setValues(srdihsValues); srdihs.setRouteId(rId); for (String day : daysTrips.keySet()) { List<String> dayTrips = Lists.newArrayList(daysTrips.get(day)); List<String> dayServices = Lists.newArrayList(daysServices.get(day)); String hash = getEqString(dayServices, agencyId); if (daysHashes.containsKey(day)) { continue; } daysHashes.put(day, hash); Set<String> dayServicesSet = daysServices.get(day); AnnotatedTimetable reducedTable = reduceAnnotatedTimetable(daysTable.get(day), dayServicesSet, agencyId); CacheTable ct = new CacheTable(); List<String> tripIds = Lists.newArrayList(); List<List<String>> compressedTimes = Lists.newArrayList(); ct.setTimes(compressedTimes); for (String trip : dayTrips) { int index = trip.indexOf("_"); tripIds.add(trip.substring(index + 1)); compressedTimes.add(tripsColumns.get(trip).getTimes()); } if (setTripsIds) { ct.setTripIds(tripIds); } List<String> routesIds = Lists.newArrayList(); for (String ti : tripIds) { routesIds.add(tripsRoutes.get(ti)); } ct.setStops(reducedTable.getStopNames()); ct.setStopsId(reducedTable.getStopIds()); ct.setInvisibles(reducedTable.getInvisibles()); ct.setFrequency(reducedTable.getFrequency()); ct.setLine(reducedTable.getLine()); ct.setRoutesIds(routesIds); ct.setShortDescription(reducedTable.getShortDescription()); ct.setLongDescription(reducedTable.getLongDescription()); ct.setValidity(reducedTable.getValidity()); ct.setSchedule(reducedTable.getSchedule()); ct.compress(); hashTable.put(hash, ct); if (!srdihsValues.containsKey(hash)) { SymbolicRouteDayInfo srdi = new SymbolicRouteDayInfo(reducedTable); StopNames sn = new StopNames(); sn.setRouteId(rId); sn.setIds(reducedTable.getStopIds()); sn.setNames(reducedTable.getStopNames()); srdi.setStopNames(sn); srdi.setTripIds(tripIds); srdihsValues.put(hash, srdi); } srdihsCalendar.put(day, hash); } System.out.println("Writing " + rId); String calendar = agencyDir + System.getProperty("file.separator") + "calendar_" + rId + ".js"; mapper.writeValue(new File(calendar), daysHashes); for (String hash : hashTable.keySet()) { String hashFile = agencyDir + System.getProperty("file.separator") + rId + "_" + hash + ".js"; mapper.writeValue(new File(hashFile), hashTable.get(hash)); CacheIndexEntry cie = new CacheIndexEntry(); cie.setId(rId + "_" + hash); cie.setVersion(1); cie.setStatus(CacheEntryStatus.ADDED); aci.getEntries().put(rId + "_" + hash, cie); } } String indexFile = cacheDir + System.getProperty("file.separator") + agencyId + "_index.txt"; File aciFile = new File(indexFile); if (aciFile.exists()) { AgencyCacheIndex oldAci = mapper.readValue(aciFile, AgencyCacheIndex.class); aci.setVersion(oldAci.getVersion() + 1); } mapper.writeValue(new File(indexFile), aci); String auxDir = cacheDir + System.getProperty("file.separator") + Constants.AUXILIARY_CACHE_DIR; String infoFile = auxDir + System.getProperty("file.separator") + agencyId + "_info.txt"; mapper.writeValue(new File(infoFile), agencySrdihs); String symbolicFile = auxDir + System.getProperty("file.separator") + agencyId + "_symbolic_trips.txt"; Map<String, Collection<String>> map = Maps.newTreeMap(); for (String key : tripsSymbolicRouteId.keys()) { List<String> rids = Lists.newArrayList(); rids.addAll(tripsSymbolicRouteId.get(key)); map.put(key, rids); } mapper.writeValue(new File(symbolicFile), map); }
From source file:com.huateng.ebank.framework.util.DateUtil.java
/** * ?//from w ww . j a va 2 s .c o m * * @param startDate * @param days * @return */ public static Date getEndDateByDays(Date startDate, int days) { Calendar calendarStartDate = Calendar.getInstance(); calendarStartDate.setTime(startDate); calendarStartDate.add(Calendar.DAY_OF_YEAR, days); return calendarStartDate.getTime(); }
From source file:com.aurel.track.linkType.MsProjectLinkTypeBL.java
/** * This method adds steps to dateParam and returns. If withCheckingFreeDays == true * then weekends, and free days doesn't treats as work day. * @param dateParam//from w ww . ja v a2 s . c o m * @param steps * @param withCheckingFreeDays * @return */ public static Date stepForward(Date dateParam, int steps, boolean withCheckingFreeDays) { if (dateParam == null) { return null; } int actualSteps = 0; Calendar cal = Calendar.getInstance(); cal.setTime(dateParam); Date newDate = new Date(); while (actualSteps < steps) { cal.add(Calendar.DAY_OF_YEAR, 1); newDate = cal.getTime(); if (withCheckingFreeDays) { if (!WorkDaysConfigImplementation.isSaturday(newDate) && !WorkDaysConfigImplementation.isSunday(newDate) && !WorkDaysConfigImplementation.isFreeDay(newDate)) { actualSteps++; } } else { actualSteps++; } } return newDate; }
From source file:es.ficonlan.web.backend.test.eventservice.EventServiceTest.java
@Test public void testRemoveParticipantFromActivity() throws ServiceException { Session anonymousSession = userService.newAnonymousSession(); Session s = userService.login(anonymousSession.getSessionId(), ADMIN_LOGIN, ADMIN_PASS); User user = userService.addUser(anonymousSession.getSessionId(), new User("User1", "login1", "pass", "12345678R", "user1@gmail.com", "690047407", "L")); Calendar dateStart = Calendar.getInstance(); dateStart.add(Calendar.DAY_OF_YEAR, -1); Calendar dateEnd = Calendar.getInstance(); dateEnd.add(Calendar.DAY_OF_YEAR, 1); Event event = eventService.createEvent(s.getSessionId(), new Event(0, "FicOnLan 2014", "FicOnLan 2014", 150, dateStart, dateEnd, dateStart, dateEnd, null, null, null, null, null)); eventService.addParticipantToEvent(s.getSessionId(), user.getUserId(), event.getEventId()); Activity activity = eventService.addActivity(s.getSessionId(), event.getEventId(), new Activity(event, "Torneo de Lol", "Torneo de Lol", 10, ActivityType.Tournament, true, dateStart, dateEnd, dateStart, dateEnd)); eventService.addParticipantToActivity(s.getSessionId(), user.getUserId(), activity.getActivityId()); assertTrue(activity.getParticipants().contains(user)); eventService.removeParticipantFromActivity(s.getSessionId(), user.getUserId(), activity.getActivityId()); assertTrue(!activity.getParticipants().contains(user)); }
From source file:net.chaosserver.timelord.data.ExcelDataReaderWriter.java
/** * This creates all of the sheets for the workbook. The sheets * have names to associated with the proper dates, but have no data * filled into them.//www .j a v a 2s. c om * * This also builds out the sheetToNotes map by associating all the * notes data in the application with the sheet that the data will * eventually be written out to. * * @param workbook the workbook to create sheets on * @param timelordData the timelord data used for the sheets. * @param sheetToNotes the map of sheets to the notes associated with it * @param styleMap the map of styles */ protected void preCreateAllSheets(HSSFWorkbook workbook, TimelordData timelordData, Map<String, List<String>> sheetToNotes, Map<String, HSSFCellStyle> styleMap) { // This holds the most recent date in the entire data file. // This date starts out as null, and any time a task if found // with a more recent date it replaces this value. Date mostRecentDate = null; // This holds the oldest date in the entire data file. // This date starts out null and any time a task is found // with an older date it is replaced with this one. Date oldestDate = null; List<TimelordTask> taskCollection = timelordData.getTaskCollection(); Iterator<TimelordTask> taskIterator = taskCollection.iterator(); // Iterator through all the tasks in the data to create the // output sheet while (taskIterator.hasNext()) { TimelordTask timelordTask = (TimelordTask) taskIterator.next(); // Only exportable tasks should be considered. Tasks that aren't // exportable must be skipped if (timelordTask.isExportable()) { List<TimelordTaskDay> taskDayList = timelordTask.getTaskDayList(); if (!taskDayList.isEmpty()) { // Since the days associated with this task aren't empty, // pull out the first task. This is the most recent day // that has time tracked to it. TimelordTaskDay firstDay = (TimelordTaskDay) taskDayList.get(0); // If the first date in this task is more recent than the // most recent temporary date, replace it with this one. if (mostRecentDate == null || mostRecentDate.before(firstDay.getDate())) { if (logger.isTraceEnabled()) { logger.trace("Updating mostRecentDate from [" + mostRecentDate + "] to [" + firstDay.getDate() + "]"); } mostRecentDate = firstDay.getDate(); } // Just as a double check see if the earliest date is // the oldest and do the replacement. if (oldestDate == null || oldestDate.after(firstDay.getDate())) { if (logger.isTraceEnabled()) { logger.trace("Updating oldestDate from [" + oldestDate + "] to [" + firstDay.getDate() + "]"); } oldestDate = firstDay.getDate(); } // Grab the very last item in the list. This should // be the oldest date associated with the task. TimelordTaskDay lastDay = (TimelordTaskDay) taskDayList.get(taskDayList.size() - 1); if (mostRecentDate == null || mostRecentDate.before(lastDay.getDate())) { if (logger.isTraceEnabled()) { logger.trace("Updating mostRecentDate from [" + mostRecentDate + "] to [" + lastDay.getDate() + "]"); } mostRecentDate = lastDay.getDate(); } if (oldestDate == null || oldestDate.after(lastDay.getDate())) { if (logger.isTraceEnabled()) { logger.trace( "Updating oldestDate from [" + oldestDate + "] to [" + lastDay.getDate() + "]"); } oldestDate = lastDay.getDate(); } } } } if (logger.isDebugEnabled()) { logger.debug( "Found the oldestDate [" + oldestDate + "] to the mostRecentDate [" + mostRecentDate + "]"); } Calendar createSheetsCalendar = Calendar.getInstance(); createSheetsCalendar.setTime(mostRecentDate); // Start at the most recent date in the system and roll back // the dates creating the sheets until all the dates have been // covered. while (createSheetsCalendar.getTime().after(oldestDate)) { Date weekStartDate = convertToWeekStart(createSheetsCalendar.getTime()); String sheetName = sheetNameFormat.format(weekStartDate); HSSFSheet sheet = workbook.getSheet(sheetName); if (sheet == null) { if (logger.isDebugEnabled()) { logger.debug("Creating HSSFSheet named [" + sheetName + "]"); } sheet = workbook.createSheet(sheetName); sheetToNotes.put(sheetName, new ArrayList<String>()); createHeaderRows(sheet, weekStartDate, styleMap); } createSheetsCalendar.add(Calendar.DAY_OF_YEAR, -1); } }
From source file:es.udc.fic.test.model.CerrarMangaTest.java
@Test public void cerrarMangaSiTodasPosiciones() { //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 www . j a v 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); // 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)); // b4 DNC // b5 DNC //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 se han creado todas las posiciones assertEquals(6, manga1.getPosiciones().size()); assertEquals(posManga1.get(0).getPenal(), Posicion.Penalizacion.ZFP); assertEquals(posManga1.get(0).getPuntos(), 3); assertEquals(posManga1.get(1).getPenal(), Posicion.Penalizacion.SCP); assertEquals(posManga1.get(1).getPuntos(), 2); assertEquals(posManga1.get(2).getPenal(), Posicion.Penalizacion.NAN); assertEquals(posManga1.get(2).getPuntos(), 1); boolean estab4 = false; for (Posicion p : manga1.getPosiciones()) { if ((p.getBarco() == b4) && (p.getPenal() == Posicion.Penalizacion.DNC) && (p.getPuntos() == 6)) { estab4 = true; } } assertTrue(estab4); boolean estab5 = false; for (Posicion p : manga1.getPosiciones()) { if ((p.getBarco() == b5) && (p.getPenal() == Posicion.Penalizacion.DNC) && (p.getPuntos() == 6)) { estab5 = true; } } assertTrue(estab5); assertEquals(posManga1.get(3).getPenal(), Posicion.Penalizacion.ZFP); assertEquals(posManga1.get(3).getPuntos(), 1); }
From source file:com.eryansky.common.utils.SysUtils.java
public static String dateFormatTally() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, -1); return dateFormat(calendar.getTime(), "yyyyMMdd"); }
From source file:com.hangum.tadpole.manager.core.editor.executedsql.ExecutedSQLEditor.java
/** * ?? ./* w ww . jav a2 s. c o m*/ */ private void initUIData() { try { // database name combo listUserDBDAO = TadpoleSystem_UserDBQuery.getUserDB(); comboDatabase.add("All"); comboDatabase.setData("All", null); for (UserDBDAO userDBDAO : listUserDBDAO) { comboDatabase.add(userDBDAO.getDisplay_name()); comboDatabase.setData(userDBDAO.getDisplay_name(), userDBDAO); } comboDatabase.select(0); } catch (Exception e) { logger.error("get db list", e); } // Range of date 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)); }
From source file:com.eryansky.common.utils.SysUtils.java
public static String dateFormatTallyStr() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, -1); return dateFormat(calendar.getTime(), "yyyy-MM-dd"); }