List of usage examples for org.joda.time DateTime plusDays
public DateTime plusDays(int days)
From source file:org.jtotus.database.AutoUpdateStocks.java
License:Open Source License
private int updateClosingPrice(StockType stock, LocalJDBC javadb) { int counter = 0; DateTime calendar = new DateTime(); final int failureLimit = -8; final int foundLimit = 8; for (int i = 0; (failureLimit < i) && (i < foundLimit); i++) { calendar = calendar.plusDays(stepToRemove); stepToRemove = -1;/*from ww w . j av a 2 s .c o m*/ if (javadb.fetchClosingPrice(stockName, calendar) != null) { // Found in database counter++; continue; } else { calendar = calendar.plusDays(stepToRemove); if (stock.fetchClosingPrice(calendar) != null) { // Found somewhere in resources.. // Database should be updated already. counter = 0; continue; } else { // Not found int local database //nor in other resources. // Could be holiday or data simply is not available counter--; } } } return 1; }
From source file:org.kairosdb.util.Util.java
License:Apache License
/** Computes the duration of the sampling (value * unit) starting at timestamp. //w w w . ja v a 2s .c om @param timestamp unix timestamp of the start time. @return the duration of the sampling in millisecond. */ public static long getSamplingDuration(long timestamp, Sampling sampling, DateTimeZone timeZone) { long ret = sampling.getValue(); DateTime dt = new DateTime(timestamp, timeZone); switch (sampling.getUnit()) { case YEARS: ret = new org.joda.time.Duration(dt, dt.plusYears((int) sampling.getValue())).getMillis(); break; case MONTHS: ret = new org.joda.time.Duration(dt, dt.plusMonths((int) sampling.getValue())).getMillis(); break; case WEEKS: ret = new org.joda.time.Duration(dt, dt.plusWeeks((int) sampling.getValue())).getMillis(); break; case DAYS: ret = new org.joda.time.Duration(dt, dt.plusDays((int) sampling.getValue())).getMillis(); break; case HOURS: ret = new org.joda.time.Duration(dt, dt.plusHours((int) sampling.getValue())).getMillis(); break; case MINUTES: ret = new org.joda.time.Duration(dt, dt.plusMinutes((int) sampling.getValue())).getMillis(); break; case SECONDS: ret = new org.joda.time.Duration(dt, dt.plusSeconds((int) sampling.getValue())).getMillis(); break; case MILLISECONDS: ret = (long) sampling.getValue(); break; } return ret; }
From source file:org.kalypso.ui.rrm.internal.calccase.CatchmentModelHelper.java
License:Open Source License
/** * This function checks the validity ranges of the generators for gaps. * * @param generators/*ww w .j ava 2s. c om*/ * The generators to be checked. * @param simulationStart * The start of the simulation. * @param simulationEnd * The end of the simulation. * @param timestep * The timestep. * @param timestamp * The timestamp. * @return True, if the validity ranges of the generators do not have gaps or only timestep sized gaps. False * otherwise. */ private static boolean compareGeneratorValidityGaps(final IRainfallGenerator[] generators, final Date simulationStart, final Date simulationEnd, final Integer timestep, final LocalTime timestamp) { /* No generators available. */ /* Only one generator available. */ if (generators.length <= 1) return true; /* Build the simulation interval. */ final DateTime simulationStartDateTime = new DateTime(simulationStart); final DateTime simulationEndDateTime = new DateTime(simulationEnd); final DateRange simulationRange = modifyWithTimestamp(timestamp, simulationStartDateTime, simulationEndDateTime); final Date simulationStartDate = simulationRange.getFrom(); final Date simulationEndDate = simulationRange.getTo(); final long simulationStartTime = simulationStartDate.getTime(); final long simulationEndTime = simulationEndDate.getTime(); final org.kalypso.contribs.java.math.Interval simulationInterval = new org.kalypso.contribs.java.math.Interval( simulationStartTime, simulationEndTime); org.kalypso.contribs.java.math.Interval[] simulationRest = new org.kalypso.contribs.java.math.Interval[] { simulationInterval }; /* Check each generator. */ for (final IRainfallGenerator generator : generators) { /* Get the generator dates. */ DateTime generatorStartDateTime = new DateTime(generator.getValidFrom()); final DateTime generatorEndDateTime = new DateTime(generator.getValidTo()); /* Adjust the check for sum values. */ final String parameterType = generator.getParameterType(); final TIMESERIES_TYPE type = TimeseriesUtils.getType(parameterType); if (type.equals(TIMESERIES_TYPE.eSumValue)) generatorStartDateTime = generatorStartDateTime.plusDays(1); /* Build the generator interval. */ final Date generatorStartDate = generatorStartDateTime.toDate(); final Date generatorEndDate = generatorEndDateTime.toDate(); final long generatorStartTime = generatorStartDate.getTime(); final long generatorEndTime = generatorEndDate.getTime(); final org.kalypso.contribs.java.math.Interval generatorInterval = new org.kalypso.contribs.java.math.Interval( generatorStartTime, generatorEndTime); /* Substract the generator interval from all rest intervals. */ simulationRest = IntervalUtilities.difference(simulationRest, generatorInterval); } /* No gaps. */ if (simulationRest.length == 0) return true; for (final org.kalypso.contribs.java.math.Interval restInterval : simulationRest) { /* The gaps are only allowed to be of the size of the timestep. */ /* HINT: The timestep is in minutes -> convert to milliseconds. */ if (restInterval.getWidth() > timestep.intValue() * 60 * 1000) return false; } return true; }
From source file:org.killbill.billing.payment.control.InvoicePaymentControlPluginApi.java
License:Apache License
private DateTime getNextRetryDateForPaymentFailure( final List<PaymentTransactionModelDao> purchasedTransactions) { DateTime result = null;/*from w w w.j a va 2s .co m*/ final List<Integer> retryDays = paymentConfig.getPaymentRetryDays(); final int attemptsInState = getNumberAttemptsInState(purchasedTransactions, TransactionStatus.PAYMENT_FAILURE); final int retryCount = (attemptsInState - 1) >= 0 ? (attemptsInState - 1) : 0; if (retryCount < retryDays.size()) { int retryInDays; final DateTime nextRetryDate = clock.getUTCNow(); try { retryInDays = retryDays.get(retryCount); result = nextRetryDate.plusDays(retryInDays); } catch (NumberFormatException ex) { logger.error("Could not get retry day for retry count {}", retryCount); } } return result; }
From source file:org.killbill.billing.payment.invoice.InvoicePaymentControlPluginApi.java
License:Apache License
private DateTime getNextRetryDateForPaymentFailure( final List<PaymentTransactionModelDao> purchasedTransactions) { DateTime result = null;/*from w w w. jav a 2 s.c om*/ final List<Integer> retryDays = paymentConfig.getPaymentFailureRetryDays(); final int attemptsInState = getNumberAttemptsInState(purchasedTransactions, TransactionStatus.PAYMENT_FAILURE); final int retryCount = (attemptsInState - 1) >= 0 ? (attemptsInState - 1) : 0; if (retryCount < retryDays.size()) { final int retryInDays; final DateTime nextRetryDate = clock.getUTCNow(); try { retryInDays = retryDays.get(retryCount); result = nextRetryDate.plusDays(retryInDays); } catch (final NumberFormatException ex) { log.error("Could not get retry day for retry count {}", retryCount); } } return result; }
From source file:org.killbill.billing.payment.invoice.InvoicePaymentRoutingPluginApi.java
License:Apache License
private DateTime getNextRetryDateForPaymentFailure( final List<PaymentTransactionModelDao> purchasedTransactions) { DateTime result = null;/*from www. j a v a2 s .c o m*/ final List<Integer> retryDays = paymentConfig.getPaymentRetryDays(); final int attemptsInState = getNumberAttemptsInState(purchasedTransactions, TransactionStatus.PAYMENT_FAILURE); final int retryCount = (attemptsInState - 1) >= 0 ? (attemptsInState - 1) : 0; if (retryCount < retryDays.size()) { final int retryInDays; final DateTime nextRetryDate = clock.getUTCNow(); try { retryInDays = retryDays.get(retryCount); result = nextRetryDate.plusDays(retryInDays); } catch (final NumberFormatException ex) { log.error("Could not get retry day for retry count {}", retryCount); } } return result; }
From source file:org.killbill.billing.plugin.analytics.reports.scheduler.JobsScheduler.java
License:Apache License
@VisibleForTesting DateTime computeNextRun(final AnalyticsReportJob report) { final DateTime now = clock.getUTCNow(); if (Frequency.HOURLY.equals(report.getRefreshFrequency())) { // 5' past the hour (fixed to avoid drifts) return now.plusHours(1).withMinuteOfHour(5).withSecondOfMinute(0).withMillisOfSecond(0); } else if (Frequency.DAILY.equals(report.getRefreshFrequency())) { // 6am GMT by default final Integer hourOfTheDayGMT = MoreObjects.firstNonNull(report.getRefreshHourOfDayGmt(), 6); final DateTime boundaryTime = now.withHourOfDay(hourOfTheDayGMT).withMinuteOfHour(0) .withSecondOfMinute(0).withMillisOfSecond(0); return now.compareTo(boundaryTime) >= 0 ? boundaryTime.plusDays(1) : boundaryTime; } else {//from w w w. ja v a2 s . c om // Run now return now; } }
From source file:org.killbill.billing.plugin.bitcoin.osgi.http.PaymentRequestServlet.java
License:Apache License
private void createContract(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException, CatalogApiException, AccountApiException, PaymentApiException, EntitlementApiException, CustomFieldApiException, TagApiException, SubscriptionApiException { final String networkArg = Objects.firstNonNull(req.getParameter("network"), "main"); final String contractIdArg = req.getParameter("contractId"); // TODO The request parameter should be a subscriptionId, but the wallet should be given btcSubscriptionId. final String bitcoinSubscriptionIdArg = req.getParameter("subscriptionId"); final DateTime nowDateTime = new DateTime(DateTimeZone.UTC); final LocalDate now = new LocalDate(nowDateTime); final CallContext callContext = createCallContext(req, resp); final BitcoinSubscriptionId bitcoinSubscriptionId = BitcoinSubscriptionId .fromString(bitcoinSubscriptionIdArg); // TODO Works only for subscription aligned - exercise for the reader for bundle / account aligned // Depending on the alignment, the contracts should contain one contract for each entity that can end up in one invoice. // For example, all subscriptions on a given bundle, or all account aligned subscriptions Preconditions.checkState(ObjectType.SUBSCRIPTION.equals(bitcoinSubscriptionId.getAlignment())); final UUID subscriptionId = bitcoinSubscriptionId.getEntityId(); final Subscription subscription = killbillAPI.getSubscriptionApi() .getSubscriptionForEntitlementId(subscriptionId, callContext); final SubscriptionBundle bundle = killbillAPI.getSubscriptionApi() .getSubscriptionBundle(subscription.getBundleId(), callContext); SubscriptionEvent currentEvent = null; for (final SubscriptionEvent subscriptionEvent : Lists .reverse(bundle.getTimeline().getSubscriptionEvents())) { if (subscriptionEvent.getEntitlementId().equals(subscription.getId()) && subscriptionEvent.getEffectiveDate().compareTo(now) <= 0 && (SubscriptionEventType.START_BILLING.equals(subscriptionEvent.getSubscriptionEventType()) || SubscriptionEventType.CHANGE.equals(subscriptionEvent.getSubscriptionEventType()))) { currentEvent = subscriptionEvent; break; }/*from w w w . ja v a 2 s . co m*/ } final SubscriptionEvent futureChangeOrCancelEvent = Iterables.<SubscriptionEvent>tryFind( bundle.getTimeline().getSubscriptionEvents(), new Predicate<SubscriptionEvent>() { @Override public boolean apply(SubscriptionEvent input) { return input.getEntitlementId().equals(subscription.getId()) && (SubscriptionEventType.CHANGE.equals(input.getSubscriptionEventType()) || SubscriptionEventType.STOP_BILLING .equals(input.getSubscriptionEventType())) && // TODO clock input.getEffectiveDate().compareTo(new LocalDate(new DateTime(DateTimeZone.UTC))) > 0; } }).orNull(); final boolean isCancelled = (subscription.getBillingEndDate() != null && subscription.getBillingEndDate().compareTo(new LocalDate(now)) <= 0); final long maxPayment = isCancelled ? 0L : getMaxPaymentAmount(currentEvent.getNextPlan()); final Protos.PaymentFrequencyType frequencyType = isCancelled ? null : getPaymentFrequencyType(subscription.getLastActivePlan().getBillingPeriod()); final List<Protos.RecurringPaymentContract> contracts = new LinkedList<Protos.RecurringPaymentContract>(); final UUID contractId = contractIdArg == null ? UUID.randomUUID() : UUID.fromString(contractIdArg); Protos.RecurringPaymentContract.Builder currentContractBuilder = Protos.RecurringPaymentContract .newBuilder().setContractId(uuidToByteString(contractId)) .setStarts(localDateToMillis(currentEvent.getEffectiveDate())) .setPollingUrl(createURL(req, BTC_SUBSCRIPTION_POLLING_PATH, ImmutableMap.<String, String>of("merchantId", DEFAULT_MERCHANT_ID, "subscriptionId", bitcoinSubscriptionId.toString(), "contractId", contractId.toString(), "network", networkArg))) .setPaymentFrequencyType(frequencyType).setMaxPaymentPerPeriod(maxPayment) .setMaxPaymentAmount(maxPayment); if (futureChangeOrCancelEvent != null) { currentContractBuilder.setEnds(localDateToMillis(futureChangeOrCancelEvent.getEffectiveDate())); // TODO check it may exist! final UUID nextContractId = UUID.randomUUID(); transactionLogDao.insertTransactionLog(new TransactionLog(new DateTime(DateTimeZone.UTC), "createContract", subscription.getAccountId(), subscription.getId(), nextContractId)); final long nextMaxAmount = getMaxPaymentAmount(futureChangeOrCancelEvent.getNextPlan()); Protos.RecurringPaymentContract.Builder nextContractBuilder = Protos.RecurringPaymentContract .newBuilder().setContractId(uuidToByteString(nextContractId)) .setStarts(localDateToMillis(futureChangeOrCancelEvent.getEffectiveDate())) .setEnds(localDateToMillis(subscription.getBillingEndDate())) .setPollingUrl(createURL(req, BTC_SUBSCRIPTION_POLLING_PATH, ImmutableMap.<String, String>of("merchantId", DEFAULT_MERCHANT_ID, "subscriptionId", bitcoinSubscriptionId.toString(), "contractId", nextContractId.toString(), "network", networkArg))) .setMaxPaymentPerPeriod(nextMaxAmount).setMaxPaymentAmount(nextMaxAmount); if (futureChangeOrCancelEvent.getNextPlan() != null) { nextContractBuilder.setPaymentFrequencyType( getPaymentFrequencyType(futureChangeOrCancelEvent.getNextPlan().getBillingPeriod())); } contracts.add(nextContractBuilder.build()); } contracts.add(currentContractBuilder.build()); if (contractIdArg == null) { contractDao .insertContract(new Contract(new BitcoinSubscriptionId(ObjectType.SUBSCRIPTION, subscriptionId), currentEvent.getEffectiveDate(), futureChangeOrCancelEvent == null ? null : futureChangeOrCancelEvent.getEffectiveDate(), contractId)); transactionLogDao.insertTransactionLog(new TransactionLog(new DateTime(DateTimeZone.UTC), "createContract", subscription.getAccountId(), subscription.getId(), contractId)); } Protos.RecurringPaymentDetails recurringPaymentDetails = Protos.RecurringPaymentDetails.newBuilder() .setMerchantId(DEFAULT_MERCHANT_ID).setSubscriptionId(uuidToByteString(subscription.getId())) .addAllContracts(contracts).build(); Protos.PaymentDetails details = Protos.PaymentDetails.newBuilder().setNetwork(networkArg) .setTime(nowDateTime.getMillis()).setExpires(nowDateTime.plusDays(1).getMillis()) .setMemo("Kill Bill subscription " + subscription.getLastActivePlan().getName()) .setPaymentUrl(createURL(req, BTC_SUBSCRIPTION_PAYMENT_PATH)) .setMerchantData(ByteString.copyFrom(contractId.toString().getBytes())) .setSerializedRecurringPaymentDetails(recurringPaymentDetails.toByteString()).build(); Protos.PaymentRequest result = Protos.PaymentRequest.newBuilder().setPaymentDetailsVersion(1) .setPkiType("none") //.setPkiData(null) .setSerializedPaymentDetails(details.toByteString()) //.setSignature(null) .build(); result.writeTo(resp.getOutputStream()); resp.setContentType("application/bitcoin-paymentrequest"); resp.setStatus(HttpServletResponse.SC_OK); }
From source file:org.killbill.billing.plugin.bitcoin.osgi.http.PaymentRequestServlet.java
License:Apache License
private void pollForPayment(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException, CatalogApiException, PaymentApiException { final String contractIdString = req.getParameter("contractId"); final String accountIdString = req.getParameter("accountId"); Preconditions.checkNotNull(contractIdString); final UUID contractId = UUID.fromString(contractIdString); final String network = Objects.firstNonNull(req.getParameter("network"), "main"); final List<PendingPayment> pendingPayments = paymentDao.getByBtcContractId(contractId); // TODO PIERRE combine multiple pending payments as long as this is within contract bounds. final PendingPayment pendingPayment = pendingPayments.size() > 0 ? pendingPayments.get(0) : null; final Payment payment = pendingPayment != null ? killbillAPI.getPaymentApi().getPayment(pendingPayment.getPaymentId(), false, createCallContext(req, resp)) : null;//from w w w. j a v a2 s . co m Preconditions.checkState(payment == null || payment.getCurrency() == Currency.BTC); final UUID accountId = UUID.fromString(accountIdString); transactionLogDao.insertTransactionLog( new TransactionLog(new DateTime(DateTimeZone.UTC), "pollForPayment", accountId, null, contractId)); final long paymentAmountInSatochi = payment != null ? payment.getAmount().longValue() * BTC_TO_SATOSHIS : 0L; final DateTime now = new DateTime(DateTimeZone.UTC); final String memo = payment != null ? "Kill Bill payment " + payment.getId() : "No invoice to pay"; final Protos.PaymentDetails.Builder detailsBuilder = Protos.PaymentDetails.newBuilder(); detailsBuilder.setNetwork(network).setTime(now.getMillis()).setExpires(now.plusDays(1).getMillis()) .setMemo(memo).setPaymentUrl(createURL(req, BTC_SUBSCRIPTION_PAYMENT_PATH)) .setMerchantData(ByteString.copyFrom(contractId.toString().getBytes())); if (paymentAmountInSatochi > 0) { final Protos.Output.Builder outputBuilder = Protos.Output.newBuilder(); outputBuilder.setAmount(paymentAmountInSatochi); final ECKey newPaymentKey = bitcoinManager.addKey(); outputBuilder .setScript(ByteString.copyFrom(ScriptBuilder.createOutputScript(newPaymentKey).getProgram())); final Protos.Output output = outputBuilder.build(); detailsBuilder.addOutputs(output); } final Protos.PaymentDetails details = detailsBuilder.build(); final Protos.PaymentRequest result = Protos.PaymentRequest.newBuilder().setPaymentDetailsVersion(1) .setPkiType("none") //.setPkiData(null) .setSerializedPaymentDetails(details.toByteString()) //.setSignature(null) .build(); result.writeTo(resp.getOutputStream()); resp.setContentType("application/bitcoin-paymentrequest"); resp.setStatus(HttpServletResponse.SC_OK); }
From source file:org.killbill.billing.subscription.alignment.BaseAligner.java
License:Apache License
private DateTime addOrRemoveDuration(final DateTime input, final Duration duration, boolean add) { DateTime result = input; switch (duration.getUnit()) { case DAYS:/*from www . java 2 s. c om*/ result = add ? result.plusDays(duration.getNumber()) : result.minusDays(duration.getNumber()); ; break; case MONTHS: result = add ? result.plusMonths(duration.getNumber()) : result.minusMonths(duration.getNumber()); break; case YEARS: result = add ? result.plusYears(duration.getNumber()) : result.minusYears(duration.getNumber()); break; case UNLIMITED: default: throw new RuntimeException("Trying to move to unlimited time period"); } return result; }