List of usage examples for org.joda.time DateTime minusWeeks
public DateTime minusWeeks(int weeks)
From source file:app.action.generate.ProjectsAction.java
public String index() throws Exception { fairy = Fairy.create();/*w w w. j ava 2s . c o m*/ // ** GENERATE PROJECTS ** // List<Lecturer> lecturers = DB.getInstance().createNamedQuery("Lecturer.findAll").getResultList(); List<Student> students = DB.getInstance().createNamedQuery("Student.findAll").getResultList(); List<Specialization> specs = DB.getInstance().createNamedQuery("Specialization.findAll").getResultList(); for (int i = 0; i < 50; i++) { Project p = new Project(); p.setLecturerId(lecturers.get(ThreadLocalRandom.current().nextInt(0, lecturers.size()))); p.setSpecId(specs.get(ThreadLocalRandom.current().nextInt(0, specs.size()))); p.setProjectTitle(fairy.textProducer().sentence()); StringBuilder content = new StringBuilder(); int randPara = ThreadLocalRandom.current().nextInt(2, 6); for (int j = 0; j < randPara; j++) { content.append(fairy.textProducer().paragraph() + "\n\n"); } p.setProjectDescription(content.toString()); DateTime duedate = fairy.dateProducer().randomDateBetweenTwoDates(DateTime.now().minusWeeks(1), DateTime.now().plusWeeks(5)); p.setDueDate(duedate.toDate()); p.setStartDate(fairy.dateProducer() .randomDateBetweenTwoDates(DateTime.now().minusWeeks(6), DateTime.now().minusWeeks(1)) .toDate()); if (duedate.isAfterNow()) { String status = PROJECT_STATUS[ThreadLocalRandom.current().nextInt(2, 5)]; DateTime subDate = fairy.dateProducer().randomDateBetweenTwoDates(duedate.minusWeeks(1), duedate.toDateTime()); if (status.equals("EVALUATED")) { p.setStudentId(students.get(ThreadLocalRandom.current().nextInt(0, students.size()))); p.setEvaComment(fairy.textProducer().latinSentence()); p.setProjectGrade(PROJECT_GRADE[ThreadLocalRandom.current().nextInt(0, PROJECT_GRADE.length)]); p.setSubDate(subDate.toDate()); } else if (status.equals("SUBMITTED")) { p.setStudentId(students.get(ThreadLocalRandom.current().nextInt(0, students.size()))); p.setSubDate(subDate.toDate()); } } else { String status = PROJECT_STATUS[ThreadLocalRandom.current().nextInt(0, 2)]; if (status.equals("ASSIGNED")) { p.setStudentId(students.get(ThreadLocalRandom.current().nextInt(0, students.size()))); } } // roughly 10% chance a project is inactive: if (ThreadLocalRandom.current().nextInt(1, 11) == 5) { p.setProjectActive(false); } DB.getInstance().persist(p); } return SUCCESS; }
From source file:com.ehdev.chronos.lib.types.holders.PayPeriodHolder.java
License:Open Source License
/** * Will do the calculations for the start and end of the process *///from w w w .j a va2s. co m public void generate() { //Get the start and end of pay period DateTime startOfPP = gJob.getStartOfPayPeriod(); gDuration = gJob.getDuration(); DateTime endOfPP = DateTime.now(); //Today long duration = endOfPP.getMillis() - startOfPP.getMillis(); DateTimeZone startZone = startOfPP.getZone(); DateTimeZone endZone = endOfPP.getZone(); long offset = endZone.getOffset(endOfPP) - startZone.getOffset(startOfPP); int weeks = (int) ((duration + offset) / 1000 / 60 / 60 / 24 / 7); /* System.out.println("end of pp: " + endOfPP); System.out.println("start of pp: " + startOfPP); System.out.println("dur: " + duration); System.out.println("weeks diff: " + weeks); */ switch (gDuration) { case ONE_WEEK: //weeks = weeks; startOfPP = startOfPP.plusWeeks(weeks); endOfPP = startOfPP.plusWeeks(1); break; case TWO_WEEKS: weeks = weeks / 2; startOfPP = startOfPP.plusWeeks(weeks * 2); endOfPP = startOfPP.plusWeeks(2); break; case THREE_WEEKS: weeks = weeks / 3; startOfPP = startOfPP.plusWeeks(weeks * 3); endOfPP = startOfPP.plusWeeks(3); break; case FOUR_WEEKS: weeks = weeks / 4; startOfPP = startOfPP.plusWeeks(weeks * 4); endOfPP = startOfPP.plusWeeks(4); break; case FULL_MONTH: //in this case, endOfPP is equal to now startOfPP = DateMidnight.now().toDateTime().withDayOfMonth(1); endOfPP = startOfPP.plusMonths(1); break; case FIRST_FIFTEENTH: DateTime now = DateTime.now(); if (now.getDayOfMonth() >= 15) { startOfPP = now.withDayOfMonth(15); endOfPP = startOfPP.plusDays(20).withDayOfMonth(1); } else { startOfPP = now.withDayOfMonth(1); endOfPP = now.withDayOfMonth(15); } break; default: break; } if (startOfPP.isAfter(DateTime.now())) { startOfPP = startOfPP.minusWeeks(getDays() / 7); endOfPP = endOfPP.minusWeeks(getDays() / 7); } gStartOfPP = startOfPP; gEndOfPP = endOfPP; }
From source file:com.google.api.ads.adwords.awreporting.model.entities.dateranges.LastWeekDateRangeHandler.java
License:Open Source License
@Override public DateTime retrieveDateStart(DateTime date) { return date.minusWeeks(1).minusDays(date.getDayOfWeek() - 1); }
From source file:com.google.api.ads.adwords.awreporting.model.entities.dateranges.LastWeekDateRangeHandler.java
License:Open Source License
@Override public DateTime retrieveDateEnd(DateTime date) { return date.minusWeeks(1).plusDays(7 - date.getDayOfWeek()); }
From source file:com.google.sampling.experiential.server.DSQueryBuilder.java
License:Open Source License
private static Interval getXWeeksAgo(int weeksAgo, DateTimeZone clientTimeZone) { DateTime lastMondayAfter = getMondayAfterWeekEnclosing(getDayLastWeek(clientTimeZone)); DateTime xMondaysAfterAgo = lastMondayAfter.minusWeeks(weeksAgo); DateTime xMondaysAgo = xMondaysAfterAgo.minusWeeks(1); return new Interval(xMondaysAgo, lastMondayAfter); }
From source file:com.marand.thinkmed.medications.dao.openehr.MedicationsOpenEhrDao.java
License:Open Source License
public Map<String, MedicationOrderComposition> getLatestCompositionsForOriginalCompositionUids( final Set<String> originalCompositionUids, final Set<String> patientIds, final int searchIntervalInWeeks, final DateTime when) { final Map<String, MedicationOrderComposition> originalUidWithLatestCompositionMap = new HashMap<>(); if (originalCompositionUids.isEmpty() || patientIds.isEmpty()) { return originalUidWithLatestCompositionMap; }/* ww w . ja va 2s . c om*/ final Map<String, String> ehrIdsMap = getEhrIds(patientIds); final Set<String> ehrIds = new HashSet<>(ehrIdsMap.values()); final StringBuilder sb = new StringBuilder(); sb.append("SELECT c/uid/value, i/links/target/value, i/links/type/value, c FROM EHR e") .append(" CONTAINS Composition c[openEHR-EHR-COMPOSITION.encounter.v1]") .append(" CONTAINS Instruction i[openEHR-EHR-INSTRUCTION.medication.v1]") .append(" WHERE c/name/value = 'Medication order'"); appendMedicationTimingIntervalCriterion(sb, Intervals.infiniteFrom(when.minusWeeks(searchIntervalInWeeks).withTimeAtStartOfDay())); //TODO NEJC change to correct time - to load correct therapies sb.append(" AND e/ehr_id/value matches {" + getAqlQuoted(ehrIds) + '}') .append(" ORDER BY c/context/start_time DESC"); query(sb.toString(), (ResultRowProcessor<Object[], Void>) (resultRow, hasNext) -> { final String compositionId = (String) resultRow[0]; final String linkTarget = (String) resultRow[1]; final String linkType = (String) resultRow[2]; final RmObject orderCompositionObject = (RmObject) resultRow[3]; final String compositionUidWithoutVersion = TherapyIdUtils .getCompositionUidWithoutVersion(compositionId); if (originalCompositionUids.contains(compositionUidWithoutVersion) && !originalUidWithLatestCompositionMap.containsKey(compositionUidWithoutVersion)) { originalUidWithLatestCompositionMap.put(compositionUidWithoutVersion, RmoToTdoConverter.convert(MedicationOrderComposition.class, orderCompositionObject)); } else if (linkTarget != null && linkType.equals(EhrLinkType.ORIGIN.getName())) { final OpenEhrRefUtils.EhrUriComponents ehrUri = OpenEhrRefUtils.parseEhrUri(linkTarget); final String linkedCompositionUidWithoutVersion = TherapyIdUtils .getCompositionUidWithoutVersion(ehrUri.getCompositionId()); if (originalCompositionUids.contains(linkedCompositionUidWithoutVersion) && !originalUidWithLatestCompositionMap.containsKey(linkedCompositionUidWithoutVersion)) { originalUidWithLatestCompositionMap.put(linkedCompositionUidWithoutVersion, RmoToTdoConverter.convert(MedicationOrderComposition.class, orderCompositionObject)); } } return null; }); return originalUidWithLatestCompositionMap; }
From source file:com.marc.lastweek.web.components.recommendedclassifiedads.RecommendedClassifiedAdsListPanel.java
License:Open Source License
private void initializeFilterDate() { DateTime now = new DateTime(Calendar.getInstance()); this.date = DateUtils.truncate(now.minusWeeks(1).toCalendar(getLocale()), Calendar.DAY_OF_MONTH); }
From source file:com.marc.lastweek.web.pages.classifiedadslisting.FilterResultsPage.java
License:Open Source License
private boolean filterParametersHasResults(FilterParameters filterParameters) { DateTime now = new DateTime(Calendar.getInstance()); Calendar date = DateUtils.truncate(now.minusWeeks(1).toCalendar(getLocale()), Calendar.DAY_OF_MONTH); return !LastweekApplication.get().getClassifiedAdsService() .findClassifiedAdsByFilterParameters(filterParameters, 0, 15, date).isEmpty(); }
From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java
License:Apache License
private File createImage(ApplicationGroup appgroup) throws IOException { Map<String, Double> costs = Maps.newHashMap(); DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0); Interval interval = new Interval(end.minusWeeks(numWeeks), end); for (Product product : products) { List<ResourceGroup> resourceGroups = getResourceGroups(appgroup, product); if (resourceGroups.size() == 0) { continue; }// w w w.j a va2 s.c om DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly); if (dataManager == null) { continue; } TagLists tagLists = new TagLists(accounts, regions, null, Lists.newArrayList(product), null, null, resourceGroups); Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Product, AggregateType.none, false); for (Tag tag : data.keySet()) { for (int week = 0; week < numWeeks; week++) { String key = tag + "|" + week; if (costs.containsKey(key)) costs.put(key, data.get(tag)[week] + costs.get(key)); else costs.put(key, data.get(tag)[week]); } } } boolean hasData = false; for (Map.Entry<String, Double> entry : costs.entrySet()) { if (!entry.getKey().contains("monitor") && entry.getValue() != null && entry.getValue() >= 0.1) { hasData = true; break; } } if (!hasData) return null; DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (Product product : products) { for (int week = 0; week < numWeeks; week++) { String weekStr = String.format("%s - %s week", formatter.print(end.minusWeeks(numWeeks - week)).substring(5), formatter.print(end.minusWeeks(numWeeks - week - 1)).substring(5)); dataset.addValue(costs.get(product + "|" + week), product.name, weekStr); } } JFreeChart chart = ChartFactory.createBarChart3D(appgroup.getDisplayName() + " Weekly AWS Costs", "", "Costs", dataset, PlotOrientation.VERTICAL, true, false, false); CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); BarRenderer3D renderer = (BarRenderer3D) categoryplot.getRenderer(); renderer.setItemLabelAnchorOffset(10.0); TextTitle title = chart.getTitle(); title.setFont(title.getFont().deriveFont((title.getFont().getSize() - 3))); renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator() { public java.lang.String generateLabel(org.jfree.data.category.CategoryDataset dataset, int row, int column) { return costFormatter.format(dataset.getValue(row, column)); } }); renderer.setBaseItemLabelsVisible(true); renderer.setBasePositiveItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER)); NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis(); numberaxis.setNumberFormatOverride(costFormatter); BufferedImage image = chart.createBufferedImage(1200, 400); File outputfile = File.createTempFile("awscost", "png"); ImageIO.write(image, "png", outputfile); return outputfile; }
From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java
License:Apache License
private MimeBodyPart constructEmail(int index, ApplicationGroup appGroup, StringBuilder body) throws IOException, MessagingException { if (index == 0 && !StringUtils.isEmpty(headerNote)) body.append(headerNote);//w w w . j a v a2s.co m numberFormatter.setMaximumFractionDigits(1); numberFormatter.setMinimumFractionDigits(1); File file = createImage(appGroup); if (file == null) return null; DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0); String link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks), end); body.append(String.format("<b><h4><a href='%s'>%s</a> Weekly Costs:</h4></b>", link, appGroup.getDisplayName())); body.append("<table style=\"border: 1px solid #DDD; border-collapse: collapse\">"); body.append( "<tr style=\"background-color: whiteSmoke;text-align:center\" ><td style=\"border-left: 1px solid #DDD;\"></td>"); for (int i = 0; i <= accounts.size(); i++) { int cols = i == accounts.size() ? 1 : regions.size(); String accName = i == accounts.size() ? "total" : accounts.get(i).name; body.append(String.format( "<td style=\"border-left: 1px solid #DDD;font-weight: bold;padding: 4px\" colspan='%d'>", cols)) .append(accName).append("</td>"); } body.append("</tr>"); body.append("<tr style=\"background-color: whiteSmoke;text-align:center\" ><td></td>"); for (int i = 0; i < accounts.size(); i++) { boolean first = true; for (Region region : regions) { body.append("<td style=\"font-weight: bold;padding: 4px;" + (first ? "border-left: 1px solid #DDD;" : "") + "\">").append(region.name) .append("</td>"); first = false; } } body.append("<td style=\"border-left: 1px solid #DDD;\"></td></tr>"); Map<String, Double> costs = Maps.newHashMap(); Interval interval = new Interval(end.minusWeeks(numWeeks), end); double[] total = new double[numWeeks]; for (Product product : products) { List<ResourceGroup> resourceGroups = getResourceGroups(appGroup, product); if (resourceGroups.size() == 0) { continue; } DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly); if (dataManager == null) { continue; } for (int i = 0; i < accounts.size(); i++) { List<Account> accountList = Lists.newArrayList(accounts.get(i)); TagLists tagLists = new TagLists(accountList, regions, null, Lists.newArrayList(product), null, null, resourceGroups); Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Region, AggregateType.none, false); for (Tag tag : data.keySet()) { for (int week = 0; week < numWeeks; week++) { String key = accounts.get(i) + "|" + tag + "|" + week; if (costs.containsKey(key)) costs.put(key, data.get(tag)[week] + costs.get(key)); else costs.put(key, data.get(tag)[week]); total[week] += data.get(tag)[week]; } } } } boolean firstLine = true; DateTime currentWeekEnd = end; for (int week = numWeeks - 1; week >= 0; week--) { String weekStr; if (week == numWeeks - 1) weekStr = "Last week"; else weekStr = (numWeeks - week - 1) + " weeks ago"; String background = week % 2 == 1 ? "background: whiteSmoke;" : ""; body.append(String.format( "<tr style=\"%s\"><td nowrap style=\"border-left: 1px solid #DDD;padding: 4px\">%s (%s - %s)</td>", background, weekStr, formatter.print(currentWeekEnd.minusWeeks(1)).substring(5), formatter.print(currentWeekEnd).substring(5))); for (int i = 0; i < accounts.size(); i++) { Account account = accounts.get(i); for (int j = 0; j < regions.size(); j++) { Region region = regions.get(j); String key = account + "|" + region + "|" + week; double cost = costs.get(key) == null ? 0 : costs.get(key); Double lastCost = week == 0 ? null : costs.get(account + "|" + region + "|" + (week - 1)); link = getLink("column", ConsolidateType.daily, appGroup, Lists.newArrayList(account), Lists.newArrayList(region), currentWeekEnd.minusWeeks(1), currentWeekEnd); body.append(getValueCell(cost, lastCost, link, firstLine)); } } link = getLink("column", ConsolidateType.daily, appGroup, accounts, regions, currentWeekEnd.minusWeeks(1), currentWeekEnd); body.append(getValueCell(total[week], week == 0 ? null : total[week - 1], link, firstLine)); body.append("</tr>"); firstLine = false; currentWeekEnd = currentWeekEnd.minusWeeks(1); } body.append("</table>"); numberFormatter.setMaximumFractionDigits(0); numberFormatter.setMinimumFractionDigits(0); if (!StringUtils.isEmpty(throughputMetrics)) body.append(throughputMetrics); body.append("<br><img src=\"cid:image_cid_" + index + "\"><br>"); for (Map.Entry<String, List<String>> entry : appGroup.data.entrySet()) { String product = entry.getKey(); List<String> selected = entry.getValue(); if (selected == null || selected.size() == 0) continue; link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks), end); body.append(String.format("<b><h4>%s in <a href='%s'>%s</a>:</h4></b>", getResourceGroupsDisplayName(product), link, appGroup.getDisplayName())); for (String name : selected) body.append(" ").append(name).append("<br>"); } body.append("<hr><br>"); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setFileName(file.getName()); DataSource ds = new ByteArrayDataSource(new FileInputStream(file), "image/png"); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setHeader("Content-ID", "<image_cid_" + index + ">"); mimeBodyPart.setHeader("Content-Disposition", "inline"); mimeBodyPart.setDisposition(MimeBodyPart.INLINE); file.delete(); return mimeBodyPart; }