List of usage examples for org.joda.time DateTime plus
public DateTime plus(ReadablePeriod period)
From source file:org.powertac.du.DefaultBrokerService.java
License:Apache License
public double computeEnergyPriceUtilityBuyer(ContractOffer offer, long duration) { double utility = 0; DateTime starttime = timeslotRepo.currentTimeslot().getStartTime(); LoadTimeSeries historicLoad = timeSeriesRepo.findHistoricLoadByCustomerId(offer.getCustomerId()); LoadTimeSeries loadForecastTS = forecast.calculateLoadForecast(historicLoad, starttime, starttime.plus(duration)); utility += loadForecastTS.getTotalLoad() * (reservationEnergyPrice - offer.getEnergyPrice()); // total // expected//from w w w . j a v a2 s . c o m // energy // cost // TIME DISCOUNTING utility = utility * Math.pow(timeDiscountingFactor, getRound(offer)); return utility; }
From source file:org.powertac.du.DefaultBrokerService.java
License:Apache License
public double computeEnergyPriceUtilitySeller(ContractOffer offer, long duration) { double utility = 0; DateTime starttime = timeslotRepo.currentTimeslot().getStartTime(); LoadTimeSeries historicLoad = timeSeriesRepo.findHistoricLoadByCustomerId(offer.getCustomerId()); LoadTimeSeries loadForecastTS = forecast.calculateLoadForecast(historicLoad, starttime, starttime.plus(duration)); utility += loadForecastTS.getTotalLoad() * (offer.getEnergyPrice() - reservationEnergyPrice); // total // expected//from w ww .jav a 2 s . co m // energy // cost // TIME DISCOUNTING utility = utility * Math.pow(timeDiscountingFactor, getRound(offer)); return utility; }
From source file:org.powertac.du.DefaultBrokerService.java
License:Apache License
public double computePeakLoadPriceUtilityBuyer(ContractOffer offer, long duration) { double utility = 0; DateTime starttime = timeslotRepo.currentTimeslot().getStartTime(); LoadTimeSeries historicLoad = timeSeriesRepo.findHistoricLoadByCustomerId(offer.getCustomerId()); LoadTimeSeries loadForecastTS = forecast.calculateLoadForecast(historicLoad, starttime, starttime.plus(duration)); for (int month = 1; month <= 12; month++) { utility += loadForecastTS.getMaxLoad(month) * (reservationPeakLoadPrice - offer.getPeakLoadPrice()); // total // expected // peak/*from w ww .j a v a 2 s . c om*/ // load // fee } // TIME DISCOUNTING utility = utility * Math.pow(timeDiscountingFactor, getRound(offer)); return utility; }
From source file:org.powertac.du.DefaultBrokerService.java
License:Apache License
public double computePeakLoadPriceUtilitySeller(ContractOffer offer, long duration) { double utility = 0; DateTime starttime = timeslotRepo.currentTimeslot().getStartTime(); LoadTimeSeries historicLoad = timeSeriesRepo.findHistoricLoadByCustomerId(offer.getCustomerId()); LoadTimeSeries loadForecastTS = forecast.calculateLoadForecast(historicLoad, starttime, starttime.plus(duration)); for (int month = 1; month <= 12; month++) { utility += loadForecastTS.getMaxLoad(month) * (offer.getPeakLoadPrice() - reservationPeakLoadPrice); // total // expected // peak//from w w w .j a v a 2 s . c om // load // fee // - // fee // with // reservation // price } // TIME DISCOUNTING utility = utility * Math.pow(timeDiscountingFactor, getRound(offer)); return utility; }
From source file:org.powertac.du.DefaultBrokerService.java
License:Apache License
public double computeUtility(ContractOffer offer) { double utility = 0; LoadTimeSeries historicLoad = timeSeriesRepo.findHistoricLoadByCustomerId(offer.getCustomerId()); DateTime starttime = timeslotRepo.currentTimeslot().getStartTime(); LoadTimeSeries loadForecastTS = forecast.calculateLoadForecast(historicLoad, starttime, starttime.plus(offer.getDuration())); utility += loadForecastTS.getTotalLoad() * offer.getEnergyPrice(); // total // expected//w w w .j a v a 2s . com // energy // cost for (int month = 1; month <= 12; month++) { utility += loadForecastTS.getMaxLoad(month) * offer.getPeakLoadPrice(); // total expected peak load fee } // TODO utility for negotiation rounds, early agreement is better/worse? // gain vs. loss return utility; }
From source file:org.powertac.hamweather.Parser.java
License:Apache License
public void processFiles() { try {//from w ww . ja v a 2s . co m BufferedReader in = new BufferedReader(new FileReader(inputFile)); Pattern observation = Pattern.compile("^-- observation: ([SMTWF][a-z]+ [A-Za-z]+ \\d+ [-0-9: ]+)"); Pattern loc = Pattern.compile("^-- location: " + location); String line; State state = State.OBS; Matcher m; JSONParser jparser = new JSONParser(); DateTimeFormatter dtf = DateTimeFormat.forPattern("E MMM d HH:mm:ss Z YYYY"); iso = ISODateTimeFormat.dateTimeNoMillis(); DateTime lastObs = null; DateTime obsHour = null; while (true) { line = in.readLine(); if (null == line || 0 == line.length()) break; switch (state) { case OBS: m = observation.matcher(line); if (m.matches()) { DateTime obsTime = dtf.parseDateTime(m.group(1)); if (null == lastObs) { lastObs = obsTime; } else if (obsTime.isAfter(lastObs.plus(MAX_INTERVAL))) { System.out.println("Missed obs - last = " + iso.print(lastObs) + ", current = " + iso.print(obsTime)); } lastObs = obsTime; obsHour = obsTime.plus(HOUR / 2).withMillisOfSecond(0).withSecondOfMinute(0) .withMinuteOfHour(0); state = State.LOC; } break; case LOC: m = loc.matcher(line); if (m.matches()) { //System.out.println("Location: " + location); state = State.JSON_OB; } break; case JSON_OB: // process new observation JSONObject obs = (JSONObject) jparser.parse(line); // check for errors Boolean success = (Boolean) obs.get("success"); if (!success) { System.out.println("Observation retrieval failed at " + iso.print(obsHour)); state = State.OBS; } else { JSONObject err = (JSONObject) obs.get("error"); if (null != err) { // error at server end String msg = (String) err.get("description"); System.out.println("Observation error: " + msg + " at " + iso.print(obsHour)); state = State.OBS; } else { try { JSONObject response = (JSONObject) obs.get("response"); JSONObject ob = (JSONObject) response.get("ob"); extractObservation(ob); state = State.JSON_FCST; } catch (ClassCastException cce) { System.out.println("Faulty observation " + obs.toString()); state = State.OBS; } } } break; case JSON_FCST: // process new forecast JSONObject fcst = (JSONObject) jparser.parse(line); // check for errors Boolean success1 = (Boolean) fcst.get("success"); if (!success1) { // could not retrieve forecast System.out.println("Forecast retrieval failed at " + iso.print(obsHour)); output.forecastMissing(); } else { JSONObject err = (JSONObject) fcst.get("error"); if (null != err) { // error at server end String msg = (String) err.get("description"); System.out.println("Forecast error: " + msg + " at " + iso.print(obsHour)); output.forecastMissing(); } else { JSONArray response = (JSONArray) fcst.get("response"); if (response.size() == 0) { // should never get here System.out.println("Empty forecast at " + iso.print(obsHour)); } JSONObject periods = (JSONObject) response.get(0); JSONArray fcsts = (JSONArray) periods.get("periods"); if (fcsts.size() != FORECAST_HORIZON) { System.out.println( "Missing forecasts (" + fcsts.size() + ") at " + iso.print(lastObs)); } for (int i = 0; i < fcsts.size(); i++) { JSONObject forecast = (JSONObject) fcsts.get(i); extractForecast(forecast, i + 1, obsHour); } } } state = State.OBS; break; } } output.write(); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (org.json.simple.parser.ParseException e) { e.printStackTrace(); } }
From source file:org.qipki.crypto.x509.X509GeneratorImpl.java
License:Open Source License
@Override public X509Certificate generateX509Certificate(PrivateKey privateKey, DistinguishedName issuerDN, BigInteger serialNumber, DistinguishedName subjectDN, PublicKey publicKey, Duration validity, List<X509ExtensionHolder> x509Extensions) { try {/*w ww .ja va2s.c om*/ X509V3CertificateGenerator x509v3Generator = new X509V3CertificateGenerator(); DateTime now = new DateTime(); x509v3Generator.setSerialNumber(serialNumber); x509v3Generator.setSubjectDN(subjectDN.toX500Principal()); x509v3Generator.setIssuerDN(issuerDN.toX500Principal()); x509v3Generator.setNotBefore(now.minus(Time.CLOCK_SKEW).toDate()); x509v3Generator.setNotAfter(now.plus(validity).minus(Time.CLOCK_SKEW).toDate()); x509v3Generator.setSignatureAlgorithm(SignatureAlgorithm.SHA256withRSA.jcaString()); x509v3Generator.setPublicKey(publicKey); for (X509ExtensionHolder eachExtensionHolder : x509Extensions) { x509v3Generator.addExtension(eachExtensionHolder.getDerOID(), eachExtensionHolder.isCritical(), eachExtensionHolder.getValue()); } return x509v3Generator.generate(privateKey, cryptoContext.providerName()); } catch (GeneralSecurityException ex) { throw new CryptoFailure("Unable to generate X509Certificate", ex); } catch (IllegalStateException ex) { throw new CryptoFailure("Unable to generate X509Certificate", ex); } }
From source file:org.rhq.server.metrics.DateTimeService.java
License:Open Source License
private boolean hasTimeSliceEnded(DateTime startTime, Duration duration) { DateTime endTime = startTime.plus(duration); return DateTimeComparator.getInstance().compare(currentHour(), endTime) >= 0; }
From source file:org.sleuthkit.autopsy.timeline.ui.countsview.CountsViewPane.java
License:Open Source License
@Override protected Task<Boolean> getUpdateTask() { return new LoggedTask<Boolean>(NbBundle.getMessage(this.getClass(), "CountsViewPane.loggedTask.name"), true) {/*from w w w . j a v a 2 s. co m*/ @Override protected Boolean call() throws Exception { if (isCancelled()) { return null; } updateProgress(-1, 1); updateMessage(NbBundle.getMessage(this.getClass(), "CountsViewPane.loggedTask.prepUpdate")); Platform.runLater(() -> { setCursor(Cursor.WAIT); }); final RangeDivisionInfo rangeInfo = RangeDivisionInfo .getRangeDivisionInfo(filteredEvents.timeRange().get()); chart.setRangeInfo(rangeInfo); //extend range to block bounderies (ie day, month, year) final long lowerBound = rangeInfo.getLowerBound(); final long upperBound = rangeInfo.getUpperBound(); final Interval timeRange = new Interval( new DateTime(lowerBound, TimeLineController.getJodaTimeZone()), new DateTime(upperBound, TimeLineController.getJodaTimeZone())); int max = 0; int p = 0; // progress counter //clear old data, and reset ranges and series Platform.runLater(() -> { updateMessage(NbBundle.getMessage(this.getClass(), "CountsViewPane.loggedTask.resetUI")); eventTypeMap.clear(); dataSets.clear(); dateAxis.getCategories().clear(); DateTime start = timeRange.getStart(); while (timeRange.contains(start)) { //add bar/'category' label for the current interval final String dateString = start.toString(rangeInfo.getTickFormatter()); dateAxis.getCategories().add(dateString); //increment for next iteration start = start.plus(rangeInfo.getPeriodSize().getPeriod()); } //make all series to ensure they get created in consistent order EventType.allTypes.forEach(CountsViewPane.this::getSeries); }); DateTime start = timeRange.getStart(); while (timeRange.contains(start)) { final String dateString = start.toString(rangeInfo.getTickFormatter()); DateTime end = start.plus(rangeInfo.getPeriodSize().getPeriod()); final Interval interval = new Interval(start, end); //query for current range Map<EventType, Long> eventCounts = filteredEvents.getEventCounts(interval); //increment for next iteration start = end; int dateMax = 0; //used in max tracking //for each type add data to graph for (final EventType et : eventCounts.keySet()) { if (isCancelled()) { return null; } final Long count = eventCounts.get(et); final int fp = p++; if (count > 0) { final double adjustedCount = count == 0 ? 0 : scale.get().adjust(count); dateMax += adjustedCount; final XYChart.Data<String, Number> xyData = new BarChart.Data<>(dateString, adjustedCount); xyData.nodeProperty().addListener((Observable o) -> { final Node node = xyData.getNode(); if (node != null) { node.setStyle("-fx-border-width: 2; -fx-border-color: " + ColorUtilities.getRGBCode(et.getSuperType().getColor()) + "; -fx-bar-fill: " + ColorUtilities.getRGBCode(et.getColor())); // NON-NLS node.setCursor(Cursor.HAND); node.setOnMouseEntered((MouseEvent event) -> { //defer tooltip creation till needed, this had a surprisingly large impact on speed of loading the chart final Tooltip tooltip = new Tooltip( NbBundle.getMessage(this.getClass(), "CountsViewPane.tooltip.text", count, et.getDisplayName(), dateString, interval.getEnd().toString(rangeInfo.getTickFormatter()))); tooltip.setGraphic(new ImageView(et.getFXImage())); Tooltip.install(node, tooltip); node.setEffect(new DropShadow(10, et.getColor())); }); node.setOnMouseExited((MouseEvent event) -> { if (selectedNodes.contains(node)) { node.setEffect(SELECTED_NODE_EFFECT); } else { node.setEffect(null); } }); node.addEventHandler(MouseEvent.MOUSE_CLICKED, new BarClickHandler(node, dateString, interval, et)); } }); max = Math.max(max, dateMax); final double fmax = max; Platform.runLater(() -> { updateMessage(NbBundle.getMessage(this.getClass(), "CountsViewPane.loggedTask.updatingCounts")); getSeries(et).getData().add(xyData); if (scale.get().equals(ScaleType.LINEAR)) { countAxis.setTickUnit( Math.pow(10, Math.max(0, Math.floor(Math.log10(fmax)) - 1))); } else { countAxis.setTickUnit(Double.MAX_VALUE); } countAxis.setUpperBound(1 + fmax * 1.2); layoutDateLabels(); updateProgress(fp, rangeInfo.getPeriodsInRange()); }); } else { final double fmax = max; Platform.runLater(() -> { updateMessage(NbBundle.getMessage(this.getClass(), "CountsViewPane.loggedTask.updatingCounts")); updateProgress(fp, rangeInfo.getPeriodsInRange()); }); } } } Platform.runLater(() -> { updateMessage(NbBundle.getMessage(this.getClass(), "CountsViewPane.loggedTask.wrappingUp")); updateProgress(1, 1); layoutDateLabels(); setCursor(Cursor.NONE); }); return max > 0; } }; }
From source file:org.sleuthkit.autopsy.timeline.ui.detailview.DateAxis.java
License:Open Source License
@Override protected List<DateTime> calculateTickValues(double length, Object range) { List<DateTime> tickDates = new ArrayList<>(); if (range == null) { return tickDates; }/* ww w . jav a 2 s . c om*/ rangeDivisionInfo = RangeDivisionInfo.getRangeDivisionInfo((Interval) range); final DateTime lowerBound1 = getLowerBound(); final DateTime upperBound1 = getUpperBound(); if (lowerBound1 == null || upperBound1 == null) { return tickDates; } DateTime lower = lowerBound1.withZone(TimeLineController.getJodaTimeZone()); DateTime upper = upperBound1.withZone(TimeLineController.getJodaTimeZone()); DateTime current = lower; // Loop as long we exceeded the upper bound. while (current.isBefore(upper)) { tickDates.add(current); current = current.plus(rangeDivisionInfo.getPeriodSize().getPeriod());//.add(interval.interval, interval.amount); } // At last add the upper bound. tickDates.add(upper); // If there are at least three dates, check if the gap between the lower date and the second date is at least half the gap of the second and third date. // Do the same for the upper bound. // If gaps between dates are to small, remove one of them. // This can occur, e.g. if the lower bound is 25.12.2013 and years are shown. Then the next year shown would be 2014 (01.01.2014) which would be too narrow to 25.12.2013. if (tickDates.size() > 2) { DateTime secondDate = tickDates.get(1); DateTime thirdDate = tickDates.get(2); DateTime lastDate = tickDates.get(tickDates.size() - 2); DateTime previousLastDate = tickDates.get(tickDates.size() - 3); // If the second date is too near by the lower bound, remove it. if (secondDate.getMillis() - lower.getMillis() < (thirdDate.getMillis() - secondDate.getMillis()) / 2) { tickDates.remove(lower); } // If difference from the upper bound to the last date is less than the half of the difference of the previous two dates, // we better remove the last date, as it comes to close to the upper bound. if (upper.getMillis() - lastDate.getMillis() < (lastDate.getMillis() - previousLastDate.getMillis()) / 2) { tickDates.remove(lastDate); } } if (tickDates.size() >= 2) { tickSpacing.set(getDisplayPosition(tickDates.get(1)) - getDisplayPosition(tickDates.get(0))); } else if (tickDates.size() >= 4) { tickSpacing.set(getDisplayPosition(tickDates.get(2)) - getDisplayPosition(tickDates.get(1))); } return tickDates; }