List of usage examples for org.joda.time DateTime plus
public DateTime plus(ReadablePeriod period)
From source file:com.thinkbiganalytics.metadata.sla.api.core.FeedOnTimeArrivalMetricAssessor.java
License:Apache License
@Override @SuppressWarnings("unchecked") public void assess(FeedOnTimeArrivalMetric metric, MetricAssessmentBuilder builder) { LOG.debug("Assessing metric: ", metric); builder.metric(metric);//from w ww. ja va 2 s .co m String feedName = metric.getFeedName(); DateTime lastFeedTime = feedProvider.getLastActiveTimeStamp(feedName); HashMap<String, String> data = new HashMap<>(); data.put("feed", feedName); Long nowDiff = 0L; Period nowDiffPeriod = new Period(nowDiff.longValue()); if (lastFeedTime != null) { nowDiff = DateTime.now().getMillis() - lastFeedTime.getMillis(); nowDiffPeriod = new Period(nowDiff.longValue()); } Long latePeriodMillis = metric.getLatePeriod().toStandardDuration().getMillis(); Long duration = CronExpressionUtil.getCronInterval(metric.getExpectedExpression()); Period acceptedPeriod = new Period(duration + latePeriodMillis); Date expectedDate = CronExpressionUtil.getPreviousFireTime(metric.getExpectedExpression()); DateTime expectedTime = new DateTime(expectedDate); LOG.debug("Calculated the Expected Date to be {} ", expectedTime); DateTime lateTime = expectedTime.plus(metric.getLatePeriod()); LOG.debug("CurrentTime is: {}. Comparing {} against the lateTime of {} ", DateTime.now(), lastFeedTime, lateTime); builder.compareWith(expectedDate, feedName); data.put("expectedTime", expectedTime.toString()); data.put("expectedTimeMillis", expectedTime.getMillis() + ""); data.put("lateTime", expectedTime.toString()); data.put("lateTimeMillis", expectedTime.getMillis() + ""); if (lastFeedTime != null) { data.put("lastFeedTime", lastFeedTime.toString()); data.put("lastFeedTimeMillis", lastFeedTime.getMillis() + ""); } builder.data(data); if (lastFeedTime == null) { LOG.debug("Feed with the specified name {} not found", feedName); builder.message("Feed with the specified name " + feedName + " not found ") .result(AssessmentResult.WARNING); } else if (lastFeedTime.isAfter(expectedTime) && lastFeedTime.isBefore(lateTime)) { LOG.debug("Data for feed {} arrived on {}, which was before late time: {}", feedName, lastFeedTime, lateTime); builder.message("Data for feed " + feedName + " arrived on " + lastFeedTime + ", which was before late time: " + lateTime).result(AssessmentResult.SUCCESS); } else if (lastFeedTime.isAfter(lateTime)) { LOG.debug("Data for feed {} has not arrived before the late time: {} ", feedName, lateTime); builder.message("Data for feed " + feedName + " has not arrived before the late time: " + lateTime + "\n The last successful feed was on " + lastFeedTime).result(AssessmentResult.FAILURE); } else if (nowDiff <= (duration + latePeriodMillis)) { LOG.debug( "Data for feed {} has arrived before the late time: {}. The last successful feed was on {}. It has been {} since data has arrived. The allowed duration is {} ", feedName, lateTime, lastFeedTime, DateTimeUtil.formatPeriod(nowDiffPeriod), DateTimeUtil.formatPeriod(acceptedPeriod)); builder.message( "Data for feed " + feedName + " has arrived on time. \n The last successful feed was on " + lastFeedTime + ". It has been " + DateTimeUtil.formatPeriod(nowDiffPeriod) + " since data has arrived. The allowed duration is " + DateTimeUtil.formatPeriod(acceptedPeriod)) .result(AssessmentResult.SUCCESS); } else if (nowDiff > (duration + latePeriodMillis)) { //error its been greater that the duration of the cron + lateTime LOG.debug( "Data for feed {} has not arrived before the late time: {}. The last successful feed was on {}. It has been {} since data has arrived. The allowed duration is {} ", feedName, lateTime, lastFeedTime, DateTimeUtil.formatPeriod(nowDiffPeriod), DateTimeUtil.formatPeriod(acceptedPeriod)); builder.message( "Data for feed " + feedName + " has not arrived on time. \n The last successful feed was on " + lastFeedTime + ". It has been " + DateTimeUtil.formatPeriod(nowDiffPeriod) + " since data has arrived. The allowed duration is " + DateTimeUtil.formatPeriod(acceptedPeriod)) .result(AssessmentResult.FAILURE); } else if (DateTime.now().isBefore(lateTime)) { //&& lastFeedTime.isBefore(expectedTime) LOG.debug("CurrentTime {} is before the lateTime of {}. Not Assessing", DateTime.now(), lateTime); return; } else { LOG.debug("Data for feed {} has not arrived before the late time: {} ", feedName, lateTime); builder.message("Data for feed " + feedName + " has not arrived before the late time: " + lateTime + "\n The last successful feed was on " + lastFeedTime).result(AssessmentResult.FAILURE); } }
From source file:com.tkmtwo.timex.source.DurationDateTimeSource.java
License:Apache License
public DateTime getDateTime(DateTime dt) { checkNotNull(dt, "Need a DateTime."); return dt.plus(getDuration()); }
From source file:com.tmathmeyer.sentinel.ui.views.day.collisiondetection.DayItem.java
License:Open Source License
public void updateTime(DateTime t) { if (!this.displayable.getStart().equals(t)) { if (puppet != null) puppet.updateTime(t);/*from w w w . j a va 2 s. c o m*/ this.displayable.setStart(t); if (this.displayable instanceof Event) ((Event) this.displayable).setEnd(t.plus(this.length.toDuration())); putTimeOn(); } }
From source file:com.tomtom.speedtools.metrics.MetricsCollector.java
License:Apache License
/** * Adds a value to the collector. Use this method instead of {@link #addValueNow(float)} when now is determined by the * caller and should be aligned with other now-related functionality. Note that now should denote the current time * and cannot be an arbitrary time in the past or the future. * * @param value Value to add.// w w w . j a v a2 s. c o m * @param now Current time, as determined by the caller. */ public synchronized void addValue(final float value, @Nonnull final DateTime now) { assert now != null; // Prune old slots. prune(now); // Add the initial slot? if (values.isEmpty()) { values.add(new MetricsTimeSlot(now, value, value * value, value, value, 1)); } else { // Add to new or existing slot. DateTime slotTime = values.getLast().startTime; DateTime slotEndTime = slotTime.plus(timeSlotDuration); // Skip values that are too old for last slot. if (now.isBefore(slotTime)) { //noinspection AccessToStaticFieldLockedOnInstance LOG.debug("Dropped metric data: {} at {}", value, now); return; } // Append new time slots until now is reached. while (slotEndTime.isBefore(now)) { values.add(new MetricsTimeSlot(slotEndTime, 0, 0, 0, 0, 0)); slotTime = slotEndTime; slotEndTime = slotTime.plus(timeSlotDuration); } final MetricsTimeSlot slot = values.removeLast(); values.addLast(slot.addValue(value)); } this.sum += value; this.sumSquares += value * value; this.count += 1; }
From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java
License:Apache License
private void completeUserLogin(HttpServletRequest request, HttpServletResponse response, String code, String clientID, String clientSecret, UrlHolder holder, AuthInfo authData) throws ServletException, IOException, MalformedURLException { String lastMileToken = null;/* w ww . j a va 2 s .c o m*/ try { lastMileToken = this.inflate(code); lastMileToken = new String( org.bouncycastle.util.encoders.Base64.encode(lastMileToken.getBytes("UTF-8"))); } catch (Exception e) { throw new ServletException("Could not inflate code", e); } OpenIDConnectTrust trust = this.trusts.get(clientID); if (!trust.isPublicEndpoint()) { if (!clientSecret.equals(trust.getClientSecret())) { AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE"); response.sendError(403); return; } } ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ); SecretKey codeKey = cfg.getSecretKey(trust.getCodeLastmileKeyName()); com.tremolosecurity.lastmile.LastMile lmreq = new com.tremolosecurity.lastmile.LastMile(); try { lmreq.loadLastMielToken(lastMileToken, codeKey); } catch (Exception e) { logger.warn("Could not decrypt code token", e); response.sendError(403); AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE"); return; } if (!lmreq.isValid()) { response.sendError(403); logger.warn("Could not validate code token"); AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE"); return; } Attribute dn = null; Attribute scopes = null; String nonce = null; for (Attribute attr : lmreq.getAttributes()) { if (attr.getName().equalsIgnoreCase("dn")) { dn = attr; } else if (attr.getName().equalsIgnoreCase("scope")) { scopes = attr; } else if (attr.getName().equalsIgnoreCase("nonce")) { nonce = attr.getValues().get(0); } } ConfigManager cfgMgr = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ); DateTime now = new DateTime(); DateTime notBefore = now.minus(trust.getCodeTokenTimeToLive()); DateTime notAfter = now.plus(trust.getCodeTokenTimeToLive()); int authLevel = lmreq.getLoginLevel(); String authMethod = lmreq.getAuthChain(); try { lmreq = new com.tremolosecurity.lastmile.LastMile(request.getRequestURI(), notBefore, notAfter, authLevel, authMethod); } catch (URISyntaxException e) { throw new ServletException("Could not request access token", e); } /* lmreq.getAttributes().add(new Attribute("dn",dn.getValues().get(0))); SecretKey key = cfgMgr.getSecretKey(trust.getAccessLastmileKeyName()); String accessToken = null; try { accessToken = lmreq.generateLastMileToken(key); } catch (Exception e) { throw new ServletException("Could not generate access token",e); }*/ String accessToken = null; try { accessToken = this .produceJWT(this.generateClaims(dn.getValues().get(0), cfgMgr, new URL(request.getRequestURL().toString()), trust, nonce), cfgMgr) .getCompactSerialization(); } catch (JoseException | LDAPException | ProvisioningException e1) { throw new ServletException("Could not generate jwt", e1); } OpenIDConnectAccessToken access = new OpenIDConnectAccessToken(); access.setAccess_token(accessToken); access.setExpires_in((int) (trust.getAccessTokenTimeToLive() / 1000)); try { access.setId_token(this .produceJWT(this.generateClaims(dn.getValues().get(0), cfgMgr, new URL(request.getRequestURL().toString()), trust, nonce), cfgMgr) .getCompactSerialization()); } catch (Exception e) { throw new ServletException("Could not generate JWT", e); } access.setToken_type("Bearer"); OIDCSession oidcSession = null; try { oidcSession = this.storeSession(access, holder.getApp(), trust.getCodeLastmileKeyName(), request, dn.getValues().get(0), clientID); } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { throw new ServletException("Could not store session", e); } access.setRefresh_token(oidcSession.getEncryptedRefreshToken()); Gson gson = new Gson(); String json = gson.toJson(access); response.setContentType("text/json"); response.getOutputStream().write(json.getBytes("UTF-8")); response.getOutputStream().flush(); if (logger.isDebugEnabled()) { logger.debug("Token JSON : '" + json + "'"); } AuthInfo remUser = new AuthInfo(); remUser.setUserDN(dn.getValues().get(0)); AccessLog.log(AccessEvent.AzSuccess, holder.getApp(), (HttpServletRequest) request, remUser, "NONE"); }
From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java
License:Apache License
private void postResponse(OpenIDConnectTransaction transaction, HttpServletRequest request, HttpServletResponse response, AuthInfo authInfo, UrlHolder holder) throws Exception { //first generate a lastmile token OpenIDConnectTrust trust = trusts.get(transaction.getClientID()); ConfigManager cfgMgr = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ); DateTime now = new DateTime(); DateTime notBefore = now.minus(trust.getCodeTokenTimeToLive()); DateTime notAfter = now.plus(trust.getCodeTokenTimeToLive()); com.tremolosecurity.lastmile.LastMile lmreq = new com.tremolosecurity.lastmile.LastMile( request.getRequestURI(), notBefore, notAfter, authInfo.getAuthLevel(), authInfo.getAuthMethod()); lmreq.getAttributes().add(new Attribute("dn", authInfo.getUserDN())); Attribute attr = new Attribute("scope"); attr.getValues().addAll(transaction.getScope()); lmreq.getAttributes().add(attr);//from w w w .ja v a 2s .co m if (transaction.getNonce() != null) { lmreq.getAttributes().add(new Attribute("nonce", transaction.getNonce())); } SecretKey key = cfgMgr.getSecretKey(trust.getCodeLastmileKeyName()); String codeToken = lmreq.generateLastMileToken(key); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream compressor = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION, true)); compressor.write(org.bouncycastle.util.encoders.Base64.decode(codeToken.getBytes("UTF-8"))); compressor.flush(); compressor.close(); String b64 = new String(org.bouncycastle.util.encoders.Base64.encode(baos.toByteArray())); StringBuffer b = new StringBuffer(); b.append(transaction.getRedirectURI()).append("?").append("code=").append(URLEncoder.encode(b64, "UTF-8")) .append("&state=").append(URLEncoder.encode(transaction.getState(), "UTF-8")); response.sendRedirect(b.toString()); }
From source file:com.tremolosecurity.proxy.util.LastMileUtil.java
License:Apache License
public static void addLastMile(ConfigManager cfg, String username, String userNameAttr, HttpRequestBase req, String keyAlias, boolean addHeader) throws Exception { if (!addHeader) { return;/*from ww w . j a va2 s.c o m*/ } String uri = req.getURI().getPath(); DateTime now = new DateTime(); DateTime notBefore = now.minus(5 * 60 * 1000); DateTime notAfter = now.plus(5 * 60 * 1000); LastMile lm = new LastMile(uri, notBefore, notAfter, 0, "nochain"); lm.getAttributes().add(new Attribute(userNameAttr, username)); SecretKey sk = cfg.getSecretKey(keyAlias); String header = lm.generateLastMileToken(sk); req.addHeader("tremoloHeader", header); }
From source file:com.tresmonos.calendar.Configuration.java
/** * Updates the status of a resource on the server. The status involves the state (busy, free, confirmation pending), * the time of the next event and the title of the current event. *///from w w w .ja va2 s . c o m public void reportResourceInfo(ResourceState resourceState) throws ConfigurationException { try { Resource resource = resourceState.getResource(); ParseObject parseResourceObject = findOrCreateResourceInfo( Account.extractDomain(resource.getAccountName()), resource.getShortName()); DateTime currentDateTime = resourceState.getCurrentDateTime(); Period timeToNextEvent = resourceState.getTimeToNextEvent(currentDateTime); parseResourceObject.put(RESOURCES_TABLE_CURRENT_STATE, resourceState.getStatus().toString()); if (resourceState.getCurrentReservation() != null) { parseResourceObject.put(RESOURCES_TABLE_CURRENT_RESERVATION_TITLE, resourceState.getCurrentReservation().getTitle()); } else { parseResourceObject.remove(RESOURCES_TABLE_CURRENT_RESERVATION_TITLE); } if (timeToNextEvent != null) { parseResourceObject.put(RESOURCES_TABLE_NEXT_EVENT_DATE, currentDateTime.plus(timeToNextEvent).toDate()); } else { parseResourceObject.remove(RESOURCES_TABLE_NEXT_EVENT_DATE); } parseResourceObject.save(); CalendarNotificationService.getOrSubscribe(context, resource.getAccountName(), resource.getFullName()) .notifyDeviceStatusUpdated(); } catch (ParseException ex) { handleParseError("Persisting status information", ex); throw new ConfigurationException("Unable to persist status information", ex); } }
From source file:com.vaushell.superpipes.nodes.buffer.N_Buffer.java
License:Open Source License
private void pushMessage(final Message message) throws IOException { final DateTime now = new DateTime(); final Duration delta; if (getProperties().containsKey("wait-min") && getProperties().containsKey("wait-max")) { final int waitMin = getProperties().getConfigInteger("wait-min"); final int waitMax = getProperties().getConfigInteger("wait-max"); if (waitMin == waitMax) { delta = new Duration((long) waitMin); } else {// w w w . ja v a 2 s . com delta = new Duration((long) (rnd.nextInt(waitMax - waitMin) + waitMin)); } } else { delta = new Duration(0L); } final DateTime ID; if (messageIDs.isEmpty()) { ID = now.plus(delta); } else { final DateTime askedTime = now.plus(delta); final long lastID = messageIDs.last(); final DateTime lastTime = new DateTime(lastID); if (askedTime.isBefore(lastTime)) { ID = lastTime.plusMillis(1); } else { ID = askedTime; } } final Path p = messagesPath.resolve(Long.toString(ID.getMillis())); if (LOGGER.isTraceEnabled()) { LOGGER.trace("[" + getNodeID() + "] write message with ID=" + ID); } writeMessage(p, message); messageIDs.add(ID.getMillis()); }
From source file:com.vmware.identity.samlservice.impl.AuthnRequestStateValidator.java
License:Open Source License
@Override public ValidationResult validate(AuthnRequestState t) { log.debug("Validating request {}", t); ValidationResult vr = null;//from www.j a v a2 s .co m try { Validate.notNull(t); HttpServletRequest httpRequest = t.getRequest(); Validate.notNull(httpRequest); AuthnRequest request = t.getAuthnRequest(); Validate.notNull(request); Validate.notNull(request.getIssuer()); IdmAccessor accessor = t.getIdmAccessor(); Validate.notNull(accessor); Validate.notNull(accessor.getTenant()); // Validate assertion consumer service first, if that is valid, we can send SAML replies try { boolean validateACSWithMetadata = !this.isRequestSigned(t); String acsUrl = accessor.getAcsForRelyingParty(request.getIssuer().getValue(), request.getAssertionConsumerServiceIndex(), request.getAssertionConsumerServiceURL(), request.getProtocolBinding(), validateACSWithMetadata); t.setAcsUrl(acsUrl); } catch (IllegalStateException e) { // set validation result to 400 log.debug("Caught illegal state exception while Validating {} returning 400", e.toString()); vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), null); } // Validate ID if (vr == null && request.getID() == null) { vr = new ValidationResult(OasisNames.REQUESTER); log.debug("Validation FAILED - Request ID is missing"); } // Validate version if (vr == null) { SAMLVersion version = request.getVersion(); if ((version.getMajorVersion() > Shared.REQUIRED_SAML_VERSION.getMajorVersion()) || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion() && version.getMinorVersion() > Shared.REQUIRED_SAML_VERSION.getMinorVersion()) { // version too high vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_HIGH); log.debug("Validation FAILED - Version is too high"); } else if ((version.getMajorVersion() < Shared.REQUIRED_SAML_VERSION.getMajorVersion()) || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion() && version.getMinorVersion() < Shared.REQUIRED_SAML_VERSION.getMinorVersion()) { // version too low vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_LOW); log.debug("Validation FAILED - Version is too low"); } } // Validate IssueInstant only if this is a new request (i.e. it had not pass been validated) if (vr == null && !t.isExistingRequest()) { DateTime dtPlus = request.getIssueInstant(); DateTime dtMinus = request.getIssueInstant(); DateTime instant = new DateTime(); long clockTolerance = accessor.getClockTolerance(); if (dtPlus == null) { vr = new ValidationResult(OasisNames.REQUESTER); log.debug("Validation FAILED - Issue Instant is missing"); } else { dtPlus = dtPlus.plus(clockTolerance); dtMinus = dtMinus.minus(clockTolerance); // dtPlus must be after now and dtMinus must be before now // in order to satisfy clock tolerance if (dtPlus.isBefore(instant) || dtMinus.isAfter(instant)) { vr = new ValidationResult(OasisNames.REQUESTER); log.debug("Validation FAILED - Issue Instant outside of clock tolerance"); log.debug("clockTolerance {}", clockTolerance); log.debug("now {}", instant); log.debug("dtPlus {}", dtPlus.toString()); log.debug("dtMinus {}", dtMinus.toString()); } } } // Destination URL skipped, this is already done by OpenSAML when parsing // validate scoping if presenet if (vr == null) { vr = validateScoping(t); } // signature must NOT be included if (vr == null) { if (request.getSignature() != null) { log.debug("Validation FAILED - Signature MUST NOT be present"); vr = new ValidationResult(OasisNames.REQUESTER, OasisNames.REQUEST_UNSUPPORTED); } } // ensure that we don't accept unsigned requests if configuration requires signing if (vr == null) { try { boolean mustBeSigned = accessor .getAuthnRequestsSignedForRelyingParty(request.getIssuer().getValue()); this.validateSigning(mustBeSigned, t); } catch (IllegalStateException e) { // set validation result to request denied log.error("Validation FAILED - unsigned request detected, signing required"); vr = new ValidationResult(OasisNames.RESPONDER, OasisNames.REQUEST_DENIED); } } // validate NameIDPolicy if present if (vr == null) { NameIDPolicy policy = request.getNameIDPolicy(); if (policy != null) { String format = policy.getFormat(); if (format != null && !format.equals(OasisNames.PERSISTENT) && !format.equals(OasisNames.EMAIL_ADDRESS) && !format.equals(SAMLNames.IDFORMAT_VAL_UPN.toString())) { log.error("Validation FAILED - unknown NameIDPolicy Format"); vr = new ValidationResult(OasisNames.REQUESTER, OasisNames.INVALID_NAMEID_POLICY); } } } // validate conditions if (vr == null) { Conditions conditions = request.getConditions(); if (conditions != null) { // notBefore processing DateTime notBefore = conditions.getNotBefore(); if (notBefore != null) { // no additional validation, we'll use whatever client wants t.setStartTime(notBefore.toDate()); } // delegable and renewable conditions for (Condition c : conditions.getConditions()) { if (c == null) { continue; } if (c instanceof RenewableType) { t.setRenewable(true); } if (c instanceof DelegableType) { t.setDelegable(true); } } } } if (vr == null) { computeSupportedAuthnTypes(t, request); } // validation done if (vr == null) { log.info("Authentication request validation succeeded"); vr = new ValidationResult(); // success // check if we need to convert a principal into emailAddress if (request.getNameIDPolicy() != null && request.getNameIDPolicy().getFormat() != null && request.getNameIDPolicy().getFormat().equals(OasisNames.EMAIL_ADDRESS)) { t.setIdentityFormat(OasisNames.IDENTITY_FORMAT_EMAIL_ADDRESS); } else { t.setIdentityFormat(OasisNames.IDENTITY_FORMAT_UPN); } } } catch (Exception e) { vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", null); log.debug("Caught exception while Validating " + e.toString() + ", returning 400"); } return vr; }