List of usage examples for org.joda.time DateTime minusMinutes
public DateTime minusMinutes(int minutes)
From source file:com.amazonaws.services.kinesis.scaling.auto.StreamMonitor.java
License:Open Source License
@Override public void run() { LOG.info(String.format("Started Stream Monitor for %s", config.getStreamName())); DateTime lastShardCapacityRefreshTime = new DateTime(System.currentTimeMillis()); // create a StreamMetricManager object StreamMetricManager metricManager = new StreamMetricManager(this.config.getStreamName(), this.config.getScaleOnOperations(), this.cloudWatchClient, this.kinesisClient); try {// w ww . j ava 2s. com // load the current configured max capacity metricManager.loadMaxCapacity(); // configure the duration to request from cloudwatch int cwSampleDuration = Math.max(config.getScaleUp().getScaleAfterMins(), config.getScaleDown().getScaleAfterMins()); ScalingOperationReport report = null; do { DateTime now = new DateTime(System.currentTimeMillis()); DateTime metricEndTime = now; // fetch only the last N minutes metrics DateTime metricStartTime = metricEndTime.minusMinutes(cwSampleDuration); // load the current cloudwatch metrics for the stream via the // metrics manager @SuppressWarnings("rawtypes") Map currentUtilisationMetrics = metricManager.queryCurrentUtilisationMetrics(cwSampleDuration, metricStartTime, metricEndTime); // process the aggregated set of Cloudwatch Datapoints report = processCloudwatchMetrics(currentUtilisationMetrics, metricManager.getStreamMaxCapacity(), cwSampleDuration, now); if (report != null) { // refresh the current max capacity after the // modification metricManager.loadMaxCapacity(); lastShardCapacityRefreshTime = now; // notify all report listeners that we've completed a // scaling operation if (this.config.getScalingOperationReportListener() != null) { this.config.getScalingOperationReportListener().onReport(report); } if (report.getScaleDirection() != ScaleDirection.NONE) { LOG.info(report.toString()); } report = null; } // refresh shard stats every configured period, in case someone // has manually updated the number of shards manually if (now.minusMinutes(this.config.getRefreshShardsNumberAfterMin()) .isAfter(lastShardCapacityRefreshTime)) { metricManager.loadMaxCapacity(); lastShardCapacityRefreshTime = now; } try { LOG.debug("Sleep"); Thread.sleep(this.config.getCheckInterval() * 1000); } catch (InterruptedException e) { LOG.error(e.getMessage(), e); break; } } while (keepRunning); LOG.info(String.format("Stream Monitor for %s in %s Completed. Exiting.", this.config.getStreamName(), this.config.getRegion())); } catch (Exception e) { this.exception = e; } }
From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java
License:Apache License
private Map<String, String> createValueMap(Azure azure, String namespaceName, String resourceType, Set<String> queueStats) { Map<String, String> valueMap = new HashMap<String, String>(); valueMap.put("SubscriptionId", azure.getSubscriptionId()); valueMap.put("NameSpace", namespaceName); valueMap.put("ResourceType", resourceType); String stats = Joiner.on(",").skipNulls().join(queueStats); valueMap.put("Stats", stats); DateTime dateTime = new DateTime(DateTimeZone.UTC).minusMinutes(15); String endTime = dateTime.toString(DateTimeFormat.forPattern(DATE_FORMAT)); String startTime = dateTime.minusMinutes(1).toString(DateTimeFormat.forPattern(DATE_FORMAT)); valueMap.put("StartTime", startTime); valueMap.put("EndTime", endTime); return valueMap; }
From source file:com.datastax.sampledata.CreateSSTables.java
private static Date randomDateInLastNYears(int years) { DateTime dateTime = new DateTime(); dateTime = dateTime.minusYears(new Double(Math.random() * years).intValue()); dateTime = dateTime.minusMonths(new Double(Math.random() * 12).intValue()); dateTime = dateTime.minusDays(new Double(Math.random() * 30).intValue()); dateTime = dateTime.minusHours(new Double(Math.random() * 24).intValue()); dateTime = dateTime.minusMinutes(new Double(Math.random() * 60).intValue()); dateTime = dateTime.minusSeconds(new Double(Math.random() * 60).intValue()); return dateTime.toDate(); }
From source file:com.ehdev.chronos.lib.Chronos.java
License:Open Source License
public void dropAndTest() { try {// w w w . ja v a 2 s. c om // instantiate the DAO to handle Account with String id Dao<Punch, String> punchDao = getPunchDao(); Dao<Task, String> taskDAO = getTaskDao(); Dao<Job, String> jobDAO = getJobDao(); Dao<Note, String> noteDAO = getNoteDao(); List<Task> tasks = taskDAO.queryForAll(); Job currentJob = jobDAO.queryForAll().get(0); DateTime iTime = new DateTime(); Random rand = new Random(); DateTime tempTime = null; for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { tempTime = iTime.minusHours(j); tempTime = tempTime.minusMinutes(rand.nextInt() % 60); Punch temp = new Punch(currentJob, tasks.get(0), tempTime); Note newNote = new Note(tempTime, currentJob, "Note number " + String.valueOf(j + 1)); noteDAO.create(newNote); punchDao.create(temp); } tempTime = tempTime.minusMinutes(rand.nextInt() % 60); punchDao.create( new Punch(currentJob, tasks.get((int) (Math.random() * 100) % tasks.size()), tempTime)); iTime = iTime.plusDays(1); } } catch (SQLException e) { Log.e(TAG, e.getMessage()); } catch (Exception e) { Log.e(TAG, e.getMessage()); } }
From source file:com.enitalk.controllers.OpentokSessionController.java
@RequestMapping(method = RequestMethod.GET, value = "/session/teacher/{id}", produces = "text/html") @ResponseBody/*from w w w.jav a 2s. c om*/ public byte[] sessionTeacher(@PathVariable String id, HttpServletResponse res, boolean requireUrl) throws IOException { byte[] out = null; try { Query q = Query.query(Criteria.where("ii").is(id).andOperator(Criteria.where("status").is(2))); logger.info("Looking for teacher event {}", id); HashMap ev = mongo.findOne(q, HashMap.class, "events"); if (ev == null) { return "Sorry, no such event found.".getBytes(); } Date date = (Date) ev.get("dd"); DateTime scheduled = new DateTime(date.getTime()).toDateTime(DateTimeZone.UTC); DateTime nnow = new DateTime(DateTimeZone.UTC); int bt = Minutes.minutesBetween(nnow, scheduled).getMinutes(); logger.info("Scheduled joda {} diff {}", scheduled, bt); ObjectNode evJson = jackson.convertValue(ev, ObjectNode.class); if (bt > 6) { String rs = "You're a bit early, please visit this page at " + scheduled.minusMinutes(5).toString("yyyy/MM/dd HH:mm:ss 'GMT'"); return rs.getBytes(); } // if (bt < -62) { String rs = "It seems that your session has already ended or expired. Please, contact us at ceo@enitalk.com if there seems to be a mistake."; return rs.getBytes(); } String url = s3Cache.get(evJson); if (!requireUrl) { url += "?dest=" + evJson.at("/ii").asText() + "&i=" + evJson.path("ii").asText(); String signed = signer.signUrl(url, new DateTime().plusMinutes(80)); res.sendRedirect(signed); } else { return url.getBytes(); } } catch (Exception e) { logger.error(ExceptionUtils.getFullStackTrace(e)); return "Oops. Something went wrong. Contact us at ceo@enitalk.com".getBytes(); } return out; }
From source file:com.ext.portlet.epsos.EpsosHelperService.java
public static Assertion createAssertion(String username, String role, String organization, String organizationId, String facilityType, String purposeOfUse, String xspaLocality, java.util.Vector permissions) { // assertion/* w w w.j av a2 s . c om*/ Assertion assertion = null; try { DefaultBootstrap.bootstrap(); XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); SAMLObjectBuilder<Assertion> builder = (SAMLObjectBuilder<Assertion>) builderFactory .getBuilder(Assertion.DEFAULT_ELEMENT_NAME); // Create the NameIdentifier SAMLObjectBuilder nameIdBuilder = (SAMLObjectBuilder) builderFactory .getBuilder(NameID.DEFAULT_ELEMENT_NAME); NameID nameId = (NameID) nameIdBuilder.buildObject(); nameId.setValue(username); //nameId.setNameQualifier(strNameQualifier); nameId.setFormat(NameID.UNSPECIFIED); assertion = create(Assertion.class, Assertion.DEFAULT_ELEMENT_NAME); String assId = "_" + UUID.randomUUID(); assertion.setID(assId); assertion.setVersion(SAMLVersion.VERSION_20); assertion.setIssueInstant(new org.joda.time.DateTime().minusHours(3)); Subject subject = create(Subject.class, Subject.DEFAULT_ELEMENT_NAME); assertion.setSubject(subject); subject.setNameID(nameId); //Create and add Subject Confirmation SubjectConfirmation subjectConf = create(SubjectConfirmation.class, SubjectConfirmation.DEFAULT_ELEMENT_NAME); subjectConf.setMethod(SubjectConfirmation.METHOD_SENDER_VOUCHES); assertion.getSubject().getSubjectConfirmations().add(subjectConf); //Create and add conditions Conditions conditions = create(Conditions.class, Conditions.DEFAULT_ELEMENT_NAME); org.joda.time.DateTime now = new org.joda.time.DateTime(); conditions.setNotBefore(now.minusMinutes(1)); conditions.setNotOnOrAfter(now.plusHours(2)); // According to Spec assertion.setConditions(conditions); // AudienceRestriction ar = create(AudienceRestriction.class,AudienceRestriction.DEFAULT_ELEMENT_NAME); // Audience aud = create(Audience.class,Audience.DEFAULT_ELEMENT_NAME); // aud.setAudienceURI("aaa"); // conditions.s Issuer issuer = new IssuerBuilder().buildObject(); issuer.setValue("urn:idp:countryB"); issuer.setNameQualifier("urn:epsos:wp34:assertions"); assertion.setIssuer(issuer); //Add and create the authentication statement AuthnStatement authStmt = create(AuthnStatement.class, AuthnStatement.DEFAULT_ELEMENT_NAME); authStmt.setAuthnInstant(now.minusHours(2)); assertion.getAuthnStatements().add(authStmt); //Create and add AuthnContext AuthnContext ac = create(AuthnContext.class, AuthnContext.DEFAULT_ELEMENT_NAME); AuthnContextClassRef accr = create(AuthnContextClassRef.class, AuthnContextClassRef.DEFAULT_ELEMENT_NAME); accr.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX); ac.setAuthnContextClassRef(accr); authStmt.setAuthnContext(ac); AttributeStatement attrStmt = create(AttributeStatement.class, AttributeStatement.DEFAULT_ELEMENT_NAME); // XSPA Subject Attribute attrPID = createAttribute(builderFactory, "XSPA subject", "urn:oasis:names:tc:xacml:1.0:subject:subject-id", username, "", ""); attrStmt.getAttributes().add(attrPID); // XSPA Role Attribute attrPID_1 = createAttribute(builderFactory, "XSPA role", "urn:oasis:names:tc:xacml:2.0:subject:role", role, "", ""); attrStmt.getAttributes().add(attrPID_1); // HITSP Clinical Speciality /* Attribute attrPID_2 = createAttribute(builderFactory,"HITSP Clinical Speciality", "urn:epsos:names:wp3.4:subject:clinical-speciality",role,"",""); attrStmt.getAttributes().add(attrPID_2); */ // XSPA Organization Attribute attrPID_3 = createAttribute(builderFactory, "XSPA Organization", "urn:oasis:names:tc:xspa:1.0:subject:organization", organization, "", ""); attrStmt.getAttributes().add(attrPID_3); // XSPA Organization ID Attribute attrPID_4 = createAttribute(builderFactory, "XSPA Organization ID", "urn:oasis:names:tc:xspa:1.0:subject:organization-id", organizationId, "AA", ""); attrStmt.getAttributes().add(attrPID_4); // // On behalf of // Attribute attrPID_4 = createAttribute(builderFactory,"OnBehalfOf", // "urn:epsos:names:wp3.4:subject:on-behalf-of",organizationId,role,""); // attrStmt.getAttributes().add(attrPID_4); // epSOS Healthcare Facility Type Attribute attrPID_5 = createAttribute(builderFactory, "epSOS Healthcare Facility Type", "urn:epsos:names:wp3.4:subject:healthcare-facility-type", facilityType, "", ""); attrStmt.getAttributes().add(attrPID_5); // XSPA Purpose of Use Attribute attrPID_6 = createAttribute(builderFactory, "XSPA Purpose Of Use", "urn:oasis:names:tc:xspa:1.0:subject:purposeofuse", purposeOfUse, "", ""); attrStmt.getAttributes().add(attrPID_6); // XSPA Locality Attribute attrPID_7 = createAttribute(builderFactory, "XSPA Locality", "urn:oasis:names:tc:xspa:1.0:environment:locality", xspaLocality, "", ""); attrStmt.getAttributes().add(attrPID_7); // HL7 Permissions Attribute attrPID_8 = createAttribute(builderFactory, "Hl7 Permissions", "urn:oasis:names:tc:xspa:1.0:subject:hl7:permission"); Iterator itr = permissions.iterator(); while (itr.hasNext()) { attrPID_8 = AddAttributeValue(builderFactory, attrPID_8, itr.next().toString(), "", ""); } attrStmt.getAttributes().add(attrPID_8); assertion.getStatements().add(attrStmt); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } return assertion; }
From source file:com.marand.thinkmed.medications.service.impl.MedicationsServiceImpl.java
License:Open Source License
@Override @Transactional(readOnly = true)/* ww w . j ava 2s . co m*/ @ServiceMethod(auditing = @Auditing(level = Level.FULL)) @EhrSessioned public List<AdministrationPatientTaskDto> getAdministrationTasks(final Opt<Collection<String>> careProviderIds, final Opt<Collection<String>> patientIds, @Nonnull final Locale locale) { Preconditions.checkNotNull(locale, "locale is required"); final Map<String, PatientDisplayWithLocationDto> patientIdAndPatientWithLocationMap = getPatientDisplayWithLocationDtoMap( careProviderIds, patientIds); final AdministrationPatientTaskLimitsDto administrationLimits = MedicationPreferencesUtil .getAdministrationPatientTaskLimitsPreference(); final DateTime when = RequestContextHolder.getContext().getRequestTimestamp(); final Interval searchInterval = new Interval(when.minusMinutes(administrationLimits.getDueTaskOffset()), when.plusMinutes(administrationLimits.getFutureTaskOffset())); return medicationsTasksProvider.findAdministrationTasks(patientIdAndPatientWithLocationMap, searchInterval, administrationLimits.getMaxNumberOfTasks(), locale, when); }
From source file:com.netflix.ice.login.saml.Saml.java
License:Apache License
/** * Process an assertion and setup our session attributes *//*from w w w.j ava 2 s. co m*/ private void processAssertion(IceSession iceSession, Assertion assertion, LoginResponse lr) throws LoginMethodException { boolean foundAnAccount = false; iceSession.voidSession(); for (AttributeStatement as : assertion.getAttributeStatements()) { // iterate once to assure we set the username first for (Attribute attr : as.getAttributes()) { if (attr.getName().equals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")) { for (XMLObject groupXMLObj : attr.getAttributeValues()) { String username = groupXMLObj.getDOM().getTextContent(); iceSession.setUsername(username); } } } // iterate again for everything else for (Attribute attr : as.getAttributes()) { if (attr.getName().equals("com.netflix.ice.account")) { for (XMLObject groupXMLObj : attr.getAttributeValues()) { String allowedAccount = groupXMLObj.getDOM().getTextContent(); if (allowedAccount.equals(config.allAccounts)) { whitelistAllAccounts(iceSession); foundAnAccount = true; logger.info("Found Allow All Accounts: " + allowedAccount); break; } else { if (whitelistAccount(iceSession, allowedAccount)) { foundAnAccount = true; logger.info("Found Account: " + allowedAccount); } } } } } } //require at least one account if (!foundAnAccount) { throw new LoginMethodException( "SAML Assertion must give at least one Account as part of the Assertion"); } //set expiration date DateTime startDate = assertion.getConditions().getNotBefore(); DateTime endDate = assertion.getConditions().getNotOnOrAfter(); if (startDate == null || endDate == null) { throw new LoginMethodException("Assertion must state an expiration date"); } // Clocks may not be synchronized. startDate = startDate.minusMinutes(2); endDate = endDate.plusMinutes(2); logger.info(startDate.toCalendar(null).getTime().toString()); logger.info(endDate.toCalendar(null).getTime().toString()); lr.loginStart = startDate.toCalendar(null).getTime(); lr.loginEnd = endDate.toCalendar(null).getTime(); }
From source file:com.proofpoint.event.monitor.Monitor.java
License:Apache License
@Managed public void checkState() { DateTime startTime = now(DateTimeZone.UTC); DateTime oldestGoodDateTime = startTime.minusMinutes(maxAgeInMinutes); log.info("Checking state for monitor %s", name); if (eventStore.recentEventExists(eventType, eventPredicate, oldestGoodDateTime)) { recovered(//from w ww .ja va2s.c o m String.format("At least one event has been sent within the last %d minutes", maxAgeInMinutes)); } else { failed(String.format("Expected to have seen an event since %s (%s minutes ago), but have not", oldestGoodDateTime, maxAgeInMinutes)); } lastChecked = startTime; }
From source file:com.reclabs.recomendar.common.helpers.types.DateHelper.java
License:Open Source License
/** * Subtract to the current date the amount of that precisionType represent. * @param date The date to subtract// www.j a v a 2 s . c o m * @param amount The amount to subtract * @param precisionType The field to subtract * @return The new date */ public static Date subtract(Date date, int amount, DatePrecisionType precisionType) { DateTime jodaDate1 = new DateTime(date.getTime()); DateTime result; switch (precisionType) { case YEAR: result = jodaDate1.minusYears(amount); break; case MONTH: result = jodaDate1.minusMonths(amount); break; case DAY: result = jodaDate1.minusDays(amount); break; case HOUR: result = jodaDate1.minusHours(amount); break; case MINUTE: result = jodaDate1.minusMinutes(amount); break; case SECOND: result = jodaDate1.minusSeconds(amount); break; case MILLISECOND: result = jodaDate1.minusMillis(amount); break; default: LOGGER.warn("[Error subtract, precision value is invalid: {}]", precisionType); throw new RecIllegalArgumentException("The precision value is invalid " + precisionType); } return result.toDate(); }