List of usage examples for org.joda.time DateTime minusDays
public DateTime minusDays(int days)
From source file:com.lastpass.saml.SAMLClient.java
License:Apache License
private void validate(Response response) throws ValidationException { // response signature must match IdP's key, if present Signature sig = response.getSignature(); if (sig != null) sigValidator.validate(sig);/*w w w. j av a 2s . co m*/ // response must be successful 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"); } // response destination must match ACS if (!spConfig.getAcs().equals(response.getDestination())) throw new ValidationException("Response is destined for a different endpoint"); DateTime now = DateTime.now(); // issue instant must be within a day 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"); } List<Assertion> assertions; try { assertions = parseAllAssertions(response); } catch (SAMLException ex) { throw new ValidationException("no assertions found."); } for (Assertion assertion : assertions) { // Assertion must be signed correctly if (!assertion.isSigned()) throw new ValidationException("Assertion must be signed"); sig = assertion.getSignature(); sigValidator.validate(sig); // 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()) { DateTime sessionTime = as.getSessionNotOnOrAfter(); if (sessionTime != null) { DateTime exp = sessionTime.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 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 Conditions conditions = assertion.getConditions(); DateTime notBefore = conditions.getNotBefore(); DateTime notOnOrAfter = conditions.getNotOnOrAfter(); 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 Subject subject = assertion.getSubject(); if (subject != null && !subject.getSubjectConfirmations().isEmpty()) { boolean foundRecipient = false; for (SubjectConfirmation sc : subject.getSubjectConfirmations()) { if (sc.getSubjectConfirmationData() == null) continue; SubjectConfirmationData scd = sc.getSubjectConfirmationData(); if (scd.getNotOnOrAfter() != null) { DateTime chkdate = scd.getNotOnOrAfter().plusSeconds(slack); if (now.isEqual(chkdate) || now.isAfter(chkdate)) { throw new ValidationException("SubjectConfirmationData is in the past"); } } if (spConfig.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"); 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 (spConfig.getEntityId().equals(a.getAudienceURI())) foundSP = true; } if (!foundSP) throw new ValidationException("Assertion audience does not include issuer"); } }
From source file:com.linkedin.cubert.utils.FileSystemUtils.java
License:Open Source License
public static List<Path> getDurationPaths(FileSystem fs, Path root, DateTime startDate, DateTime endDate, boolean isDaily, int hourStep, boolean errorOnMissing, boolean useHourlyForMissingDaily) throws IOException { List<Path> paths = new ArrayList<Path>(); while (endDate.compareTo(startDate) >= 0) { Path loc;/*from ww w. j a va 2 s .c o m*/ if (isDaily) loc = generateDatedPath(root, endDate.getYear(), endDate.getMonthOfYear(), endDate.getDayOfMonth()); else loc = generateDatedPath(root, endDate.getYear(), endDate.getMonthOfYear(), endDate.getDayOfMonth(), endDate.getHourOfDay()); // Check that directory exists, and contains avro files. if (fs.exists(loc) && fs.globStatus(new Path(loc, "*" + "avro")).length > 0) { paths.add(loc); } else { loc = generateDatedPath(new Path(root.getParent(), "hourly"), endDate.getYear(), endDate.getMonthOfYear(), endDate.getDayOfMonth()); if (isDaily && useHourlyForMissingDaily && fs.exists(loc)) { for (FileStatus hour : fs.listStatus(loc)) { paths.add(hour.getPath()); } } else if (errorOnMissing) { throw new RuntimeException("Missing directory " + loc.toString()); } } if (hourStep == 24) endDate = endDate.minusDays(1); else endDate = endDate.minusHours(hourStep); } return paths; }
From source file:com.lmig.forge.stash.ssh.keys.EnterpriseSshKeyServiceImpl.java
License:Apache License
@Override public void replaceExpiredKeysAndNotifyUsers() { DateTime dateTime = new DateTime(); Date oldestAllowed = dateTime.minusDays(pluginSettingsService.getDaysAllowedForUserKeys()).toDate(); //Date oldestAllowed = dateTime.minusMinutes(1).toDate(); //for live demos List<SshKeyEntity> expiredStashKeys = enterpriseKeyRepository.listOfExpiredKeys(oldestAllowed, KeyType.USER);//www . jav a2s. c om for (SshKeyEntity keyRecord : expiredStashKeys) { try { log.info("Removing Key for user " + keyRecord.getUserId()); sshKeyService.remove(keyRecord.getKeyId()); enterpriseKeyRepository.removeRecord(keyRecord); notificationService.notifyUserOfExpiredKey(keyRecord.getUserId()); log.info("Key Removed"); } catch (Exception e) { log.error("Key removal failed for user: " + keyRecord.getUserId()); e.printStackTrace(); } } }
From source file:com.magnet.mmx.server.plugin.mmxmgmt.db.DeviceDAOImpl.java
License:Apache License
@Override public Map<String, MMXDeviceStats> getDeviceStats(List<String> appIdList) { LOGGER.trace("getDeviceStats : appIdList={}", appIdList); Connection con = null;/*from w ww .j a v a 2 s . c o m*/ PreparedStatement pstmt = null; ResultSet rs = null; String statementStr = "SELECT appId, status, dateCreated FROM mmxDevice WHERE appId IN ( " + SqlUtil.getQs(appIdList.size()) + " )"; Map<String, MMXDeviceStats> statsMap = new HashMap<String, MMXDeviceStats>(); try { con = provider.getConnection(); pstmt = con.prepareStatement(statementStr); for (int i = 1; i <= appIdList.size(); i++) { String appId = appIdList.get(i - 1); pstmt.setString(i, appId); statsMap.put(appId, new MMXDeviceStats(appId)); } LOGGER.trace("getDeviceStats : executing query : {}", pstmt); rs = pstmt.executeQuery(); while (rs.next()) { String appId = rs.getString(1); String status = rs.getString(2); MMXDeviceStats deviceStats = statsMap.get(appId); if (DeviceStatus.ACTIVE.name().equals(status)) { deviceStats.incrementActive(); } else if (DeviceStatus.INACTIVE.name().equals(status)) { deviceStats.incrementInactive(); } DateTime dateCreated = new DateTime(rs.getDate(3)); DateTime now = new DateTime(); if (dateCreated.isAfter(now.minusDays(7))) { deviceStats.incrementNumDevices(); } LOGGER.trace("getDeviceStats : appId={}, numDevices={}, totalActive={}, totalInactive={}", new Object[] { appId, deviceStats.getNumDevices(), deviceStats.getTotalActive(), deviceStats.getTotalInActive() }); } } catch (SQLException e) { LOGGER.error("getDeviceStats : exception caught appIdList={}", appIdList); e.printStackTrace(); } finally { CloseUtil.close(LOGGER, rs, pstmt, con); } return statsMap; }
From source file:com.marand.thinkmed.medications.administration.impl.AdministrationTaskCreatorImpl.java
License:Open Source License
private List<Interval> removeInactiveTherapyDaysFromTasksInterval(final TherapyDto therapy, final DateTime start, final DateTime end) { final DateTime therapyStart = therapy.getStart(); final Integer daysFrequency = therapy.getDosingDaysFrequency(); final List<Interval> intervals = new ArrayList<>(); DateTime intervalStart = new DateTime(start); DateTime intervalEnd = intervalStart.withTimeAtStartOfDay().plusDays(1); final DateTime firstDayStart = intervalStart.withTimeAtStartOfDay(); boolean validDayOfWeek = isInValidDaysOfWeek(intervalStart, therapy.getDaysOfWeek()); boolean validFrequency = isInValidDaysFrequency(intervalStart, therapyStart, daysFrequency); boolean previousDayWasValid = validDayOfWeek && validFrequency; if (!previousDayWasValid) { intervalStart = firstDayStart.plusDays(1); }/*from w w w. j a v a 2 s. c om*/ boolean validInFutureDays = false; while (intervalEnd.isBefore(end) || intervalEnd.equals(end)) { validDayOfWeek = isInValidDaysOfWeek(intervalEnd, therapy.getDaysOfWeek()); validFrequency = isInValidDaysFrequency(intervalEnd, therapyStart, daysFrequency); if (validDayOfWeek && validFrequency) { previousDayWasValid = true; } else { if (previousDayWasValid) { intervals.add(new Interval(intervalStart, intervalEnd)); } previousDayWasValid = false; intervalStart = intervalEnd.plusDays(1); } intervalEnd = intervalEnd.plusDays(1); validInFutureDays = true; } if (previousDayWasValid && validInFutureDays || intervalEnd.minusDays(1).isBefore(end)) { if (!intervalStart.isAfter(end)) { intervals.add(new Interval(intervalStart, end)); } } return intervals; }
From source file:com.marand.thinkmed.medications.administration.impl.AdministrationTaskCreatorImpl.java
License:Open Source License
private Pair<DateTime, TherapyDoseDto> getPreviousAdministrationTimeWithDose(final DateTime fromTime, final Map<HourMinuteDto, TherapyDoseDto> administrationTimesWithDoses, final boolean fromTimeIncluded) { int index = administrationTimesWithDoses.size() - 1; final List<HourMinuteDto> times = new ArrayList<>(administrationTimesWithDoses.keySet()); Collections.sort(times);//from w w w . j ava 2 s . co m DateTime foundTime = times.get(index).combine(fromTime.plusDays(1)); TherapyDoseDto therapyDoseDto = administrationTimesWithDoses.get(times.get(index)); while (foundTime.isAfter(fromTime) || (foundTime.equals(fromTime) && !fromTimeIncluded)) { index--; if (index < 0) { index = administrationTimesWithDoses.size() - 1; foundTime = foundTime.minusDays(1); } final HourMinuteDto hourMinute = times.get(index); foundTime = hourMinute.combine(foundTime); therapyDoseDto = administrationTimesWithDoses.get(hourMinute); } return Pair.of(foundTime, therapyDoseDto); }
From source file:com.marand.thinkmed.medications.business.impl.DefaultMedicationsBo.java
License:Open Source License
@Override @Transactional// ww w .ja va 2s . c om @ServiceMethod(auditing = @Auditing(level = Level.FULL)) public DateTime findPreviousTaskForTherapy(final String patientId, final String compositionUid, final String ehrOrderName, final DateTime when) { Pair<MedicationOrderComposition, MedicationInstructionInstruction> instructionPair = medicationsOpenEhrDao .getTherapyInstructionPair(patientId, compositionUid, ehrOrderName); while (instructionPair != null) { final List<AdministrationDto> administrations = administrationProvider .getTherapiesAdministrations(patientId, Collections.singletonList(instructionPair), null); final String therapyId = TherapyIdUtils.createTherapyId(instructionPair.getFirst(), instructionPair.getSecond()); final DateTime lastTask = medicationsTasksProvider.findLastAdministrationTaskTimeForTherapy(patientId, therapyId, new Interval(when.minusDays(10), when), false).orElse(null); final DateTime lastAdministration = administrations.stream() .filter(a -> a.getAdministrationResult() != AdministrationResultEnum.NOT_GIVEN) .map(AdministrationDto::getAdministrationTime).max(Comparator.naturalOrder()).orElse(null); final DateTime lastTime = getMostRecent(lastTask, lastAdministration); if (lastTime != null) { return lastTime; } instructionPair = getInstructionFromLink(patientId, instructionPair.getSecond(), EhrLinkType.UPDATE, true); } return null; }
From source file:com.marand.thinkmed.medications.dao.openehr.MedicationsOpenEhrDao.java
License:Open Source License
@EhrSessioned public Collection<TherapyAutomaticChartingDto> getAutoChartingTherapyDtos(final DateTime when) { final StringBuilder sb = new StringBuilder(); sb.append("SELECT c/uid/value, " + "i/name/value, " + "e/ehr_status/subject/external_ref/id/value, " + "i/activities/description/items/value/formalism") .append(" 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.minusDays(1).withTimeAtStartOfDay())); //TODO NEJC SAVE DIFFERENTLY when new templates! sb.append(" AND i/activities/description/items/name = 'Parsable dose description'") .append(" AND i/activities/description/items/value/value = '" + SelfAdministeringActionEnum.AUTOMATICALLY_CHARTED.name() + "'"); final List<TherapyAutomaticChartingDto> autoChartingTherapies = new ArrayList<>(); try (EhrResult ehrResult = new QueryBuilder(ehrQueryService, ehrSessionManager.getSessionId()) .poll(100L, 1000L * 30L).withAql(sb.toString()).execute()) { while (ehrResult.isActive()) { if (ehrResult.hasNext(100L)) { final EhrResultRow resultRow = ehrResult.next(); final String compositionUid = (String) resultRow.get(0); final String instructionName = (String) resultRow.get(1); final String patientId = (String) resultRow.get(2); final String jsonDateTime = (String) resultRow.get(3); final SelfAdminAutomaticChartingDto dto = new SelfAdminAutomaticChartingDto(compositionUid, instructionName, patientId, JsonUtil.fromJson(jsonDateTime, DateTime.class), SelfAdministeringActionEnum.AUTOMATICALLY_CHARTED); autoChartingTherapies.add(dto); }// w w w . j ava2s. c om } } final List<TherapyAutomaticChartingDto> autoChartingNormalInfusions = getAutoChartingTherapiesWithRate( when); return joinAutoChartingDtos(autoChartingTherapies, autoChartingNormalInfusions); }
From source file:com.marand.thinkmed.medications.dao.openehr.MedicationsOpenEhrDao.java
License:Open Source License
private List<TherapyAutomaticChartingDto> getAutoChartingTherapiesWithRate(final DateTime when) { final StringBuilder sb = new StringBuilder(); sb.append("SELECT " + "c/uid/value, " + "i/name/value, " + "e/ehr_status/subject/external_ref/id/value") .append(" FROM EHR e").append(" CONTAINS Composition c[openEHR-EHR-COMPOSITION.encounter.v1]") .append(" CONTAINS Instruction i[openEHR-EHR-INSTRUCTION.medication.v1]") .append(" CONTAINS Cluster a[openEHR-EHR-CLUSTER.medication_admin.v1]") .append(" CONTAINS Cluster d[openEHR-EHR-CLUSTER.infusion_details.v1]") .append(" WHERE c/name/value = 'Medication order'").append(" AND EXISTS d/items[at0001]/value") // has rate .append(" AND d/items[at0001]/value/value != 'BOLUS'") // is not BOLUS .append(" AND NOT EXISTS a/items[at0003]/value"); // delivery method is empty appendMedicationTimingIntervalCriterion(sb, Intervals.infiniteFrom(when.minusDays(1).withTimeAtStartOfDay())); final List<TherapyAutomaticChartingDto> autoChartingNormalInfusions = new ArrayList<>(); try (EhrResult ehrResult = new QueryBuilder(ehrQueryService, ehrSessionManager.getSessionId()) .poll(100L, 1000L * 30L).withAql(sb.toString()).execute()) { while (ehrResult.isActive()) { if (ehrResult.hasNext(100L)) { final EhrResultRow resultRow = ehrResult.next(); final NormalInfusionAutomaticChartingDto dto = new NormalInfusionAutomaticChartingDto( (String) resultRow.get(0), (String) resultRow.get(1), (String) resultRow.get(2)); autoChartingNormalInfusions.add(dto); }// w w w .j a v a 2 s . co m } } return autoChartingNormalInfusions; }
From source file:com.marand.thinkmed.medications.process.impl.TherapyTaskCreatorImpl.java
License:Open Source License
private List<Interval> removeInactiveTherapyDaysFromTasksInterval(final DateTime start, final DateTime end, final RoundsIntervalDto roundsInterval, final TimingCluster timing) { final List<Interval> intervals = new ArrayList<>(); DateTime tasksStart = new DateTime(start); final DateTime startOfTodaysRounds = start.withTimeAtStartOfDay().plusHours(roundsInterval.getStartHour()) .plusMinutes(roundsInterval.getStartMinute()); DateTime tasksEnd = start.withTimeAtStartOfDay().plusHours(roundsInterval.getEndHour()) .plusMinutes(roundsInterval.getEndMinute()); if (start.isAfter(startOfTodaysRounds) && tasksEnd.isBefore(end)) { if (tasksEnd.plusDays(1).isAfter(end)) { tasksEnd = end;// w ww .ja v a2s. c o m } else { tasksEnd = tasksEnd.plusDays(1); } } int daysFrequency = 1; if (timing != null && timing.getInterval() != null) { final int days = DataValueUtils.getPeriod(timing.getInterval()).getDays(); if (days > 0) { daysFrequency = days; } } boolean previousDayWasValid = isInValidDaysOfWeek(tasksStart, timing); if (!previousDayWasValid) { tasksStart = startOfTodaysRounds.plusDays(1); } int dayIndex = 1; while (tasksEnd.isBefore(end) || tasksEnd.equals(end)) { final boolean validDayOfWeek = isInValidDaysOfWeek(tasksEnd, timing); final boolean validFrequency = dayIndex % daysFrequency == 0; if (validDayOfWeek && validFrequency) { previousDayWasValid = true; } else { final DateTime startOfRounds = tasksEnd.withTimeAtStartOfDay() .plusHours(roundsInterval.getStartHour()).plusMinutes(roundsInterval.getStartMinute()); if (previousDayWasValid) { intervals.add(new Interval(tasksStart, startOfRounds)); } previousDayWasValid = false; tasksStart = startOfRounds.plusDays(1); } tasksEnd = tasksEnd.plusDays(1); dayIndex++; } if (previousDayWasValid && dayIndex > 1 || tasksEnd.minusDays(1).isBefore(end)) { if (!tasksStart.isAfter(end)) { intervals.add(new Interval(tasksStart, end)); } } return intervals; }