List of usage examples for org.joda.time DateTime plus
public DateTime plus(ReadablePeriod period)
From source file:be.fedict.trust.ocsp.OcspTrustLinker.java
License:Open Source License
@Override public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy) throws TrustLinkerResultException, Exception { URI ocspUri = getOcspUri(childCertificate); if (null == ocspUri) { return TrustLinkerResult.UNDECIDED; }/*from w ww . j a v a 2s. c o m*/ LOG.debug("OCSP URI: " + ocspUri); OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate, validationDate); if (null == ocspResp) { LOG.debug("OCSP response not found"); return TrustLinkerResult.UNDECIDED; } int ocspRespStatus = ocspResp.getStatus(); if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) { LOG.debug("OCSP response status: " + ocspRespStatus); return TrustLinkerResult.UNDECIDED; } Object responseObject = ocspResp.getResponseObject(); BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject; X509CertificateHolder[] responseCertificates = basicOCSPResp.getCerts(); for (X509CertificateHolder responseCertificate : responseCertificates) { LOG.debug("OCSP response cert: " + responseCertificate.getSubject()); LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuer()); } algorithmPolicy.checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgOID().getId(), validationDate); if (0 == responseCertificates.length) { /* * This means that the OCSP response has been signed by the issuing * CA itself. */ ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certificate.getPublicKey()); boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider); if (false == verificationResult) { LOG.debug("OCSP response signature invalid"); return TrustLinkerResult.UNDECIDED; } } else { /* * We're dealing with a dedicated authorized OCSP Responder * certificate, or of course with a CA that issues the OCSP * Responses itself. */ X509CertificateHolder ocspResponderCertificate = responseCertificates[0]; ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspResponderCertificate); boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider); if (false == verificationResult) { LOG.debug("OCSP Responser response signature invalid"); return TrustLinkerResult.UNDECIDED; } if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) { // check certificate signature algorithm algorithmPolicy.checkSignatureAlgorithm( ocspResponderCertificate.getSignatureAlgorithm().getAlgorithm().getId(), validationDate); X509Certificate issuingCaCertificate; if (responseCertificates.length < 2) { // so the OCSP certificate chain only contains a single // entry LOG.debug("OCSP responder complete certificate chain missing"); /* * Here we assume that the OCSP Responder is directly signed * by the CA. */ issuingCaCertificate = certificate; } else { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); issuingCaCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(responseCertificates[1].getEncoded())); /* * Is next check really required? */ if (false == certificate.equals(issuingCaCertificate)) { LOG.debug("OCSP responder certificate not issued by CA"); return TrustLinkerResult.UNDECIDED; } } // check certificate signature algorithmPolicy.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgOID(), validationDate); PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509OcspResponderCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(ocspResponderCertificate.getEncoded())); LOG.debug("OCSP Responder public key fingerprint: " + DigestUtils.sha1Hex(x509OcspResponderCertificate.getPublicKey().getEncoded())); publicKeyTrustLinker.hasTrustLink(x509OcspResponderCertificate, issuingCaCertificate, validationDate, revocationData, algorithmPolicy); if (null == x509OcspResponderCertificate .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) { LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck"); /* * TODO: perform CRL validation on the OCSP Responder * certificate. On the other hand, do we really want to * check the checker? */ return TrustLinkerResult.UNDECIDED; } List<String> extendedKeyUsage = x509OcspResponderCertificate.getExtendedKeyUsage(); if (null == extendedKeyUsage) { LOG.debug("OCSP Responder certificate has no extended key usage extension"); return TrustLinkerResult.UNDECIDED; } if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) { LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage"); return TrustLinkerResult.UNDECIDED; } } else { LOG.debug("OCSP Responder certificate equals the CA certificate"); // and the CA certificate is already trusted at this point } } DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(); CertificateID certificateId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(certificate), childCertificate.getSerialNumber()); SingleResp[] singleResps = basicOCSPResp.getResponses(); for (SingleResp singleResp : singleResps) { CertificateID responseCertificateId = singleResp.getCertID(); if (false == certificateId.equals(responseCertificateId)) { continue; } DateTime thisUpdate = new DateTime(singleResp.getThisUpdate()); DateTime nextUpdate; if (null != singleResp.getNextUpdate()) { nextUpdate = new DateTime(singleResp.getNextUpdate()); } else { LOG.debug("no OCSP nextUpdate"); nextUpdate = thisUpdate; } LOG.debug("OCSP thisUpdate: " + thisUpdate); LOG.debug("(OCSP) nextUpdate: " + nextUpdate); DateTime beginValidity = thisUpdate.minus(this.freshnessInterval); DateTime endValidity = nextUpdate.plus(this.freshnessInterval); DateTime validationDateTime = new DateTime(validationDate); if (validationDateTime.isBefore(beginValidity)) { LOG.warn("OCSP response not yet valid"); continue; } if (validationDateTime.isAfter(endValidity)) { LOG.warn("OCSP response expired"); continue; } if (null == singleResp.getCertStatus()) { LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal()); addRevocationData(revocationData, ocspResp, ocspUri); return TrustLinkerResult.TRUSTED; } else { LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName()); if (singleResp.getCertStatus() instanceof RevokedStatus) { LOG.debug("OCSP status revoked"); } addRevocationData(revocationData, ocspResp, ocspUri); throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_REVOCATION_STATUS, "certificate revoked by OCSP"); } } LOG.debug("no matching OCSP response entry"); return TrustLinkerResult.UNDECIDED; }
From source file:cd.go.contrib.elasticagents.docker.DockerContainers.java
License:Apache License
private DockerContainers unregisteredAfterTimeout(PluginSettings settings, Agents knownAgents) throws Exception { Period period = settings.getAutoRegisterPeriod(); DockerContainers unregisteredContainers = new DockerContainers(); for (String containerName : instances.keySet()) { if (knownAgents.containsAgentWithId(containerName)) { continue; }//from w ww . j a v a 2 s. co m ContainerInfo containerInfo; try { containerInfo = docker(settings).inspectContainer(containerName); } catch (ContainerNotFoundException e) { LOG.warn("The container " + containerName + " could not be found."); continue; } DateTime dateTimeCreated = new DateTime(containerInfo.created()); if (clock.now().isAfter(dateTimeCreated.plus(period))) { unregisteredContainers.register(DockerContainer.fromContainerInfo(containerInfo)); } } return unregisteredContainers; }
From source file:cd.go.contrib.elasticagents.dockerswarm.elasticagent.DockerServices.java
License:Apache License
private DockerServices unregisteredAfterTimeout(PluginSettings settings, Agents knownAgents) throws Exception { Period period = settings.getAutoRegisterPeriod(); DockerServices unregisteredContainers = new DockerServices(); for (String serviceName : services.keySet()) { if (knownAgents.containsServiceWithId(serviceName)) { continue; }//from w ww .j a v a2 s . co m Service serviceInfo; try { serviceInfo = docker(settings).inspectService(serviceName); } catch (ServiceNotFoundException e) { LOG.warn("The container " + serviceName + " could not be found."); continue; } DateTime dateTimeCreated = new DateTime(serviceInfo.createdAt()); if (clock.now().isAfter(dateTimeCreated.plus(period))) { unregisteredContainers.register(DockerService.fromService(serviceInfo)); } } return unregisteredContainers; }
From source file:cd.go.contrib.elasticagents.marathon.MarathonAgentInstances.java
License:Apache License
private MarathonAgentInstances unregisteredAfterTimeout(PluginSettings settings, Agents knownAgents) throws Exception { MarathonAgentInstances unregisteredContainers = new MarathonAgentInstances(); if (settings == null) { return unregisteredContainers; }//from www .j av a 2 s . co m Period period = settings.getAutoRegisterPeriod(); for (MarathonInstance instance : instances.values()) { if (knownAgents.containsAgentWithId(instance.name())) { continue; } DateTime dateTimeCreated = new DateTime(instance.createdAt()); if (clock.now().isAfter(dateTimeCreated.plus(period))) { unregisteredContainers.register(instance); } } return unregisteredContainers; }
From source file:ch.windmobile.server.mongo.MongoDataSource.java
License:Open Source License
static protected Status getDataStatus(String status, DateTime now, DateTime expirationDate) { // Orange > 10 minutes late DateTime orangeStatusLimit = expirationDate.plus(10 * 60 * 1000); // Red > 2h10 late DateTime redStatusLimit = expirationDate.plus(2 * 3600 * 1000 + 10 * 60 * 1000); if (Status.RED.value().equalsIgnoreCase(status) || now.isAfter(redStatusLimit)) { return Status.RED; } else if (Status.ORANGE.value().equalsIgnoreCase(status) || now.isAfter(orangeStatusLimit)) { return Status.ORANGE; } else {//from w w w .j ava 2 s . c o m // Handle case when data received are in the future return Status.GREEN; } }
From source file:com.aionemu.gameserver.model.house.MaintenanceTask.java
License:Open Source License
@Override protected void executeTask() { if (!HousingConfig.ENABLE_HOUSE_PAY) { return;/*from w w w.j av a 2 s . c o m*/ } // Get times based on configuration values DateTime now = new DateTime(); DateTime previousRun = now.minus(getPeriod()); // usually week ago DateTime beforePreviousRun = previousRun.minus(getPeriod()); // usually two weeks ago for (House house : maintainedHouses) { if (house.isFeePaid()) { continue; // player already paid, don't check } long payTime = house.getNextPay().getTime(); long impoundTime = 0; int warnCount = 0; PlayerCommonData pcd = null; Player player = World.getInstance().findPlayer(house.getOwnerId()); if (player == null) { pcd = DAOManager.getDAO(PlayerDAO.class).loadPlayerCommonData(house.getOwnerId()); } else { pcd = player.getCommonData(); } if (pcd == null) { // player doesn't exist already for some reasons log.warn("House " + house.getAddress().getId() + " had player assigned but no player exists. Auctioned."); putHouseToAuction(house, null); continue; } if (payTime <= beforePreviousRun.getMillis()) { DateTime plusDay = beforePreviousRun.minusDays(1); if (payTime <= plusDay.getMillis()) { // player didn't pay after the second warning and one day passed impoundTime = now.getMillis(); warnCount = 3; putHouseToAuction(house, pcd); } else { impoundTime = now.plusDays(1).getMillis(); warnCount = 2; } } else if (payTime <= previousRun.getMillis()) { // player did't pay 1 period impoundTime = now.plus(getPeriod()).plusDays(1).getMillis(); warnCount = 1; } else { continue; // should not happen } if (pcd.isOnline()) { if (warnCount == 3) { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_SEQUESTRATE); } else { PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OVERDUE); } } MailFormatter.sendHouseMaintenanceMail(house, warnCount, impoundTime); } }
From source file:com.alfaariss.oa.util.saml2.SAML2ConditionsWindow.java
License:Open Source License
/** * Verifies if the current time is within the supplied time window. * <br>// w w w .jav a2 s.co m * The time window is extended with configured offsets. * * @param dtNB Not Before condition or NULL if not available. * @param dtNOA Not On Or After condition or NULL if not available. * @return TRUE if the current datetime is within the window. */ public boolean canAccept(DateTime dtNB, DateTime dtNOA) { DateTime dtNow = new DateTime(); if (dtNB != null) { DateTime dtNotBefore = dtNB.minus(_lBeforeOffset); if (dtNow.getMillis() < dtNotBefore.getMillis()) { StringBuffer sbDebug = new StringBuffer("Condition time stamp(s) incorrect; Current time ("); sbDebug.append(dtNow); sbDebug.append(") is before the Not Before time: "); sbDebug.append(dtNB); _logger.debug(sbDebug.toString()); return false; } } if (dtNOA != null) { DateTime dtNotOnOrAfter = dtNOA.plus(_lAfterOffset); if (dtNow.getMillis() >= dtNotOnOrAfter.getMillis()) { StringBuffer sbDebug = new StringBuffer("Condition time stamp(s) incorrect; Current time ("); sbDebug.append(dtNow); sbDebug.append(") is on or after the Not On Or After time: "); sbDebug.append(dtNOA); _logger.debug(sbDebug.toString()); return false; } } return true; }
From source file:com.almende.eve.agent.MeetingAgent.java
License:Apache License
/** * Apply the constraints of the the activity (for example duration) * //from ww w . ja v a 2 s . co m * @param activity * @return changed Returns true if the activity is changed */ private boolean applyConstraints() { final Activity activity = getState().get("activity", Activity.class); boolean changed = false; if (activity == null) { return false; } // constraints on attendees/resources /* * TODO: copy actual attendees to status.attendees * List<Attendee> constraintsAttendees = * activity.withConstraints().withAttendees(); * List<Attendee> attendees = new ArrayList<Attendee>(); * for (Attendee attendee : constraintsAttendees) { * attendees.add(attendee.clone()); * } * activity.withStatus().setAttendees(attendees); * // TODO: is it needed to check if the attendees are changed? */ // check time constraints final Long duration = activity.withConstraints().withTime().getDuration(); if (duration != null) { final String start = activity.withStatus().getStart(); final String end = activity.withStatus().getEnd(); if (start != null && end != null) { final DateTime startTime = new DateTime(start); DateTime endTime = new DateTime(end); final Interval interval = new Interval(startTime, endTime); if (interval.toDurationMillis() != duration) { LOG.info("status did not match constraints. " + "Changed end time to match the duration of " + duration + " ms"); // duration does not match. adjust the end time endTime = startTime.plus(duration); activity.withStatus().setEnd(endTime.toString()); activity.withStatus().setUpdated(DateTime.now().toString()); changed = true; } } } // location constraints final String newLocation = activity.withConstraints().withLocation().getSummary(); final String oldLocation = activity.withStatus().withLocation().getSummary(); if (newLocation != null && !newLocation.equals(oldLocation)) { activity.withStatus().withLocation().setSummary(newLocation); changed = true; } if (changed) { // store the updated activity getState().put("activity", activity); } return changed; }
From source file:com.almende.eve.agent.MeetingAgent.java
License:Apache License
/** * Calculate all feasible intervals with their preference weight, based on * the event status, stored infeasible intervals, and preferred intervals. * If there are no solutions, an empty array is returned. * /*w w w . j av a 2 s.c o m*/ * @return solutions */ private List<Weight> calculateSolutions() { LOG.info("calculateSolutions started"); // TODO: cleanup final State state = getState(); final List<Weight> solutions = new ArrayList<Weight>(); // get the activity final Activity activity = state.get("activity", Activity.class); if (activity == null) { return solutions; } // get infeasible intervals ArrayList<Interval> infeasible = state.get("infeasible", new TypeUtil<ArrayList<Interval>>() { }); if (infeasible == null) { infeasible = new ArrayList<Interval>(); } // get preferred intervals List<Weight> preferred = state.get("preferred", new TypeUtil<ArrayList<Weight>>() { }); if (preferred == null) { preferred = new ArrayList<Weight>(); } // get the duration of the activity final Long durationLong = activity.withConstraints().withTime().getDuration(); Duration duration = null; if (durationLong != null) { duration = new Duration(durationLong); } else { // TODO: give error when duration is not defined? duration = Duration.standardHours(1); } // check interval at next half hour final DateTime firstTimeslot = getNextHalfHour(); Interval test = new Interval(firstTimeslot, firstTimeslot.plus(duration)); testInterval(infeasible, preferred, test, solutions); // loop over all infeasible intervals for (final Interval i : infeasible) { // test timeslot left from the infeasible interval test = new Interval(i.getStart().minus(duration), i.getStart()); testInterval(infeasible, preferred, test, solutions); // test timeslot right from the infeasible interval test = new Interval(i.getEnd(), i.getEnd().plus(duration)); testInterval(infeasible, preferred, test, solutions); } // loop over all preferred intervals for (final Weight w : preferred) { // test timeslot left from the start of the preferred interval test = new Interval(w.getStart().minus(duration), w.getStart()); testInterval(infeasible, preferred, test, solutions); // test timeslot right from the start of the preferred interval test = new Interval(w.getStart(), w.getStart().plus(duration)); testInterval(infeasible, preferred, test, solutions); // test timeslot left from the end of the preferred interval test = new Interval(w.getEnd().minus(duration), w.getEnd()); testInterval(infeasible, preferred, test, solutions); // test timeslot right from the end of the preferred interval test = new Interval(w.getEnd(), w.getEnd().plus(duration)); testInterval(infeasible, preferred, test, solutions); } // order the calculated feasible timeslots by weight, from highest to // lowest. In case of equals weights, the timeslots are ordered by // start date class WeightComparator implements Comparator<Weight> { @Override public int compare(final Weight a, final Weight b) { if (a.getWeight() != null && b.getWeight() != null) { final int cmp = Double.compare(a.getWeight(), b.getWeight()); if (cmp == 0) { return a.getStart().compareTo(b.getStart()); } else { return -cmp; } } return 0; } } final WeightComparator comparator = new WeightComparator(); Collections.sort(solutions, comparator); // remove duplicates int i = 1; while (i < solutions.size()) { if (solutions.get(i).equals(solutions.get(i - 1))) { solutions.remove(i); } else { i++; } } return solutions; }
From source file:com.almende.pi5.common.agents.GraphAgent.java
License:Apache License
/** * Update time./* w ww. j a va 2s . c om*/ */ @Access(AccessType.PUBLIC) public void updateTime() { DateTime now = DateTime.now(); now = now.plus((TIMESTEP - (now.getMinuteOfHour() % TIMESTEP)) * 60000 - (now.getSecondOfMinute() * 1000) - now.getMillisOfSecond()); if (!this.currentTimeslot.equals(now)) { this.currentTimeslot = now; LOG.fine(getId() + ": updateTime to: " + now); } }