List of usage examples for java.util Date toInstant
public Instant toInstant()
From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java
public Map<String, String> getMinimumOffsetValues(Connection connection, String schema, String tableName, QuoteChar quoteChar, Collection<String> offsetColumnNames) throws SQLException { Map<String, String> minOffsetValues = new HashMap<>(); final String qualifiedName = TableContextUtil.getQuotedQualifiedTableName(schema, tableName, quoteChar.getQuoteCharacter()); for (String offsetColumn : offsetColumnNames) { final String minOffsetQuery = String.format(MIN_OFFSET_VALUE_QUERY, offsetColumn, qualifiedName); try (Statement st = connection.createStatement(); ResultSet rs = st.executeQuery(minOffsetQuery)) { if (rs.next()) { String minValue = null; final int colType = rs.getMetaData().getColumnType(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX); switch (colType) { case Types.DATE: java.sql.Date date = rs.getDate(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX); if (date != null) { minValue = String.valueOf(date.toInstant().toEpochMilli()); }/* ww w . j a va2s . co m*/ break; case Types.TIME: java.sql.Time time = rs.getTime(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX); if (time != null) { minValue = String.valueOf(time.toInstant().toEpochMilli()); } break; case Types.TIMESTAMP: Timestamp timestamp = rs.getTimestamp(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX); if (timestamp != null) { final Instant instant = timestamp.toInstant(); minValue = String.valueOf(instant.toEpochMilli()); } break; default: minValue = rs.getString(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX); break; } if (minValue != null) { minOffsetValues.put(offsetColumn, minValue); } } else { LOG.warn("Unable to get minimum offset value using query {}; result set had no rows", minOffsetQuery); } } } return minOffsetValues; }
From source file:gov.va.isaac.gui.preferences.plugins.ViewCoordinatePreferencesPluginView.java
/** * //from ww w. java2 s .c o m * @param path int of the path to get the Time Options for * @param storedTimePref Long of anytime during the specific day that we want to return times for * @return populates the "times" TreeSet (time longs truncated at the "the seconds" position) * which populates Time Combo box, the truncTimeToFullTimeMap which maps the truncated times * im times TreeSet to each times full Long value. The truncTimeToFullTimeMap chooses each time * up to the second and maps it to the greatest equivalent time up to the milliseconds. * */ protected void setTimeOptions(int path, Long storedTimePref) { try { timeSelectCombo.getItems().clear(); overrideTimestamp = null; Date startDate = null, finishDate = null; if (storedTimePref != null) { StampBdb stampDb = Bdb.getStampDb(); NidSet nidSet = new NidSet(); nidSet.add(path); NidSetBI stamps = null; if (!storedTimePref.equals(getDefaultTime())) { startDate = getStartOfDay(new Date(storedTimePref)); finishDate = getEndOfDay(new Date(storedTimePref)); stamps = stampDb.getSpecifiedStamps(nidSet, startDate.getTime(), finishDate.getTime()); } else { stamps = stampDb.getSpecifiedStamps(nidSet, Long.MIN_VALUE, Long.MAX_VALUE); } truncTimeToFullTimeMap.clear(); times.clear(); HashSet<Integer> stampSet = stamps.getAsSet(); Date d = new Date(storedTimePref); if (dateIsLocalDate(d)) { // Get stamps of day Date todayStartDate = getStartOfDay(new Date()); Date todayFinishDate = getEndOfDay(new Date()); NidSetBI todayStamps = stampDb.getSpecifiedStamps(nidSet, todayStartDate.getTime(), todayFinishDate.getTime()); // If have stamps, no action, if not, show Latest and set stamps to latest stamp we have in stampset if (todayStamps.size() == 0) { // timeSelectCombo.getItems().add(Long.MAX_VALUE); NidSetBI allStamps = stampDb.getSpecifiedStamps(nidSet, Long.MIN_VALUE, Long.MAX_VALUE); HashSet<Integer> allStampSet = allStamps.getAsSet(); SortedSet<Integer> s = new TreeSet<Integer>(allStampSet); if (!s.isEmpty()) { Integer stampToSet = s.last(); overrideTimestamp = stampDb.getPosition(stampToSet).getTime(); timeSelectCombo.getItems().add(Long.MAX_VALUE); timeSelectCombo.setValue(Long.MAX_VALUE); } } } this.pathDatesList.add(LocalDate.now()); if (overrideTimestamp == null) { if (!stampSet.isEmpty()) { enableTimeCombo(true); for (Integer thisStamp : stampSet) { Long fullTime = null; Date stampDate; LocalDate stampInstant = null; try { fullTime = stampDb.getPosition(thisStamp).getTime(); stampDate = new Date(fullTime); stampInstant = stampDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); } catch (Exception e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(new Date(fullTime)); cal.set(Calendar.MILLISECOND, 0); //Strip milliseconds Long truncTime = cal.getTimeInMillis(); this.pathDatesList.add(stampInstant); //Build DatePicker times.add(truncTime); //This can probably go, we don't populate hashmap like this at initialization timeSelectCombo.getItems().add(truncTime); if (truncTimeToFullTimeMap.containsKey(truncTime)) { //Build Truncated Time to Full Time HashMap //If truncTimeToFullTimeMap has this key, is the value the newest time in milliseconds? if (new Date(truncTimeToFullTimeMap.get(truncTime)).before(new Date(fullTime))) { truncTimeToFullTimeMap.put(truncTime, fullTime); } } else { truncTimeToFullTimeMap.put(truncTime, fullTime); } } } else { // disableTimeCombo(true); // timeSelectCombo.getItems().add(Long.MAX_VALUE); timeSelectCombo.setValue(Long.MAX_VALUE); enableTimeCombo(true); // logger.error("Could not retreive any Stamps"); } } } } catch (Exception e) { logger.error("Error setting the default Time Dropdown"); e.printStackTrace(); } }
From source file:net.nikr.eve.jeveasset.gui.tabs.tracker.TrackerTab.java
private LocalDate dateToLocalDate(Date date) { Instant instant = date.toInstant(); return LocalDateTime.ofInstant(instant, ZoneId.of("GMT")).toLocalDate(); }
From source file:gov.va.isaac.gui.preferences.plugins.ViewCoordinatePreferencesPluginView.java
@Override public Region getContent() { if (hBox == null) { VBox statedInferredToggleGroupVBox = new VBox(); statedInferredToggleGroupVBox.setSpacing(4.0); //Instantiate Everything pathComboBox = new ComboBox<>(); //Path statedInferredToggleGroup = new ToggleGroup(); //Stated / Inferred List<RadioButton> statedInferredOptionButtons = new ArrayList<>(); datePicker = new DatePicker(); //Date timeSelectCombo = new ComboBox<Long>(); //Time //Radio buttons for (StatedInferredOptions option : StatedInferredOptions.values()) { RadioButton optionButton = new RadioButton(); if (option == StatedInferredOptions.STATED) { optionButton.setText("Stated"); } else if (option == StatedInferredOptions.INFERRED_THEN_STATED) { optionButton.setText("Inferred Then Stated"); } else if (option == StatedInferredOptions.INFERRED) { optionButton.setText("Inferred"); } else { throw new RuntimeException("oops"); }/*from w w w. jav a2 s.co m*/ optionButton.setUserData(option); optionButton.setTooltip( new Tooltip("Default StatedInferredOption is " + getDefaultStatedInferredOption())); statedInferredToggleGroup.getToggles().add(optionButton); statedInferredToggleGroupVBox.getChildren().add(optionButton); statedInferredOptionButtons.add(optionButton); } statedInferredToggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) { currentStatedInferredOptionProperty.set((StatedInferredOptions) newValue.getUserData()); } }); //Path Combo Box pathComboBox.setCellFactory(new Callback<ListView<UUID>, ListCell<UUID>>() { @Override public ListCell<UUID> call(ListView<UUID> param) { final ListCell<UUID> cell = new ListCell<UUID>() { @Override protected void updateItem(UUID c, boolean emptyRow) { super.updateItem(c, emptyRow); if (c == null) { setText(null); } else { String desc = OTFUtility.getDescription(c); setText(desc); } } }; return cell; } }); pathComboBox.setButtonCell(new ListCell<UUID>() { // Don't know why this should be necessary, but without this the UUID itself is displayed @Override protected void updateItem(UUID c, boolean emptyRow) { super.updateItem(c, emptyRow); if (emptyRow) { setText(""); } else { String desc = OTFUtility.getDescription(c); setText(desc); } } }); pathComboBox.setOnAction((event) -> { if (!pathComboFirstRun) { UUID selectedPath = pathComboBox.getSelectionModel().getSelectedItem(); if (selectedPath != null) { int path = OTFUtility.getConceptVersion(selectedPath).getPathNid(); StampBdb stampDb = Bdb.getStampDb(); NidSet nidSet = new NidSet(); nidSet.add(path); //TODO: Make this multi-threaded and possibly implement setTimeOptions() here also NidSetBI stamps = stampDb.getSpecifiedStamps(nidSet, Long.MIN_VALUE, Long.MAX_VALUE); pathDatesList.clear(); // disableTimeCombo(true); timeSelectCombo.setValue(Long.MAX_VALUE); for (Integer thisStamp : stamps.getAsSet()) { try { Position stampPosition = stampDb.getPosition(thisStamp); this.stampDate = new Date(stampPosition.getTime()); stampDateInstant = stampDate.toInstant().atZone(ZoneId.systemDefault()) .toLocalDate(); this.pathDatesList.add(stampDateInstant); //Build DatePicker } catch (Exception e) { e.printStackTrace(); } } datePicker.setValue(LocalDate.now()); } } else { pathComboFirstRun = false; } }); pathComboBox.setTooltip( new Tooltip("Default path is \"" + OTFUtility.getDescription(getDefaultPath()) + "\"")); //Calendar Date Picker final Callback<DatePicker, DateCell> dayCellFactory = new Callback<DatePicker, DateCell>() { @Override public DateCell call(final DatePicker datePicker) { return new DateCell() { @Override public void updateItem(LocalDate thisDate, boolean empty) { super.updateItem(thisDate, empty); if (pathDatesList != null) { if (pathDatesList.contains(thisDate)) { setDisable(false); } else { setDisable(true); } } } }; } }; datePicker.setDayCellFactory(dayCellFactory); datePicker.setOnAction((event) -> { if (!datePickerFirstRun) { UUID selectedPath = pathComboBox.getSelectionModel().getSelectedItem(); Instant instant = Instant.from(datePicker.getValue().atStartOfDay(ZoneId.systemDefault())); Long dateSelected = Date.from(instant).getTime(); if (selectedPath != null && dateSelected != 0) { int path = OTFUtility.getConceptVersion(selectedPath).getPathNid(); setTimeOptions(path, dateSelected); try { timeSelectCombo.setValue(times.first()); //Default Dropdown Value } catch (Exception e) { // Eat it.. like a sandwich! TODO: Create Read Only Property Conditional for checking if Time Combo is disabled // Right now, Sometimes Time Combo is disabled, so we catch this and eat it // Otherwise make a conditional from the Read Only Boolean Property to check first } } else { disableTimeCombo(false); logger.debug("The path isn't set or the date isn't set. Both are needed right now"); } } else { datePickerFirstRun = false; } }); //Commit-Time ComboBox timeSelectCombo.setMinWidth(200); timeSelectCombo.setCellFactory(new Callback<ListView<Long>, ListCell<Long>>() { @Override public ListCell<Long> call(ListView<Long> param) { final ListCell<Long> cell = new ListCell<Long>() { @Override protected void updateItem(Long item, boolean emptyRow) { super.updateItem(item, emptyRow); if (item == null) { setText(""); } else { if (item == Long.MAX_VALUE) { setText("LATEST TIME"); } else { setText(timeFormatter.format(new Date(item))); } } } }; return cell; } }); timeSelectCombo.setButtonCell(new ListCell<Long>() { @Override protected void updateItem(Long item, boolean emptyRow) { super.updateItem(item, emptyRow); if (item == null) { setText(""); } else { if (item == Long.MAX_VALUE) { setText("LATEST TIME"); } else { setText(timeFormatter.format(new Date(item))); } } } }); try { currentPathProperty.bind(pathComboBox.getSelectionModel().selectedItemProperty()); //Set Path Property currentTimeProperty.bind(timeSelectCombo.getSelectionModel().selectedItemProperty()); } catch (Exception e) { e.printStackTrace(); } // DEFAULT VALUES UserProfile loggedIn = ExtendedAppContext.getCurrentlyLoggedInUserProfile(); storedTimePref = loggedIn.getViewCoordinateTime(); storedPathPref = loggedIn.getViewCoordinatePath(); if (storedPathPref != null) { pathComboBox.getItems().clear(); //Set the path Dates by default pathComboBox.getItems().addAll(getPathOptions()); final UUID storedPath = getStoredPath(); if (storedPath != null) { pathComboBox.getSelectionModel().select(storedPath); } if (storedTimePref != null) { final Long storedTime = loggedIn.getViewCoordinateTime(); Calendar cal = Calendar.getInstance(); cal.setTime(new Date(storedTime)); cal.set(Calendar.MILLISECOND, 0); //Strip milliseconds Long storedTruncTime = cal.getTimeInMillis(); if (!storedTime.equals(Long.MAX_VALUE)) { //***** FIX THIS, not checking default vc time value int path = OTFUtility.getConceptVersion(storedPathPref).getPathNid(); setTimeOptions(path, storedTimePref); timeSelectCombo.setValue(storedTruncTime); // timeSelectCombo.getItems().addAll(getTimeOptions()); //The correct way, but doesen't work Date storedDate = new Date(storedTime); datePicker.setValue(storedDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()); } else { datePicker.setValue(LocalDate.now()); timeSelectCombo.getItems().addAll(Long.MAX_VALUE); //The correct way, but doesen't work timeSelectCombo.setValue(Long.MAX_VALUE); // disableTimeCombo(false); } } else { //Stored Time Pref == null logger.error("ERROR: Stored Time Preference = null"); } } else { //Stored Path Pref == null logger.error("We could not load a stored path, ISAAC cannot run"); throw new Error("No stored PATH could be found. ISAAC can't run without a path"); } GridPane gridPane = new GridPane(); gridPane.setHgap(10); gridPane.setVgap(10); Label pathLabel = new Label("View Coordinate Path"); gridPane.add(pathLabel, 0, 0); //Path Label - Row 0 GridPane.setHalignment(pathLabel, HPos.LEFT); gridPane.add(statedInferredToggleGroupVBox, 1, 0, 1, 2); //--Row 0, span 2 gridPane.add(pathComboBox, 0, 1); //Path Combo box - Row 2 GridPane.setValignment(pathComboBox, VPos.TOP); Label datePickerLabel = new Label("View Coordinate Dates"); gridPane.add(datePickerLabel, 0, 2); //Row 3 GridPane.setHalignment(datePickerLabel, HPos.LEFT); gridPane.add(datePicker, 0, 3); //Row 4 Label timeSelectLabel = new Label("View Coordinate Times"); gridPane.add(timeSelectLabel, 1, 2); //Row 3 GridPane.setHalignment(timeSelectLabel, HPos.LEFT); gridPane.add(timeSelectCombo, 1, 3); //Row 4 // FOR DEBUGGING CURRENTLY SELECTED PATH, TIME AND POLICY /* UserProfile userProfile = ExtendedAppContext.getCurrentlyLoggedInUserProfile(); StatedInferredOptions chosenPolicy = userProfile.getStatedInferredPolicy(); UUID chosenPathUuid = userProfile.getViewCoordinatePath(); Long chosenTime = userProfile.getViewCoordinateTime(); Label printSelectedPathLabel = new Label("Path: " + OTFUtility.getDescription(chosenPathUuid)); gridPane.add(printSelectedPathLabel, 0, 4); GridPane.setHalignment(printSelectedPathLabel, HPos.LEFT); Label printSelectedTimeLabel = null; if(chosenTime != getDefaultTime()) { printSelectedTimeLabel = new Label("Time: " + dateFormat.format(new Date(chosenTime))); } else { printSelectedTimeLabel = new Label("Time: LONG MAX VALUE"); } gridPane.add(printSelectedTimeLabel, 1, 4); GridPane.setHalignment(printSelectedTimeLabel, HPos.LEFT); Label printSelectedPolicyLabel = new Label("Policy: " + chosenPolicy); gridPane.add(printSelectedPolicyLabel, 2, 4); GridPane.setHalignment(printSelectedPolicyLabel, HPos.LEFT); */ hBox = new HBox(); hBox.getChildren().addAll(gridPane); allValid_ = new ValidBooleanBinding() { { bind(currentStatedInferredOptionProperty, currentPathProperty, currentTimeProperty); setComputeOnInvalidate(true); } @Override protected boolean computeValue() { if (currentStatedInferredOptionProperty.get() == null) { this.setInvalidReason("Null/unset/unselected StatedInferredOption"); for (RadioButton button : statedInferredOptionButtons) { TextErrorColorHelper.setTextErrorColor(button); } return false; } else { for (RadioButton button : statedInferredOptionButtons) { TextErrorColorHelper.clearTextErrorColor(button); } } if (currentPathProperty.get() == null) { this.setInvalidReason("Null/unset/unselected path"); TextErrorColorHelper.setTextErrorColor(pathComboBox); return false; } else { TextErrorColorHelper.clearTextErrorColor(pathComboBox); } if (OTFUtility.getConceptVersion(currentPathProperty.get()) == null) { this.setInvalidReason("Invalid path"); TextErrorColorHelper.setTextErrorColor(pathComboBox); return false; } else { TextErrorColorHelper.clearTextErrorColor(pathComboBox); } // if(currentTimeProperty.get() == null && currentTimeProperty.get() != Long.MAX_VALUE) // { // this.setInvalidReason("View Coordinate Time is unselected"); // TextErrorColorHelper.setTextErrorColor(timeSelectCombo); // return false; // } this.clearInvalidReason(); return true; } }; } // createButton.disableProperty().bind(saveButtonValid.not())); // Reload persisted values every time final StatedInferredOptions storedStatedInferredOption = getStoredStatedInferredOption(); for (Toggle toggle : statedInferredToggleGroup.getToggles()) { if (toggle.getUserData() == storedStatedInferredOption) { toggle.setSelected(true); } } // pathComboBox.setButtonCell(new ListCell<UUID>() { // @Override // protected void updateItem(UUID c, boolean emptyRow) { // super.updateItem(c, emptyRow); // if (emptyRow) { // setText(""); // } else { // String desc = OTFUtility.getDescription(c); // setText(desc); // } // } // }); // timeSelectCombo.setButtonCell(new ListCell<Long>() { // @Override // protected void updateItem(Long item, boolean emptyRow) { // super.updateItem(item, emptyRow); // if (emptyRow) { // setText(""); // } else { // setText(timeFormatter.format(new Date(item))); // } // } // }); // datePickerFirstRun = false; // pathComboFirstRun = false; return hBox; }
From source file:org.xwiki.store.filesystem.internal.migration.R910100XWIKI14871DataMigration.java
private void storeDeletedAttachment(File directory, long id, Session session) throws ParserConfigurationException, SAXException, IOException { this.logger.info("Storing attachment metadata [{}] in the database", directory); // Find document reference File documentDirectory = directory.getParentFile().getParentFile().getParentFile(); DocumentReference documentReference = getDocumentReference(documentDirectory); if (getXWikiContext().getWikiReference().equals(documentReference.getWikiReference())) { // Parse ~DELETED_ATTACH_METADATA.xml File file = new File(directory, "~DELETED_ATTACH_METADATA.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); String filename = getElementText(doc, "filename", null); String deleter = getElementText(doc, "deleter", null); Date deleteDate = new Date(Long.valueOf(getElementText(doc, "datedeleted", null))); long docId = new XWikiDocument(documentReference).getId(); // We need to make sure the deleted attachment is not already in the database with a different id (left // there by the attachment porter script for example) Query selectQuery = session .createQuery("SELECT id FROM DeletedAttachment WHERE docId=? AND filename=? AND date=?"); selectQuery.setLong(0, docId);/*from w w w . ja va 2 s. c o m*/ selectQuery.setString(1, filename); selectQuery.setTimestamp(2, new java.sql.Timestamp(deleteDate.getTime())); Long databaseId = (Long) selectQuery.uniqueResult(); if (databaseId == null) { // Try without the milliseconds since most versions of MySQL don't support them selectQuery.setTimestamp(2, new java.sql.Timestamp(deleteDate.toInstant().getEpochSecond() * 1000)); databaseId = (Long) selectQuery.uniqueResult(); } DeletedAttachment dbAttachment; if (databaseId != null) { // Update the database metadata (probably left there by the attachment porter script) dbAttachment = new DeletedAttachment(docId, this.serializer.serialize(documentReference), filename, FileSystemStoreUtils.HINT, deleter, deleteDate, null, databaseId); session.update(dbAttachment); } else { // Insert new deleted attachment metadata in the DB dbAttachment = new DeletedAttachment(docId, this.serializer.serialize(documentReference), filename, FileSystemStoreUtils.HINT, deleter, deleteDate, null); databaseId = (Long) session.save(dbAttachment); } // Refactor file storage to be based on database id instead of date File newDirectory = new File(directory.getParentFile(), encode(dbAttachment.getFilename() + "-id" + databaseId)); FileUtils.moveDirectory(directory, newDirectory); } }
From source file:ch.algotrader.esper.EngineImpl.java
@Override public void addTimerCallback(Date dateTime, String name, Consumer<Date> consumer) { // execute callback immediately if dateTime is in the past if (dateTime.compareTo(getCurrentTime()) < 0) { consumer.accept(getCurrentTime()); } else {// w w w. ja v a2 s .co m String alias = "ON_TIMER_" + DateTimeUtil.formatAsGMT(dateTime.toInstant()).replace(" ", "_").replace(":", "-") + (name != null ? "_" + name : ""); Calendar cal = Calendar.getInstance(); cal.setTime(dateTime); Object[] params = { alias, cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.SECOND), cal.get(Calendar.YEAR) }; deployStatement("prepared", "ON_TIMER", alias, params, new TimerCallback(this, alias, consumer), true); } }
From source file:org.eclipse.smarthome.ui.internal.chart.defaultchartprovider.DefaultChartProvider.java
boolean addItem(Chart chart, QueryablePersistenceService service, Date timeBegin, Date timeEnd, Item item, int seriesCounter, ChartTheme chartTheme, int dpi) { Color color = chartTheme.getLineColor(seriesCounter); // Get the item label String label = null;/* w ww . j a va2 s. co m*/ if (itemUIRegistry != null) { // Get the item label label = itemUIRegistry.getLabel(item.getName()); if (label != null && label.contains("[") && label.contains("]")) { label = label.substring(0, label.indexOf('[')); } } if (label == null) { label = item.getName(); } Iterable<HistoricItem> result; FilterCriteria filter; // Generate data collections List<Date> xData = new ArrayList<Date>(); List<Number> yData = new ArrayList<Number>(); // Declare state here so it will hold the last value at the end of the process State state = null; // First, get the value at the start time. // This is necessary for values that don't change often otherwise data will start // after the start of the graph (or not at all if there's no change during the graph period) filter = new FilterCriteria(); filter.setEndDate(ZonedDateTime.ofInstant(timeBegin.toInstant(), timeZoneProvider.getTimeZone())); filter.setItemName(item.getName()); filter.setPageSize(1); filter.setOrdering(Ordering.DESCENDING); result = service.query(filter); if (result.iterator().hasNext()) { HistoricItem historicItem = result.iterator().next(); state = historicItem.getState(); xData.add(timeBegin); yData.add(convertData(state)); } // Now, get all the data between the start and end time filter.setBeginDate(ZonedDateTime.ofInstant(timeBegin.toInstant(), timeZoneProvider.getTimeZone())); filter.setEndDate(ZonedDateTime.ofInstant(timeEnd.toInstant(), timeZoneProvider.getTimeZone())); filter.setPageSize(Integer.MAX_VALUE); filter.setOrdering(Ordering.ASCENDING); // Get the data from the persistence store result = service.query(filter); Iterator<HistoricItem> it = result.iterator(); // Iterate through the data while (it.hasNext()) { HistoricItem historicItem = it.next(); // For 'binary' states, we need to replicate the data // to avoid diagonal lines if (state instanceof OnOffType || state instanceof OpenClosedType) { Calendar cal = Calendar.getInstance(); cal.setTime(historicItem.getTimestamp()); cal.add(Calendar.MILLISECOND, -1); xData.add(cal.getTime()); yData.add(convertData(state)); } state = historicItem.getState(); xData.add(historicItem.getTimestamp()); yData.add(convertData(state)); } // Lastly, add the final state at the endtime if (state != null) { xData.add(timeEnd); yData.add(convertData(state)); } // Add the new series to the chart - only if there's data elements to display // The chart engine will throw an exception if there's no data if (xData.size() == 0) { return false; } // If there's only 1 data point, plot it again! if (xData.size() == 1) { xData.add(xData.iterator().next()); yData.add(yData.iterator().next()); } Series series = chart.addSeries(label, xData, yData); float lineWidth = (float) chartTheme.getLineWidth(dpi); series.setLineStyle(new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)); series.setMarker(SeriesMarker.NONE); series.setLineColor(color); // If the start value is below the median, then count legend position down // Otherwise count up. // We use this to decide whether to put the legend in the top or bottom corner. if (yData.iterator().next().floatValue() > ((series.getYMax() - series.getYMin()) / 2 + series.getYMin())) { legendPosition++; } else { legendPosition--; } return true; }
From source file:org.sakaiproject.evaluation.logic.externals.EvalExternalLogicImpl.java
public String createScheduledJob(Date executionDate, Long evaluationId, String jobType) { String jobKey = EvalScheduledJob.encodeContextId(evaluationId, jobType); return scheduledInvocationManager.createDelayedInvocation(executionDate.toInstant(), SCHEDULER_SPRING_BEAN_ID, jobKey); }
From source file:com.diversityarrays.kdxplore.stats.DateSimpleStatistics.java
public DateSimpleStatistics(String statsName, List<KdxSample> samples, Integer nStdDevForOutlier) { super(statsName, Date.class); nSampleMeasurements = samples.size(); Bag<String> bag = new HashBag<>(); List<Long> values = new ArrayList<>(nSampleMeasurements); for (KdxSample sm : samples) { switch (TraitValue.classify(sm.getTraitValue())) { case NA:// ww w . java2 s. co m ++nNA; break; case SET: try { Date date = dateFormat.parse(sm.getTraitValue()); long millis = date.getTime(); values.add(millis); bag.add(String.valueOf(millis)); } catch (ParseException e) { ++nInvalid; } break; case MISSING: case UNSET: default: ++nMissing; break; } } nValidValues = values.size(); switch (nValidValues) { case 0: minValue = null; maxValue = null; mode = null; median = null; mean = null; variance = null; stddev = null; nOutliers = null; stderr = null; break; case 1: mean = new Date(values.get(0)); median = mean; minValue = mean; maxValue = mean; mode = dateFormat.format(mean); variance = null; stddev = null; nOutliers = null; stderr = null; break; default: Collections.sort(values); minValue = new Date(values.get(0)); maxValue = new Date(values.get(values.size() - 1)); mean = new Date((minValue.getTime() + maxValue.getTime()) / 2); long median_l = StatsUtil.computeLongMedian(values); median = new Date(median_l); List<String> modes = StatsUtil.computeMode(bag, null); StringBuilder sb = new StringBuilder(); String sep = ""; for (String s : modes) { sb.append(sep); long millis = Long.parseLong(s); Date d = new Date(millis); sb.append(dateFormat.format(d)); sep = " , "; } mode = sb.toString(); // - - - - // Now for variance, stddev, stderr, nOutliers Instant start = minValue.toInstant(); long meanDays = ChronoUnit.DAYS.between(start, mean.toInstant()); double s2 = 0; for (Long v : values) { s2 += (v - meanDays) * (v - meanDays); } variance = s2 / (nValidValues - 1); stddev = Math.sqrt(variance); stderr = stddev / Math.sqrt(nValidValues); double q1 = BoxAndWhiskerCalculator.calculateQ1(values); double q3 = BoxAndWhiskerCalculator.calculateQ3(values); int nout = 0; if (nStdDevForOutlier == null) { double interQuartileRange = q3 - q1; double lowerOutlierThreshold = q1 - (interQuartileRange * 1.5); double upperOutlierThreshold = q3 + (interQuartileRange * 1.5); for (Long value : values) { if (value < lowerOutlierThreshold) { ++nout; lowOutliers.add(new Date(value)); } else if (value > upperOutlierThreshold) { ++nout; highOutliers.add(new Date(value)); } if (lowerOutlierThreshold < value || value < upperOutlierThreshold) { ++nout; } } } else { double lowerOutlierThreshold = meanDays - (nStdDevForOutlier * stddev); double upperOutlierThreshold = meanDays + (nStdDevForOutlier * stddev); for (Long v : values) { Date d = new Date(v); long nDays = ChronoUnit.DAYS.between(start, d.toInstant()); if (nDays < lowerOutlierThreshold) { ++nout; lowOutliers.add(d); } else if (nDays > upperOutlierThreshold) { ++nout; highOutliers.add(d); } } } nOutliers = nout; break; } }