List of usage examples for org.joda.time DateTime plusDays
public DateTime plusDays(int days)
From source file:net.tourbook.ui.views.calendar.CalendarGraph.java
License:Open Source License
private void drawCalendar(GC gc) { final int dayLabelXOffset = 1; final int XX = getSize().x; final int YY = getSize().y; // System.out.println(_graphClean ? "clean!" : "NOT clean!"); // System.out.println(_highlightChanged ? "HL changed!" : "HL NOT changed"); // System.out.println("-----------"); _fontHeight = gc.getFontMetrics().getHeight(); if (_graphClean && _image != null) { final GC oldGc = gc; _highlight = new Image(getDisplay(), XX, YY); gc = new GC(_highlight); gc.drawImage(_image, 0, 0);/*w w w. j a va 2s . c om*/ drawSelection(gc); if (_highlightChanged) { drawHighLight(gc); _highlightChanged = false; } gc.dispose(); oldGc.drawImage(_highlight, 0, 0); _highlight.dispose(); return; } if (_scrollDebug) { System.out.println("Drawing year: " + _dt.getYear() + " week: " + _dt.getWeekOfWeekyear()); //$NON-NLS-1$ //$NON-NLS-2$ } if (_image != null && !_image.isDisposed()) { _image.dispose(); } DateTime date = new DateTime(_dt); _image = new Image(getDisplay(), XX, YY); // update month/year dropdown box // look at the 1st day of the week after the first day displayed because if we go to // a specific month we ensure that the first day of the month is displayed in // the first line, meaning the first day in calendar normally contains a day // of the *previous* month if (_calendarYearMonthContributor.getSelectedYear() != date.plusDays(7).getYear()) { _calendarYearMonthContributor.selectYear(date.getYear()); } if (_calendarYearMonthContributor.getSelectedMonth() != date.plusDays(7).getMonthOfYear()) { _calendarYearMonthContributor.selectMonth(date.getMonthOfYear()); } final GC oldGc = gc; gc = new GC(_image); _refTextExtent = gc.stringExtent(_refText); final boolean oldLayout = _tinyLayout; _tinyLayout = (_refTextExtent.x > XX / 9); // getNumOfWeeks needs the _tinuLayout set if (oldLayout != _tinyLayout) { // the layout style changed, try to restore weeks and make selection visible if (_tinyLayout) { _dt_normal = _dt; _dt = _dt_tiny; } else { _dt_tiny = _dt; _dt = _dt_normal; } scrollBarUpdate(); if (_selectedItem.id > 0) { switch (_selectedItem.type) { case DAY: gotoDate(new DateTime(0).plusDays(_selectedItem.id.intValue())); return; case TOUR: gotoTourId(_selectedItem.id); return; } } } final int numCols = 9; // one col left and right of the week + 7 week days final int numRows = getNumOfWeeks(); // number of weeks per month displayed (make sure _tinyLayout is already defined!) final Color alternate = _colorCache.getColor(0xf0f0f0); _tourFocus = new ArrayList<ObjectLocation>(); _dayFocus = new ArrayList<ObjectLocation>(); CalendarTourData[] data; final Font normalFont = gc.getFont(); final FontData fd[] = normalFont.getFontData(); fd[0].setStyle(SWT.BOLD); final Font boldFont = new Font(_display, fd[0]); final Rectangle area = getClientArea(); gc.setBackground(_white); gc.setForeground(_black); gc.fillRectangle(area); final float dY = (float) YY / (float) numRows; float dX = (float) XX / (float) numCols; // keep the summary column at a minimal width and hide it completely if height goes blow usable value final int minSummaryWidth = _refTextExtent.x; final int minSummaryHeigth = (_refTextExtent.y * 2) / 3; int summaryWidth = 0; if (dY > minSummaryHeigth) { if (dX < minSummaryWidth) { summaryWidth = minSummaryWidth; } else { summaryWidth = (int) dX; } } final int minInfoWidth = _refTextExtent.x / 2; final int minInfoHeigth = (_refTextExtent.y / 3); int infoWidth = 0; if (dY > minInfoHeigth) { if (dX < minInfoWidth) { infoWidth = minInfoWidth; } else { infoWidth = (int) dX; } } dX = (float) (XX - summaryWidth - infoWidth) / (numCols - 2); _calendarAllDaysRectangle = new Rectangle(infoWidth, 0, (int) (7 * dX), YY); // _calendarFirstWeekRectangle = new Rectangle(infoWidth, 0, (int) (7 * dX), (int) dY); // _calendarLastWeekRectangle = new Rectangle( infoWidth, (int) ((getNumOfWeeks() - 1) * dY), (int) (7 * dX), (int) dY); // first draw the horizontal lines gc.setBackground(_white); gc.setForeground(_gray); for (int i = 0; i <= numRows; i++) { gc.drawLine(0, (int) (i * dY), XX, (int) (i * dY)); } // final Rectangle selectedRec = null; // final CalendarTourData selectedTour = null; // final boolean doSelection = false; final long todayDayId = (new Day(new DateTime())).dayId; gc.setFont(boldFont); // a rough guess about the max size of the label final Point[] headerSizes = { gc.stringExtent("22. May 99"), //$NON-NLS-1$ gc.stringExtent("22. May"), //$NON-NLS-1$ gc.stringExtent("22") }; //$NON-NLS-1$ gc.setFont(normalFont); final String[] headerFormats = { "dd. MMM yy", "dd. MMM", "dd" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String headerFormat = UI.EMPTY_STRING; // Find a format for the day header which fits into the rectangle available; int g = 0; while (g < headerSizes.length && headerSizes[g].x > (dX - dayLabelXOffset)) { g++; } g = Math.min(g, headerSizes.length - 1); // if the cell is smaller than the shortest format (no index 'g' was found) we use the shortest format and relay on clipping // if (headerSizes[g].y < dY) { // headerFormat = headerFormats[g]; // } headerFormat = headerFormats[g]; final int dayLabelWidht = headerSizes[g].x; int dayLabelHeight = headerSizes[g].y; // _tinyLayout = (refTextExtent.x > dX || refTextExtent.y > dY - dayLabelHeight) ? true : false; DateTime weekDate; long dayId = (new Day(date)).dayId; // we use simple ids // Weeks for (int i = 0; i < numRows; i++) { final int Y1 = (int) (i * dY); final int Y2 = (int) ((i + 1) * dY); // Days per week Rectangle dayRec = null; weekDate = date; // save the first day of this week as a pointer to this week if (infoWidth > 0) { final Rectangle infoRec = new Rectangle(0, Y1, infoWidth, (Y2 - Y1)); drawWeekInfo(gc, date, infoRec); } for (int j = 0; j < 7; j++) { final int X1 = infoWidth + (int) (j * dX); final int X2 = infoWidth + (int) ((j + 1) * dX); // final Rectangle dayRec = new Rectangle(X1, Y1, (X2 - X1), (Y2 - Y1)); dayRec = new Rectangle(X1, Y1, (X2 - X1), (Y2 - Y1)); final Day day = new Day(dayId); _dayFocus.add(new ObjectLocation(dayRec, dayId, day)); dayId = day.dayId + 1; final int weekDay = date.getDayOfWeek(); gc.setBackground(_white); // Day background rectangle if ((date.getMonthOfYear() % 2) == 1) { gc.setBackground(alternate); gc.fillRectangle(dayRec.x, dayRec.y + 1, dayRec.width, dayRec.height - 1); } data = _dataProvider.getCalendarDayData(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth()); // Day header box if (!_tinyLayout) { gc.setForeground(_gray); gc.fillGradientRectangle(X1, Y1, dayRec.width + 1, dayLabelHeight, true); // no clue why I've to add 1 to the width, looks like a bug on Linux and does not hurt as we overwrite with the vertial line at the end anyway // Day header label gc.setFont(boldFont); if (day.dayId == todayDayId) { gc.setForeground(_blue); } else if (weekDay == DateTimeConstants.SATURDAY || weekDay == DateTimeConstants.SUNDAY) { gc.setForeground(_red); } else { gc.setForeground(_darkGray); } gc.setClipping(X1, Y1, dayRec.width, dayLabelHeight); // this clipping should only kick in if shortest label format is still longer than the cell width gc.drawText(date.toString(headerFormat), X2 - dayLabelWidht - dayLabelXOffset, Y1, true); gc.setFont(normalFont); gc.setClipping(_nullRec); } else { dayLabelHeight = 0; } drawDayTours(gc, data, new Rectangle(dayRec.x, dayRec.y + dayLabelHeight, dayRec.width, dayRec.height - dayLabelHeight)); if (_tinyLayout && _showDayNumberInTinyView) { if (day.dayId == todayDayId) { gc.setForeground(_blue); } else if (weekDay == DateTimeConstants.SATURDAY || weekDay == DateTimeConstants.SUNDAY) { gc.setForeground(_red); } else { gc.setForeground(_darkGray); } gc.setAlpha(0x50); gc.setFont(boldFont); gc.setClipping(dayRec); gc.drawText(date.toString(headerFormat), X2 - dayLabelWidht - dayLabelXOffset, Y1, true); gc.setFont(normalFont); gc.setClipping(_nullRec); gc.setAlpha(0xFF); } date = date.plusDays(1); } if (summaryWidth > 0) { final int X1 = infoWidth + (int) (7 * dX); final int X2 = X1 + summaryWidth; final Rectangle weekRec = new Rectangle(X1, Y1, (X2 - X1), (Y2 - Y1)); final CalendarTourData weekSummary = _dataProvider.getCalendarWeekSummaryData(weekDate.getYear(), weekDate.getWeekOfWeekyear()); if (weekSummary.numTours > 0) { drawWeekSummary(gc, weekSummary, weekRec); } } } gc.setFont(normalFont); // and finally the vertical lines gc.setForeground(_display.getSystemColor(SWT.COLOR_GRAY)); for (int i = 0; i <= 7; i++) { gc.drawLine(infoWidth + (int) (i * dX), 0, infoWidth + (int) (i * dX), YY); } // draw the selection on top of our calendar graph image so we can reuse that image _highlight = new Image(getDisplay(), XX, YY); gc = new GC(_highlight); gc.drawImage(_image, 0, 0); drawSelection(gc); oldGc.drawImage(_highlight, 0, 0); _highlight.dispose(); boldFont.dispose(); oldGc.dispose(); gc.dispose(); _graphClean = true; }
From source file:net.tourbook.ui.views.calendar.CalendarGraph.java
License:Open Source License
private void drawWeekInfo(final GC gc, final DateTime dt, final Rectangle rec) { final Font normalFont = gc.getFont(); final FontData fd[] = normalFont.getFontData(); fd[0].setStyle(SWT.BOLD);/*from w w w . ja v a 2 s .co m*/ // fd[0].setHeight(((rec.height) * 72 / _display.getDPI().y) / 4); final Font boldFont = new Font(_display, fd[0]); gc.setForeground(_darkGray); gc.setBackground(_white); gc.setFont(boldFont); String text; if (_tinyLayout) { if (dt.minusDays(1).getMonthOfYear() != dt.plusDays(6).getMonthOfYear()) { // a new month started on this week gc.setClipping(new Rectangle(rec.x, rec.y, rec.width, 4 * rec.height)); // clipp to the room left of this month text = dt.plusDays(6).toString("MMM"); //$NON-NLS-1$ if (rec.width < (2 * _refTextExtent.x / 3)) { text = text.substring(0, 1); } gc.drawText(text, rec.x + 2, rec.y + 2); gc.setClipping(_nullRec); } } else { gc.drawText("" + dt.getWeekOfWeekyear(), rec.x + 4, rec.y + 2);//$NON-NLS-1$ } gc.setFont(normalFont); boldFont.dispose(); }
From source file:niche.newres.timedevents2owl.randomizer.TimedEvents2OWLRandomizer.java
public static DateTime plusRandomDays(DateTime dateTime, int minRange, int maxRange) { int randomDays = TimedEvents2OWLRandomizer.randInt(minRange, maxRange); return dateTime.plusDays(randomDays); }
From source file:nz.net.orcon.kanban.automation.actions.DateTool.java
License:Open Source License
public Date addDays(Date date, String days) { DateTime dt = new DateTime(date); DateTime plusDays = dt.plusDays(Integer.parseInt(days)); return plusDays.toDate(); }
From source file:op.tools.SYSTools.java
License:Open Source License
public static Date anonymizeDate(Date in) { Date result = in;/*w w w. j a v a 2s .c o m*/ if (OPDE.isAnonym()) { Random rnd = new Random(System.nanoTime()); DateTime dt = new DateTime(in); int factor = rnd.nextBoolean() ? -1 : 1; result = dt.plusDays(rnd.nextInt(300) * factor).plusYears(rnd.nextInt(5) * factor).toDate(); } return result; }
From source file:org.adeptnet.auth.saml.SAMLClient.java
License:Apache License
private void validate(final Response response) throws ValidationException { if (response.getStatus() == null || response.getStatus().getStatusCode() == null || !(StatusCode.SUCCESS_URI.equals(response.getStatus().getStatusCode().getValue()))) { throw new ValidationException("Response has an unsuccessful status code"); }/*ww w. j ava2s. co m*/ // response destination must match ACS if (!config.getSPConfig().getAcs().equals(response.getDestination())) { throw new ValidationException("Response is destined for a different endpoint"); } final DateTime now = DateTime.now(); // issue instant must be within a day final DateTime issueInstant = response.getIssueInstant(); if (issueInstant != null) { if (issueInstant.isBefore(now.minusDays(1).minusSeconds(slack))) { throw new ValidationException("Response IssueInstant is in the past"); } if (issueInstant.isAfter(now.plusDays(1).plusSeconds(slack))) { throw new ValidationException("Response IssueInstant is in the future"); } } for (Assertion assertion : response.getAssertions()) { // Assertion must be signed correctly if (!assertion.isSigned()) { throw new ValidationException("Assertion must be signed"); } final Signature sig2 = assertion.getSignature(); sigValidator.validate(sig2); // Assertion must contain an authnstatement // with an unexpired session if (assertion.getAuthnStatements().isEmpty()) { throw new ValidationException("Assertion should contain an AuthnStatement"); } for (AuthnStatement as : assertion.getAuthnStatements()) { if (as.getSessionNotOnOrAfter() == null) { LOG.error("SessionNotOnOrAfter is null"); continue; } final DateTime exp = as.getSessionNotOnOrAfter().plusSeconds(slack); if (exp != null && (now.isEqual(exp) || now.isAfter(exp))) { throw new ValidationException("AuthnStatement has expired"); } } if (assertion.getConditions() == null) { throw new ValidationException("Assertion should contain conditions"); } // Assertion IssueInstant must be within a day final DateTime instant = assertion.getIssueInstant(); if (instant != null) { if (instant.isBefore(now.minusDays(1).minusSeconds(slack))) { throw new ValidationException("Response IssueInstant is in the past"); } if (instant.isAfter(now.plusDays(1).plusSeconds(slack))) { throw new ValidationException("Response IssueInstant is in the future"); } } // Conditions must be met by current time final Conditions conditions = assertion.getConditions(); DateTime notBefore = conditions.getNotBefore(); DateTime notOnOrAfter = conditions.getNotOnOrAfter(); if (notBefore == null) { notBefore = now; } if (notBefore == null || notOnOrAfter == null) { throw new ValidationException("Assertion conditions must have limits"); } notBefore = notBefore.minusSeconds(slack); notOnOrAfter = notOnOrAfter.plusSeconds(slack); if (now.isBefore(notBefore)) { throw new ValidationException("Assertion conditions is in the future"); } if (now.isEqual(notOnOrAfter) || now.isAfter(notOnOrAfter)) { throw new ValidationException("Assertion conditions is in the past"); } // If subjectConfirmationData is included, it must // have a recipient that matches ACS, with a valid // NotOnOrAfter final Subject subject = assertion.getSubject(); if (subject != null && !subject.getSubjectConfirmations().isEmpty()) { boolean foundRecipient = false; for (SubjectConfirmation sc : subject.getSubjectConfirmations()) { if (sc.getSubjectConfirmationData() == null) { continue; } final SubjectConfirmationData scd = sc.getSubjectConfirmationData(); if (scd.getNotOnOrAfter() != null) { final DateTime chkdate = scd.getNotOnOrAfter().plusSeconds(slack); if (now.isEqual(chkdate) || now.isAfter(chkdate)) { throw new ValidationException("SubjectConfirmationData is in the past"); } } if (config.getSPConfig().getAcs().equals(scd.getRecipient())) { foundRecipient = true; } } if (!foundRecipient) { throw new ValidationException("No SubjectConfirmationData found for ACS"); } } // audience must include intended SP issuer if (conditions.getAudienceRestrictions().isEmpty()) { throw new ValidationException("Assertion conditions must have audience restrictions"); } // only one audience restriction supported: we can only // check against the single SP. if (conditions.getAudienceRestrictions().size() > 1) { throw new ValidationException("Assertion contains multiple audience restrictions"); } final AudienceRestriction ar = conditions.getAudienceRestrictions().get(0); // at least one of the audiences must match our SP boolean foundSP = false; for (Audience a : ar.getAudiences()) { if (config.getSPConfig().getEntityId().equals(a.getAudienceURI())) { foundSP = true; } } if (!foundSP) { throw new ValidationException("Assertion audience does not include issuer"); } } }
From source file:org.anyframe.iam.core.intercept.web.ReloadableRestrictedTimesFilterInvocationSecurityMetadataSource.java
License:Apache License
/** * Get the String Array of Days between startDate and endDate. * @param startDate/* w w w.jav a 2s. c o m*/ * @param endDate * @return String Array. The Days between startDate and endDate. */ public String[] getBetweenDays(String startDate, String endDate) { List betweenDays = new ArrayList(); DateTime tempDate = DateTimeFormat.forPattern("yyyyMMdd").parseDateTime(startDate); DateTime endJodaDate = DateTimeFormat.forPattern("yyyyMMdd").parseDateTime(endDate); betweenDays.add(DateTimeFormat.forPattern("yyyyMMdd").print(tempDate)); while (tempDate.isBefore(endJodaDate.getMillis())) { tempDate = tempDate.plusDays(1); betweenDays.add(DateTimeFormat.forPattern("yyyyMMdd").print(tempDate)); } return (String[]) betweenDays.toArray(new String[0]); }
From source file:org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.date.BeamSqlDatetimePlusExpression.java
License:Apache License
private DateTime addInterval(DateTime dateTime, SqlTypeName intervalType, int numberOfIntervals) { switch (intervalType) { case INTERVAL_SECOND: return dateTime.plusSeconds(numberOfIntervals); case INTERVAL_MINUTE: return dateTime.plusMinutes(numberOfIntervals); case INTERVAL_HOUR: return dateTime.plusHours(numberOfIntervals); case INTERVAL_DAY: return dateTime.plusDays(numberOfIntervals); case INTERVAL_MONTH: return dateTime.plusMonths(numberOfIntervals); case INTERVAL_YEAR: return dateTime.plusYears(numberOfIntervals); default:/*from w w w.ja v a2s . c om*/ throw new IllegalArgumentException("Adding " + intervalType.getName() + " to date is not supported"); } }
From source file:org.apache.cloudstack.utils.security.CertUtils.java
License:Apache License
public static X509Certificate generateV3Certificate(final X509Certificate caCert, final KeyPair caKeyPair, final PublicKey clientPublicKey, final String subject, final String signatureAlgorithm, final int validityDays, final List<String> dnsNames, final List<String> publicIPAddresses) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, InvalidKeyException, SignatureException, OperatorCreationException { final DateTime now = DateTime.now(DateTimeZone.UTC); final BigInteger serial = generateRandomBigInt(); final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); final X509v3CertificateBuilder certBuilder; if (caCert == null) { // Generate CA certificate certBuilder = new JcaX509v3CertificateBuilder(new X500Name(subject), serial, now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Name(subject), clientPublicKey);/*from w w w. j a va 2s .c o m*/ certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); } else { // Generate client certificate certBuilder = new JcaX509v3CertificateBuilder(caCert, serial, now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Principal(subject), clientPublicKey); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert)); } certBuilder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(clientPublicKey)); final List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>(); if (publicIPAddresses != null) { for (final String publicIPAddress : publicIPAddresses) { if (Strings.isNullOrEmpty(publicIPAddress)) { continue; } subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, publicIPAddress)); } } if (dnsNames != null) { for (final String dnsName : dnsNames) { if (Strings.isNullOrEmpty(dnsName)) { continue; } subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, dnsName)); } } if (subjectAlternativeNames.size() > 0) { final GeneralNames subjectAltNames = GeneralNames .getInstance(new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[] {}))); certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); } final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC") .build(caKeyPair.getPrivate()); final X509CertificateHolder certHolder = certBuilder.build(signer); final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder); if (caCert != null) { cert.verify(caCert.getPublicKey()); } else { cert.verify(caKeyPair.getPublic()); } return cert; }
From source file:org.apache.falcon.execution.SchedulerUtil.java
License:Apache License
/** * Returns the frequency in millis from the given time. * Needs to take the calender into account. * @param referenceTime/*from w ww. j ava 2 s . c o m*/ * @param frequency * @return */ public static long getFrequencyInMillis(DateTime referenceTime, Frequency frequency) { switch (frequency.getTimeUnit()) { case minutes: return MINUTE_IN_MS * frequency.getFrequencyAsInt(); case hours: return HOUR_IN_MS * frequency.getFrequencyAsInt(); case days: return referenceTime.plusDays(frequency.getFrequencyAsInt()).getMillis() - referenceTime.getMillis(); case months: return referenceTime.plusMonths(frequency.getFrequencyAsInt()).getMillis() - referenceTime.getMillis(); default: throw new IllegalArgumentException("Invalid time unit " + frequency.getTimeUnit().name()); } }