List of usage examples for org.joda.time DateTime minusSeconds
public DateTime minusSeconds(int seconds)
From source file:AuditGenerator.SeedData.java
private static void createAudit(String date, String childId, String parentId, int statusIndex, int siteId, int referringUrlId) throws SQLException, InterruptedException { String sql;/*w w w . j av a2 s. com*/ String currentSeverityId = "1"; DateTime currentTime = DateTime.now(); int randomSecond = randomGenerator.nextInt(100000); currentTime = currentTime.minusSeconds(randomSecond); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); String due = currentTime.toString(fmt); String thisSiteId = "" + siteId; if (referringUrlId == -1) { if (statusIndex == 0 || statusIndex == 1) { System.out.println("statusIndex " + statusIndex); sql = "INSERT into " + dbName + ".audits (created_at, updated_at, status, site_id, due_at, published_at,audit_type_id) VALUES ('" + date + "', '" + date + "', 'published', " + thisSiteId + ",'" + due + "', '" + date + "',1)"; } else { sql = "INSERT into " + dbName + ".audits (created_at, updated_at, status, site_id,referral_url_id, due_at,audit_type_id) VALUES ('" + date + "', '" + date + "', 'unaudited', " + thisSiteId + ",'" + due + "',1)"; } } else { if (statusIndex == 0 || statusIndex == 1) { System.out.println("statusIndex " + statusIndex); sql = "INSERT into " + dbName + ".audits (created_at, updated_at, status, site_id, referral_url_id, due_at, published_at,audit_type_id) VALUES ('" + date + "', '" + date + "', 'published', " + thisSiteId + "," + referringUrlId + ",'" + due + "', '" + date + "',1)"; } else { sql = "INSERT into " + dbName + ".audits (created_at, updated_at, status, site_id,referral_url_id, due_at,audit_type_id) VALUES ('" + date + "', '" + date + "', 'unaudited', " + thisSiteId + "," + referringUrlId + ",'" + due + "',1)"; } } //Grab audit ID from insert int auditId = sqlHandler.getSQLResponse(sql); String typePMMSQL = "INSERT INTO " + dbName + ".audit_audit_types (audit_id, audit_type_id, created_at, updated_at) VALUES (" + auditId + ", 1, '" + date + "','" + date + "')"; sqlHandler.executeStatement(typePMMSQL); ArrayList addContent = new ArrayList<String>(); addContent.add(4); Iterator it = addContent.iterator(); while (it.hasNext()) { int nextContent = (int) it.next(); String sql3 = "INSERT INTO " + dbName + ".audit_content_types (audit_id, content_type_id, created_at, updated_at) VALUES (" + auditId + ", " + nextContent + ", '" + date + "', '" + date + "')"; System.out.println(sql3); sqlHandler.executeStatement(sql3); //severities are related to content type String sql4 = "INSERT INTO " + dbName + ".audit_client_content_type_severities (audit_id, severity_id, content_type_id, client_organization_id, created_at, updated_at)" + "VALUES (" + auditId + ", " + currentSeverityId + "," + nextContent + ", " + childId + ", '" + date + "', '" + date + "')"; System.out.println(sql4); sqlHandler.executeStatement(sql4); if (parentId != null && statusIndex == 1) { String parentContentSQL = "INSERT INTO " + dbName + ".audit_client_content_type_severities (audit_id, severity_id, content_type_id, client_organization_id, created_at, updated_at)" + "VALUES (" + auditId + ", " + currentSeverityId + "," + nextContent + ", " + parentId + ", '" + date + "', '" + date + "')"; sqlHandler.executeStatement(parentContentSQL); } } if (statusIndex == 1) { String thisResolution = "cleared"; String sql5; if ("Under Review".equals(thisResolution)) { sql5 = "INSERT INTO " + dbName + ".audit_client_merchant_resolutions " + "(audit_id, severity_id, status, author_organization_id, created_at, updated_at)" + "VALUES (" + auditId + ", " + currentSeverityId + ", '" + thisResolution + "', " + childId + ", '" + date + "', '" + date + "')"; } else { sql5 = "INSERT INTO " + dbName + ".audit_client_merchant_resolutions " + "(audit_id, severity_id, status, author_organization_id, recipient_organization_id, published_at, created_at, updated_at)" + "VALUES (" + auditId + ", " + currentSeverityId + ", '" + thisResolution + "', " + childId + ", " + parentId + ", '" + date + "', '" + date + "', '" + date + "')"; } System.out.println("merchant res sql " + sql5); sqlHandler.executeStatement(sql5); } // create one or more notes Random r = new Random(); int noteCount = r.nextInt(6 - 1) + 1; for (int i = 0; i < noteCount; i++) { generateNotes(auditId, i); } generateAuditChange(auditId); }
From source file:AuditGenerator.SeedData.java
private static void createMultiAudit(String date, String childId, String parentId1, String parentId2, int statusIndex, int siteId) { String sql;/*w w w . j a va 2s.co m*/ String currentSeverityId = "1"; DateTime currentTime = DateTime.now(); int randomSecond = randomGenerator.nextInt(100000); currentTime = currentTime.minusSeconds(randomSecond); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); String due = currentTime.toString(fmt); String thisSiteId = "" + siteId; if (statusIndex == 0 || statusIndex == 1) { System.out.println("statusIndex " + statusIndex); sql = "INSERT into " + dbName + ".audits (created_at, updated_at, status, site_id, due_at, published_at) VALUES ('" + date + "', '" + date + "', 'published', " + thisSiteId + ", '" + due + "', '" + date + "')"; } else { sql = "INSERT into " + dbName + ".audits (created_at, updated_at, status, site_id, due_at) VALUES ('" + date + "', '" + date + "', 'unaudited', " + thisSiteId + ", '" + due + "')"; } //Grab audit ID from insert int auditId = sqlHandler.getSQLResponse(sql); String typePMMSQL = "INSERT INTO " + dbName + ".audit_audit_types (audit_id, audit_type_id, created_at, updated_at) VALUES (" + auditId + ", 1, '" + date + "','" + date + "')"; sqlHandler.executeStatement(typePMMSQL); ArrayList addContent = new ArrayList<String>(); addContent.add(4); Iterator it = addContent.iterator(); while (it.hasNext()) { int nextContent = (int) it.next(); String sql3 = "INSERT INTO " + dbName + ".audit_content_types (audit_id, content_type_id, created_at, updated_at) VALUES (" + auditId + ", " + nextContent + ", '" + date + "', '" + date + "')"; System.out.println(sql3); sqlHandler.executeStatement(sql3); //severities are related to content type String sql4 = "INSERT INTO " + dbName + ".audit_client_content_type_severities (audit_id, severity_id, content_type_id, client_organization_id, created_at, updated_at)" + "VALUES (" + auditId + ", " + currentSeverityId + "," + nextContent + ", " + childId + ", '" + date + "', '" + date + "')"; System.out.println(sql4); sqlHandler.executeStatement(sql4); if (parentId1 != null && statusIndex == 1) { String parentContentSQL = "INSERT INTO " + dbName + ".audit_client_content_type_severities (audit_id, severity_id, content_type_id, client_organization_id, created_at, updated_at)" + "VALUES (" + auditId + ", " + currentSeverityId + "," + nextContent + ", " + parentId1 + ", '" + date + "', '" + date + "')"; String parentContent2SQL = "INSERT INTO " + dbName + ".audit_client_content_type_severities (audit_id, severity_id, content_type_id, client_organization_id, created_at, updated_at)" + "VALUES (" + auditId + ", " + currentSeverityId + "," + nextContent + ", " + parentId2 + ", '" + date + "', '" + date + "')"; sqlHandler.executeStatement(parentContentSQL); sqlHandler.executeStatement(parentContent2SQL); } } if (statusIndex == 1) { String thisResolution = "cleared"; String sql5, sql6; if ("Under Review".equals(thisResolution)) { sql5 = "INSERT INTO " + dbName + ".audit_client_merchant_resolutions " + "(audit_id, severity_id, status, author_organization_id, created_at, updated_at)" + "VALUES (" + auditId + ", " + currentSeverityId + ", '" + thisResolution + "', " + childId + ", '" + date + "', '" + date + "')"; sql6 = ""; } else { sql5 = "INSERT INTO " + dbName + ".audit_client_merchant_resolutions " + "(audit_id, severity_id, status, author_organization_id, recipient_organization_id, published_at, created_at, updated_at)" + "VALUES (" + auditId + ", " + currentSeverityId + ", '" + thisResolution + "', " + childId + ", " + parentId1 + ", '" + date + "', '" + date + "', '" + date + "')"; sql6 = "INSERT INTO " + dbName + ".audit_client_merchant_resolutions " + "(audit_id, severity_id, status, author_organization_id, recipient_organization_id, published_at, created_at, updated_at)" + "VALUES (" + auditId + ", " + currentSeverityId + ", '" + thisResolution + "', " + childId + ", " + parentId2 + ", '" + date + "', '" + date + "', '" + date + "')"; } System.out.println("merchant res sql " + sql5); sqlHandler.executeStatement(sql5); sqlHandler.executeStatement(sql6); } }
From source file:be.e_contract.jwatchdog.datasource.rrd.RRDDatasource.java
License:Open Source License
@Override public double[] getValues(int minutes) { LOG.debug("RRD file: " + this.rrdFile); RRDatabase rrd;/*from w ww. j a v a 2 s . c o m*/ try { rrd = new RRDatabase(this.rrdFile); } catch (IOException e) { throw new RuntimeException("RRD IO error: " + e.getMessage()); } try { DateTime lastUpdate = new DateTime(rrd.getLastUpdate()); LOG.debug("last update: " + lastUpdate); DateTime now = new DateTime(); if (lastUpdate.isBefore(now.minusMinutes(minutes))) { LOG.warn("RRD outdated"); } Header header = rrd.getHeader(); int primaryDataPointInterval = header.getPDPStep(); DateTime endDateTime = lastUpdate.minusSeconds(primaryDataPointInterval); DateTime startDateTime = endDateTime.minusMinutes(minutes); DataChunk dataChunk; try { dataChunk = rrd.getData(ConsolidationFunctionType.AVERAGE, startDateTime.toDate(), endDateTime.toDate(), primaryDataPointInterval); } catch (IOException e) { throw new RuntimeException("RRD IO error: " + e.getMessage()); } double[][] data = dataChunk.getData(); Set<String> dataSourceNames = rrd.getDataSourcesName(); LOG.debug("RRD datasources: " + dataSourceNames); int dsIdx; if (null != this.datasourceName) { if (!dataSourceNames.contains(this.datasourceName)) { LOG.warn("RRD datasource name not found: " + this.datasourceName); return new double[] {}; } int size = dataSourceNames.size(); for (dsIdx = 0; dsIdx < size; dsIdx++) { DataSource dataSource = rrd.getDataSource(dsIdx); if (dataSource.getName().equals(this.datasourceName)) { break; } } } else { dsIdx = 0; } double[] values = new double[data.length]; for (int idx = 0; idx < data.length; idx++) { values[data.length - idx - 1] = data[idx][dsIdx]; } return values; } finally { try { rrd.close(); } catch (IOException e) { LOG.error("error closing RRD: " + e.getMessage()); } } }
From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java
License:Apache License
/** * Quick create an event.//from w w w. j a va 2 s . c o m * * @param start * the start * @param end * the end * @param summary * the summary * @param location * the location * @param calendarId * the calendar id * @return the object node * @throws Exception * the exception */ public ObjectNode createEventQuick(@Optional @Name("start") String start, @Optional @Name("end") String end, @Optional @Name("summary") final String summary, @Optional @Name("location") final String location, @Optional @Name("calendarId") final String calendarId) throws Exception { final ObjectNode event = JOM.createObjectNode(); if (start == null) { // set start to current time, rounded to hours DateTime startDate = DateTime.now(); startDate = startDate.plusHours(1); startDate = startDate.minusMinutes(startDate.getMinuteOfHour()); startDate = startDate.minusSeconds(startDate.getSecondOfMinute()); startDate = startDate.minusMillis(startDate.getMillisOfSecond()); start = startDate.toString(); } final ObjectNode startObj = JOM.createObjectNode(); startObj.put("dateTime", start); event.put("start", startObj); if (end == null) { // set end to start +1 hour final DateTime startDate = new DateTime(start); final DateTime endDate = startDate.plusHours(1); end = endDate.toString(); } final ObjectNode endObj = JOM.createObjectNode(); endObj.put("dateTime", end); event.put("end", endObj); if (summary != null) { event.put("summary", summary); } if (location != null) { event.put("location", location); } return createEvent(event, calendarId); }
From source file:com.almende.eve.agent.MeetingAgent.java
License:Apache License
/** * Get the timestamp rounded to the next half hour * /*from w w w . jav a2 s. c o m*/ * @return */ private DateTime getNextHalfHour() { DateTime next = DateTime.now(); next = next.minusMillis(next.getMillisOfSecond()); next = next.minusSeconds(next.getSecondOfMinute()); if (next.getMinuteOfHour() > 30) { next = next.minusMinutes(next.getMinuteOfHour()); next = next.plusMinutes(60); } else { next = next.minusMinutes(next.getMinuteOfHour()); next = next.plusMinutes(30); } return next; }
From source file:com.boundary.metrics.vmware.poller.VMwarePerfPoller.java
License:Apache License
/** * Extracts performance metrics from Managed Objects on the monitored entity * // www . jav a 2 s. c o m * @throws MalformedURLException Bad URL * @throws RemoteException Endpoint exception * @throws InvalidPropertyFaultMsg Bad Property * @throws RuntimeFaultFaultMsg Runtime error * @throws SOAPFaultException WebServer error */ public void collectPerformanceData() throws MalformedURLException, RemoteException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, SOAPFaultException { ManagedObjectReference root = client.getServiceContent().getRootFolder(); // 'now' according to the server DateTime now = TimeUtils.toDateTime(client.getVimPort().currentTime(client.getServiceInstanceReference())); Duration serverSkew = new Duration(now, new DateTime()); if (serverSkew.isLongerThan(Duration.standardSeconds(1)) && (skew == null || skew.getStandardSeconds() != serverSkew.getStandardSeconds())) { LOG.warn("Server {} and local time skewed by {} seconds", client.getHost(), serverSkew.getStandardSeconds()); skew = serverSkew; } if (lastPoll == null) { lastPoll = now.minusSeconds(20); } // Holder for all our newly found measurements // TODO set an upper size limit on measurements list List<Measurement> measurements = Lists.newArrayList(); /* * A {@link PerfMetricId} consistents of the performance counter and * the instance it applies to. * * In our particular case we are requesting for all of the instances * associated with the performance counter. * * Will this work when we have a mix of VirtualMachine, HostSystem, and DataSource * managed objects. * */ List<PerfMetricId> perfMetricIds = Lists.newArrayList(); for (String counterName : metrics.keySet()) { if (this.performanceCounterMap.containsKey(counterName)) { PerfMetricId metricId = new PerfMetricId(); /* Get the ID for this counter. */ metricId.setCounterId(this.performanceCounterMap.get(counterName)); metricId.setInstance("*"); perfMetricIds.add(metricId); } } GetMOREF getMOREFs = new GetMOREF(client); Map<String, ManagedObjectReference> entities = getMOREFs.inFolderByType(root, "VirtualMachine"); for (Map.Entry<String, ManagedObjectReference> entity : entities.entrySet()) { ManagedObjectReference mor = entity.getValue(); String entityName = entity.getKey(); /* * Create the query specification for queryPerf(). * Specify 5 minute rollup interval and CSV output format. */ PerfQuerySpec querySpec = new PerfQuerySpec(); querySpec.setEntity(mor); querySpec.setIntervalId(20); querySpec.setFormat("normal"); querySpec.setStartTime(TimeUtils.toXMLGregorianCalendar(lastPoll)); querySpec.setEndTime(TimeUtils.toXMLGregorianCalendar(now)); querySpec.getMetricId().addAll(perfMetricIds); LOG.info("Entity: {}, MOR: {}-{}, Interval: {}, Format: {}, MetricIds: {}, Start: {}, End: {}", entityName, mor.getType(), mor.getValue(), querySpec.getIntervalId(), querySpec.getFormat(), FluentIterable.from(perfMetricIds).transform(toStringFunction), lastPoll, now); List<PerfEntityMetricBase> retrievedStats = client.getVimPort() .queryPerf(client.getServiceContent().getPerfManager(), ImmutableList.of(querySpec)); /* * Cycle through the PerfEntityMetricBase objects. Each object contains * a set of statistics for a single ManagedEntity. */ for (PerfEntityMetricBase singleEntityPerfStats : retrievedStats) { if (singleEntityPerfStats instanceof PerfEntityMetric) { PerfEntityMetric entityStats = (PerfEntityMetric) singleEntityPerfStats; List<PerfMetricSeries> metricValues = entityStats.getValue(); List<PerfSampleInfo> sampleInfos = entityStats.getSampleInfo(); for (int x = 0; x < metricValues.size(); x++) { PerfMetricIntSeries metricReading = (PerfMetricIntSeries) metricValues.get(x); PerfCounterInfo metricInfo = performanceCounterInfoMap .get(metricReading.getId().getCounterId()); String metricFullName = toFullName.apply(metricInfo); if (!sampleInfos.isEmpty()) { PerfSampleInfo sampleInfo = sampleInfos.get(0); DateTime sampleTime = TimeUtils.toDateTime(sampleInfo.getTimestamp()); Number sampleValue = metricReading.getValue().iterator().next(); if (skew != null) { sampleTime = sampleTime.plusSeconds((int) skew.getStandardSeconds()); } if (metricReading.getValue().size() > 1) { LOG.warn("Metric {} has more than one value, only using the first", metricFullName); } String source = client.getName() + "-" + entityName; if (metricInfo.getUnitInfo().getKey().equalsIgnoreCase("kiloBytes")) { sampleValue = (long) sampleValue * 1024; // Convert KB to Bytes } else if (metricInfo.getUnitInfo().getKey().equalsIgnoreCase("percent")) { // Convert hundredth of a percent to a decimal percent sampleValue = new Long((long) sampleValue).doubleValue() / 10000.0; } String name = metrics.get(metricFullName).getName(); if (name != null) { Measurement measurement = Measurement.builder().setMetric(name).setSource(source) .setTimestamp(sampleTime).setMeasurement(sampleValue).build(); measurements.add(measurement); LOG.info("{} @ {} = {} {}", metricFullName, sampleTime, sampleValue, metricInfo.getUnitInfo().getKey()); } else { LOG.warn("Skipping collection of metric: {}", metricFullName); } } else { LOG.warn("Didn't receive any samples when polling for {} on {} between {} and {}", metricFullName, client.getHost(), lastPoll, now); } } } else { LOG.error("Unrecognized performance entry type received: {}, ignoring", singleEntityPerfStats.getClass().getName()); } } } // Send metrics if (!measurements.isEmpty()) { metricsClient.addMeasurements(measurements); } else { LOG.warn("No measurements collected in last poll for {}", client.getHost()); } // Reset lastPoll time lastPoll = now; }
From source file:com.cronutils.model.time.ExecutionTime.java
License:Apache License
/** * Provide nearest date for last execution. * @param date - jodatime DateTime instance. If null, a NullPointerException will be raised. * @return DateTime instance, never null. Last execution time. *///from w w w.ja v a2s. co m public DateTime lastExecution(DateTime date) { Validate.notNull(date); try { DateTime previousMatch = previousClosestMatch(date); if (previousMatch.equals(date)) { previousMatch = previousClosestMatch(date.minusSeconds(1)); } return previousMatch; } catch (NoSuchValueException e) { throw new IllegalArgumentException(e); } }
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.eucalyptus.simpleworkflow.common.client.WorkflowTimer.java
License:Open Source License
static List<WorkflowStarter> markAndGetRepeatingStarters() { try {/*from w ww .jav a2 s . c om*/ final List<WorkflowStarter> starters = Lists.newArrayList(); listRepeatingWorkflows().stream().forEach((impl) -> { try { final Repeating ats = Ats.inClassHierarchy(impl).get(Repeating.class); if (Topology.isEnabled(ats.dependsOn())) { final Long lastRun = lastExecution.get(impl); if (lastRun != null) { final DateTime now = new DateTime(System.currentTimeMillis()); final DateTime sleepBegin = now.minusSeconds(ats.sleepSeconds()); final Interval interval = new Interval(sleepBegin, now); if (!interval.contains(new DateTime(lastRun))) { if (lastExecution.replace(impl, lastRun, System.currentTimeMillis())) { starters.add(ats.value().newInstance()); } } } } } catch (InstantiationException ex) { ; } catch (IllegalAccessException ex) { ; } }); return starters; } catch (final Exception ex) { return Lists.newArrayList(); } }
From source file:com.google.android.apps.paco.NotificationCreator.java
License:Open Source License
private void createAllNotificationsForLastMinute(long alarmTime) { DateTime alarmAsDateTime = new DateTime(alarmTime); Log.i(PacoConstants.TAG, "Creating All notifications for last minute from signaled alarmTime: " + alarmAsDateTime.toString()); List<TimeExperiment> times = ExperimentAlarms.getAllAlarmsWithinOneMinuteofNow( alarmAsDateTime.minusSeconds(59), experimentProviderUtil.getJoinedExperiments(), context); for (TimeExperiment timeExperiment : times) { timeoutNotifications(experimentProviderUtil.getNotificationsFor(timeExperiment.experiment.getId())); createNewNotificationForExperiment(context, timeExperiment, false); }/* w ww. j av a 2 s.c o m*/ }