Example usage for org.apache.commons.lang Validate isTrue

List of usage examples for org.apache.commons.lang Validate isTrue

Introduction

In this page you can find the example usage for org.apache.commons.lang Validate isTrue.

Prototype

public static void isTrue(boolean expression, String message) 

Source Link

Document

Validate an argument, throwing IllegalArgumentException if the test result is false.

This is used when validating according to an arbitrary boolean expression, such as validating a primitive number or using your own custom validation expression.

 Validate.isTrue( (i > 0), "The value must be greater than zero"); Validate.isTrue( myObject.isOk(), "The object is not OK"); 

For performance reasons, the message string should not involve a string append, instead use the #isTrue(boolean,String,Object) method.

Usage

From source file:com.opengamma.analytics.financial.model.option.definition.CappedPowerOptionDefinition.java

/**
 * //from w ww . j a v a  2s .com
 * @param strike The strike
 * @param expiry The expiry
 * @param power The power, not negative
 * @param cap The cap, not negative
 * @param isCall Is the option a put or call
 */
public CappedPowerOptionDefinition(final double strike, final Expiry expiry, final double power,
        final double cap, final boolean isCall) {
    super(strike, expiry, isCall);
    Validate.isTrue(power > 0, "power must be > 0");
    Validate.isTrue(cap > 0, "cap must be > 0");
    if (!isCall && cap > strike) {
        throw new IllegalArgumentException("Cannot have cap larger than strike for a put");
    }
    _power = power;
    _cap = cap;
}

From source file:com.opengamma.analytics.math.statistics.distribution.NonCentralChiSquaredDistribution.java

/**
 * @param degrees The number of degrees of freedom, not negative or zero
 * @param nonCentrality The non-centrality parameter, not negative
 *//*  w ww. ja  va  2 s.  co  m*/
public NonCentralChiSquaredDistribution(final double degrees, final double nonCentrality) {
    Validate.isTrue(degrees > 0, "degrees of freedom must be > 0, have " + degrees);
    Validate.isTrue(nonCentrality >= 0, "non-centrality must be >= 0, have " + nonCentrality);
    _dofOverTwo = degrees / 2.0;
    _lambdaOverTwo = nonCentrality / 2.0;
    _k = (int) Math.round(_lambdaOverTwo);

    if (_lambdaOverTwo == 0) {
        _pStart = 0.0;
    } else {
        final double logP = -_lambdaOverTwo + _k * Math.log(_lambdaOverTwo) - Gamma.logGamma(_k + 1);
        _pStart = Math.exp(logP);
    }
}

From source file:eu.carrade.amaury.TimeOut.events.PlayerGainsTimeEvent.java

@Override
public void setSecondsDiff(long secondsDiff) {
    Validate.isTrue(secondsDiff >= 0, "The seconds diff must be positive for a time gain event");
    super.setSecondsDiff(secondsDiff);
}

From source file:eu.carrade.amaury.TimeOut.events.PlayerLosesTimeEvent.java

@Override
public void setSecondsDiff(long secondsDiff) {
    Validate.isTrue(secondsDiff <= 0, "The seconds diff must be negative for a time loss event");
    super.setSecondsDiff(secondsDiff);
}

From source file:com.opengamma.financial.analytics.LabelledObjectMatrix1D.java

public LabelledObjectMatrix1D(TKey[] keys, Object[] labels, String labelsTitle, TValue[] values,
        String valuesTitle, TTolerance defaultTolerance) {
    Validate.notNull(keys, "labels");
    Validate.notNull(labels, "label names");
    Validate.notNull(values, "values");
    final int n = keys.length;
    Validate.isTrue(n == labels.length, "length of keys array must match length of label names array");
    Validate.isTrue(n == values.length, "length of keys array must match length of values array");
    _keys = Arrays.copyOf(keys, n);
    _labels = Arrays.copyOf(labels, n);
    _labelsTitle = labelsTitle;//  w  w  w. j a  v  a 2  s. com
    _values = Arrays.copyOf(values, n);
    _valuesTitle = valuesTitle;
    _defaultTolerance = defaultTolerance;
    quickSort();
}

From source file:ar.com.zauber.labs.kraken.providers.wikipedia.model.impl.InmutableWikiLink.java

/**
 * Recibe la representacion en texto de la wikipedia y los separa 
 * en topico y anchor.//  w w  w  .  ja v a  2  s. c  om
 * 
 *  Ej:
 *    [[Almirante Brown (partido)]] 
 *    [[Provincia de Santiago del Estero|Santiago del Estero]]
 *
 */
public InmutableWikiLink(final String textRepresentation, final WikiPageRetriever wikiPageRetriever,
        final Language wikiLang) {
    Validate.isTrue(StringUtils.isNotEmpty(textRepresentation), "Can't create a WikiLink from null");
    Validate.notNull(wikiPageRetriever);
    Validate.notNull(wikiLang);

    this.wikiPageRetriever = wikiPageRetriever;
    this.wikiLang = wikiLang;

    final Matcher m = regex.matcher(textRepresentation);
    if (m.matches()) {
        this.href = m.group(1).trim();
        String tmp = m.group(2).trim();
        this.value = StringUtils.isBlank(tmp) ? null : tmp.substring(1);
    } else {
        throw new IllegalArgumentException("Illegal link: " + textRepresentation);
    }
}

From source file:com.opengamma.analytics.financial.model.option.pricing.fourier.FourierModelGreeks.java

public double[] getGreeks(final BlackFunctionData data, final EuropeanVanillaOption option,
        final MartingaleCharacteristicExponent ce, final double alpha, final double limitTolerance) {
    Validate.notNull(data, "data");
    Validate.notNull(option, "option");
    Validate.notNull(ce, "characteristic exponent");
    Validate.isTrue(limitTolerance > 0, "limit tolerance must be > 0");
    Validate.isTrue(alpha <= ce.getLargestAlpha() && alpha >= ce.getSmallestAlpha(),
            "The value of alpha is not valid for the Characteristic Exponent and will most likely lead to mispricing. Choose a value between "
                    + ce.getSmallestAlpha() + " and " + ce.getLargestAlpha());

    final EuropeanCallFourierTransform psi = new EuropeanCallFourierTransform(ce);
    final double strike = option.getStrike();
    final double t = option.getTimeToExpiry();
    final double forward = data.getForward();
    final double discountFactor = data.getDiscountFactor();
    final Function1D<ComplexNumber, ComplexNumber> characteristicFunction = psi.getFunction(t);
    final double xMax = LIMIT_CALCULATOR.solve(characteristicFunction, alpha, limitTolerance);

    double kappa = Math.log(strike / forward);
    int n = ce.getCharacteristicExponentAdjoint(MINUS_I, 1.0).length; //TODO have method like getNumberOfparameters 

    Function1D<ComplexNumber, ComplexNumber[]> adjointFuncs = ce.getAdjointFunction(t);
    double[] res = new double[n - 1];

    //TODO This is inefficient as a call to ajointFuncs.evaluate(z), will return several values (the value of the characteristic function and its derivatives), but only one
    // of these values is used by each of the the integraters - a parallel quadrature scheme would be good here 
    for (int i = 0; i < n - 1; i++) {
        final Function1D<Double, Double> func = getIntegrandFunction(adjointFuncs, alpha, kappa, i + 1);
        final double integral = Math.exp(-alpha * Math.log(strike / forward))
                * _integrator.integrate(func, 0.0, xMax) / Math.PI;
        res[i] = discountFactor * forward * integral;
    }// www  .  j  a  va2  s.  c  o  m
    return res;
}

From source file:com.palantir.atlasdb.transaction.impl.AbstractLockAwareTransactionManager.java

@Override
public <T, E extends Exception> T runTaskWithLocksWithRetry(Iterable<HeldLocksToken> lockTokens,
        Supplier<LockRequest> lockSupplier, LockAwareTransactionTask<T, E> task)
        throws E, InterruptedException {
    int failureCount = 0;
    while (true) {
        LockRequest lockRequest = lockSupplier.get();
        HeldLocksToken lockToken = null;
        if (lockRequest != null) {
            Validate.isTrue(lockRequest.getVersionId() == null, "Using a version id is not allowed");
            HeldLocksToken response = getLockService().lockAndGetHeldLocksAnonymously(lockRequest);
            if (response == null) {
                RuntimeException e = new LockAcquisitionException(
                        "Failed to lock using the provided lock request: " + lockRequest);
                log.warn("Could not lock successfullly", e);
                failureCount++;//from   w  ww .  j a  v  a2s.c om
                if (shouldStopRetrying(failureCount)) {
                    log.warn("Failing after " + failureCount + " tries", e);
                    throw e;
                }
                sleepForBackoff(failureCount);
                continue;
            }
            lockToken = response;
        }

        try {
            if (lockToken == null) {
                return runTaskWithLocksThrowOnConflict(lockTokens, task);
            } else {
                return runTaskWithLocksThrowOnConflict(IterableUtils.append(lockTokens, lockToken), task);
            }
        } catch (TransactionFailedException e) {
            if (!e.canTransactionBeRetried()) {
                log.warn("Non-retriable exception while processing transaction.", e);
                throw e;
            }
            failureCount++;
            if (shouldStopRetrying(failureCount)) {
                log.warn("Failing after " + failureCount + " tries", e);
                throw e;
            }
            log.info("retrying transaction", e);
        } catch (RuntimeException e) {
            log.warn("RuntimeException while processing transaction.", e);
            throw e;
        } finally {
            if (lockToken != null) {
                getLockService().unlock(lockToken.getLockRefreshToken());
            }
        }

        sleepForBackoff(failureCount);
    }
}

From source file:com.opengamma.analytics.financial.instrument.annuity.AnnuityCouponInflationYearOnYearInterpolationDefinition.java

/**
 * Year on year annuity (or Year on year coupon leg) constructor from standard description. The coupon are fixing in advance and payment in arrears. 
 * The month lag is the conventional one.
 * @param priceIndex The price index./*from w  ww .j  a va 2s  .c o m*/
 * @param settlementDate The settlement date.
 * @param notional The notional.
 * @param totalPeriod The  period of the annuity.
 * @param paymentPeriod The payment period of the coupons.
 * @param businessDayConvention the business day convention. 
 * @param calendar the calendar.
 * @param endOfMonth The end-of-month flag.
 * @param conventionalMonthLag The lag in month between the index validity and the coupon dates for the standard product.
 * @param payNotional Payer (true) / receiver (false) flag.
 * @param weightStart The weight on the first month index in the interpolation of the index at the denominator.
 * @param weightEnd The weight on the first month index in the interpolation of the index at the numerator.
 * @return The Year on year coupon leg.
 */
public static AnnuityCouponInflationYearOnYearInterpolationDefinition from(final IndexPrice priceIndex,
        final ZonedDateTime settlementDate, final double notional, final Period totalPeriod,
        final Period paymentPeriod, final BusinessDayConvention businessDayConvention, final Calendar calendar,
        final boolean endOfMonth, final int conventionalMonthLag, final boolean payNotional,
        final double weightStart, final double weightEnd) {
    Validate.notNull(settlementDate, "settlement date");
    Validate.isTrue(notional > 0, "notional <= 0");
    Validate.notNull(paymentPeriod, "Payment period");
    ZonedDateTime[] paymentDates = ScheduleCalculator.getAdjustedDateSchedule(settlementDate, paymentPeriod,
            totalPeriod, true, false, businessDayConvention, calendar, endOfMonth);

    final CouponInflationYearOnYearInterpolationDefinition[] coupons = new CouponInflationYearOnYearInterpolationDefinition[paymentDates.length];
    coupons[0] = CouponInflationYearOnYearInterpolationDefinition.from(settlementDate, paymentDates[0],
            notional, priceIndex, conventionalMonthLag, payNotional, weightStart, weightEnd);
    for (int loopcpn = 1; loopcpn < paymentDates.length; loopcpn++) {
        coupons[loopcpn] = CouponInflationYearOnYearInterpolationDefinition.from(paymentDates[loopcpn - 1],
                paymentDates[loopcpn], notional, priceIndex, conventionalMonthLag, payNotional, weightStart,
                weightEnd);
    }
    return new AnnuityCouponInflationYearOnYearInterpolationDefinition(coupons);
}

From source file:com.opengamma.analytics.financial.interestrate.payments.method.CapFloorHullWhiteSuccessiveRootFinderCalibrationEngine.java

/**
 * Add an instrument to the basket and the associated calculator.
 * @param instrument An interest rate derivative.
 * @param method A pricing method.//w w  w .ja  va 2s. com
 */
@Override
public void addInstrument(final InstrumentDerivative instrument, final PricingMethod method) {
    Validate.isTrue(instrument instanceof CapFloorIbor, "Calibration instruments should be cap/floor");
    getBasket().add(instrument);
    getMethod().add(method);
    getCalibrationPrice().add(0.0);
    _calibrationTimes.add(((CapFloorIbor) instrument).getFixingTime());
}