text:
package com.opengamma.analytics.financial.curve;

import org.testng.annotations.Test;

import com.opengamma.util.test.TestGroup;

/**
 * Data for the testing of curve construction with FX swaps and XCCy swaps
 * TODO: This is old code that has been commented. It should be removed at some point.
 */
@Test(groups = TestGroup.UNIT)
public class YieldCurveConstructionGeneratorTwoCurrenciesXCcyData {

  //  private static final Interpolator1D INTERPOLATOR = CombinedInterpolatorExtrapolatorFactory.getInterpolator(Interpolator1DFactory.DOUBLE_QUADRATIC, LinearExtrapolator1dAdapter.NAME,
  //      FlatExtrapolator1dAdapter.NAME);
  //  private static final MatrixAlgebra MATRIX_ALGEBRA = new CommonsMatrixAlgebra();
  //
  //  private static final LastTimeCalculator MATURITY_CALCULATOR = LastTimeCalculator.getInstance();
  //  private static final PresentValueBasisPointCalculator PVBP_CALCULATOR = PresentValueBasisPointCalculator.getInstance();
  //  private static final double TOLERANCE_ROOT = 1.0E-10;
  //  private static final BroydenVectorRootFinder ROOT_FINDER = new BroydenVectorRootFinder(TOLERANCE_ROOT, TOLERANCE_ROOT, 10000,
  //      DecompositionFactory.getDecomposition(DecompositionFactory.SV_COLT_NAME));
  //  static final Currency CCY1 = Currency.EUR;
  //  private static final Currency CCY2 = Currency.USD;
  //  private static final double FX_EURUSD = 1.40;
  //  private static final FXMatrix FX_MATRIX = new FXMatrix(CCY2, CCY1, FX_EURUSD);
  //  private static final Calendar CALENDAR = new MondayToFridayCalendar("CAL");
  //  private static final int SPOT_LAG = 2;
  //  private static final DayCount DAY_COUNT_CASH = DayCounts.ACT_360;
  //  private static final double NOTIONAL = 1.0;
  //  private static final BusinessDayConvention BDC = BusinessDayConventions.MODIFIED_FOLLOWING;
  //  private static final IndexON INDEX_ON_1 = new IndexON("Fed Fund", CCY1, DAY_COUNT_CASH, 1, CALENDAR);
  //  private static final GeneratorDepositON GENERATOR_DEPOSIT_ON_1 = new GeneratorDepositON("USD Deposit ON", CCY1, CALENDAR, DAY_COUNT_CASH);
  //  private static final GeneratorDepositON GENERATOR_DEPOSIT_ON_2 = new GeneratorDepositON("EUR Deposit ON", CCY2, CALENDAR, DAY_COUNT_CASH);
  //  private static final GeneratorSwapFixedON GENERATOR_OIS_1 = new GeneratorSwapFixedON("USD1YFEDFUND", INDEX_ON_1, Period.ofMonths(12), DAY_COUNT_CASH, BDC, true, SPOT_LAG, SPOT_LAG);
  //  private static final GeneratorForexSwap GENERATOR_FX = new GeneratorForexSwap("EURUSD", CCY2, CCY1, CALENDAR, SPOT_LAG, BDC, true);
  //  private static final GeneratorDeposit GENERATOR_DEPOSIT_1 = new GeneratorDeposit("USD Deposit", CCY1, CALENDAR, SPOT_LAG, DAY_COUNT_CASH, BDC, true);
  //  private static final GeneratorDeposit GENERATOR_DEPOSIT_2 = new GeneratorDeposit("EuR Deposit", CCY2, CALENDAR, SPOT_LAG, DAY_COUNT_CASH, BDC, true);
  //  private static final GeneratorSwapFixedIborMaster GENERATOR_SWAP_MASTER = GeneratorSwapFixedIborMaster.getInstance();
  //  private static final GeneratorSwapFixedIbor USD6MLIBOR3M = GENERATOR_SWAP_MASTER.getGenerator("USD6MLIBOR3M", CALENDAR);
  //  private static final GeneratorSwapFixedIbor EUR1YEURIBOR3M = GENERATOR_SWAP_MASTER.getGenerator("EUR1YEURIBOR3M", CALENDAR);
  //  private static final IborIndex USDLIBOR3M = USD6MLIBOR3M.getIborIndex();
  //  private static final IborIndex EURIBOR3M = EUR1YEURIBOR3M.getIborIndex();
  //  private static final GeneratorSwapXCcyIborIbor GENERATOR_XCCY = new GeneratorSwapXCcyIborIbor("EURIBOR3MUSDLIBOR3M", EURIBOR3M, USDLIBOR3M); // Spread on EUR leg
  //
  //  private static final ZonedDateTime NOW = DateUtils.getUTCDate(2011, 9, 28);
  //
  //  private static final ArrayZonedDateTimeDoubleTimeSeries TS_EMPTY = new ArrayZonedDateTimeDoubleTimeSeries();
  //  private static final ArrayZonedDateTimeDoubleTimeSeries TS_ON_USD_WITH_TODAY = new ArrayZonedDateTimeDoubleTimeSeries(new ZonedDateTime[] {DateUtils.getUTCDate(2011, 9, 27),
  //      DateUtils.getUTCDate(2011, 9, 28) }, new double[] {0.07, 0.08 });
  //  private static final ArrayZonedDateTimeDoubleTimeSeries TS_ON_USD_WITHOUT_TODAY = new ArrayZonedDateTimeDoubleTimeSeries(new ZonedDateTime[] {DateUtils.getUTCDate(2011, 9, 27),
  //      DateUtils.getUTCDate(2011, 9, 28) }, new double[] {0.07, 0.08 });
  //  @SuppressWarnings("rawtypes")
  //  static final DoubleTimeSeries[] TS_FIXED_OIS_USD_WITH_TODAY = new DoubleTimeSeries[] {TS_EMPTY, TS_ON_USD_WITH_TODAY };
  //  @SuppressWarnings("rawtypes")
  //  static final DoubleTimeSeries[] TS_FIXED_OIS_USD_WITHOUT_TODAY = new DoubleTimeSeries[] {TS_EMPTY, TS_ON_USD_WITHOUT_TODAY };
  //
  //  private static final ArrayZonedDateTimeDoubleTimeSeries TS_IBOR_USD3M_WITH_TODAY = new ArrayZonedDateTimeDoubleTimeSeries(new ZonedDateTime[] {DateUtils.getUTCDate(2011, 9, 27),
  //      DateUtils.getUTCDate(2011, 9, 28) }, new double[] {0.0035, 0.0036 });
  //  private static final ArrayZonedDateTimeDoubleTimeSeries TS_IBOR_USD3M_WITHOUT_TODAY = new ArrayZonedDateTimeDoubleTimeSeries(new ZonedDateTime[] {DateUtils.getUTCDate(2011, 9, 27) },
  //      new double[] {0.0035 });
  //
  //  private static final ArrayZonedDateTimeDoubleTimeSeries TS_IBOR_EUR3M_WITH_TODAY = new ArrayZonedDateTimeDoubleTimeSeries(new ZonedDateTime[] {DateUtils.getUTCDate(2011, 9, 27),
  //      DateUtils.getUTCDate(2011, 9, 28) }, new double[] {0.0060, 0.0061 });
  //  private static final ArrayZonedDateTimeDoubleTimeSeries TS_IBOR_EUR3M_WITHOUT_TODAY = new ArrayZonedDateTimeDoubleTimeSeries(new ZonedDateTime[] {DateUtils.getUTCDate(2011, 9, 27) },
  //      new double[] {0.0060 });
  //  @SuppressWarnings("rawtypes")
  //  static final DoubleTimeSeries[] TS_FIXED_IBOR_USD3M_WITH_TODAY = new DoubleTimeSeries[] {TS_IBOR_USD3M_WITH_TODAY };
  //  @SuppressWarnings("rawtypes")
  //  static final DoubleTimeSeries[] TS_FIXED_IBOR_USD3M_WITHOUT_TODAY = new DoubleTimeSeries[] {TS_IBOR_USD3M_WITHOUT_TODAY };
  //  @SuppressWarnings("rawtypes")
  //  static final DoubleTimeSeries[] TS_FIXED_IBOR_EUR3M_WITH_TODAY = new DoubleTimeSeries[] {TS_IBOR_EUR3M_WITH_TODAY };
  //  @SuppressWarnings("rawtypes")
  //  static final DoubleTimeSeries[] TS_FIXED_IBOR_EUR3M_WITHOUT_TODAY = new DoubleTimeSeries[] {TS_IBOR_EUR3M_WITHOUT_TODAY };
  //  @SuppressWarnings("rawtypes")
  //  static final DoubleTimeSeries[] TS_FIXED_IBOR_EURUSD3M_WITH_TODAY = new DoubleTimeSeries[] {TS_IBOR_EUR3M_WITH_TODAY, TS_IBOR_USD3M_WITH_TODAY };
  //  @SuppressWarnings("rawtypes")
  //  static final DoubleTimeSeries[] TS_FIXED_IBOR_EURUSD3M_WITHOUT_TODAY = new DoubleTimeSeries[] {TS_IBOR_EUR3M_WITHOUT_TODAY, TS_IBOR_USD3M_WITHOUT_TODAY };
  //
  //  static final String CURVE_NAME_DSC_1 = "USD Dsc";
  //  static final String CURVE_NAME_DSC_2 = "EUR Dsc";
  //  static final String CURVE_NAME_FWD_1 = "USD Fwd 3M";
  //  static final String CURVE_NAME_FWD_2 = "EUR Fwd 3M";
  //  private static final HashMap<String, Currency> CCY_MAP = new HashMap<String, Currency>();
  //
  //  /** Market values for the dsc USD curve */
  //  public static final double[] DSC_1_MARKET_QUOTES = new double[] {0.0045, 0.0050, 0.0075, 0.0080, 0.0085, 0.0090, 0.0095, 0.0110, 0.0120, 0.0130, 0.0140, 0.0150, 0.0200 };
  //  /** Generators for the dsc USD curve */
  //  public static final GeneratorInstrument[] DSC_1_GENERATORS = new GeneratorInstrument[] {GENERATOR_DEPOSIT_ON_1, GENERATOR_DEPOSIT_ON_1, GENERATOR_OIS_1, GENERATOR_OIS_1, GENERATOR_OIS_1,
  //    GENERATOR_OIS_1, GENERATOR_OIS_1, GENERATOR_OIS_1, GENERATOR_OIS_1, GENERATOR_OIS_1, GENERATOR_OIS_1, GENERATOR_OIS_1, GENERATOR_OIS_1};
  //  /** Tenors for the dsc USD curve */
  //  public static final Period[] DSC_1_TENOR = new Period[] {Period.ofDays(0), Period.ofDays(1), Period.ofMonths(1), Period.ofMonths(2), Period.ofMonths(3), Period.ofMonths(6), Period.ofMonths(9),
  //    Period.ofYears(1), Period.ofYears(2), Period.ofYears(3), Period.ofYears(4), Period.ofYears(5), Period.ofYears(10) };
  //
  //  /** Market values for the Fwd 3M USD curve */
  //  public static final double[] FWD_1_MARKET_QUOTES = new double[] {0.0050, 0.0075, 0.0160, 0.0170, 0.0200, 0.0225 };
  //  /** Generators for the Fwd 3M USD curve */
  //  public static final GeneratorInstrument[] FWD_1_GENERATORS = new GeneratorInstrument[] {GENERATOR_DEPOSIT_1, USD6MLIBOR3M, USD6MLIBOR3M, USD6MLIBOR3M, USD6MLIBOR3M, USD6MLIBOR3M };
  //  /** Tenors for the Fwd 3M USD curve */
  //  public static final Period[] FWD_1_TENOR = new Period[] {Period.ofMonths(3), Period.ofMonths(6), Period.ofYears(1), Period.ofYears(2), Period.ofYears(5), Period.ofYears(10) };
  //
  //  /** Market values for the dsc EUR curve */
  //  public static final double[] DSC_2_MARKET_QUOTES = new double[] {0.0070, 0.0075, 0.0002, 0.0004, 0.0006, 0.0012, 0.0018, 0.0025, -0.0025, -0.0025, -0.0025, -0.0025, -0.0025 };
  //  /** Generators for the dsc EUR curve */
  //  public static final GeneratorInstrument[] DSC_2_GENERATORS = new GeneratorInstrument[] {GENERATOR_DEPOSIT_ON_2, GENERATOR_DEPOSIT_ON_2, GENERATOR_FX, GENERATOR_FX, GENERATOR_FX, GENERATOR_FX,
  //    GENERATOR_FX, GENERATOR_FX, GENERATOR_XCCY, GENERATOR_XCCY, GENERATOR_XCCY, GENERATOR_XCCY, GENERATOR_XCCY};
  //  /** Tenors for the dsc EUR curve */
  //  public static final Period[] DSC_2_TENOR = new Period[] {Period.ofDays(0), Period.ofDays(1), Period.ofMonths(1), Period.ofMonths(2), Period.ofMonths(3), Period.ofMonths(6), Period.ofMonths(9),
  //    Period.ofYears(1), Period.ofYears(2), Period.ofYears(3), Period.ofYears(4), Period.ofYears(5), Period.ofYears(10) };
  //  //  /** FX rqtes for the dsc EUR curve */
  //  //  public static final Double[] DSC_2_FX_RATE = new Double[] {FX_EURUSD, FX_EURUSD, FX_EURUSD, FX_EURUSD, FX_EURUSD, FX_EURUSD, FX_EURUSD, FX_EURUSD, FX_EURUSD, FX_EURUSD, FX_EURUSD, FX_EURUSD,
  //  //      FX_EURUSD};
  //
  //  /** Market values for the Fwd 3M EUR curve */
  //  public static final double[] FWD_2_MARKET_QUOTES = new double[] {0.0075, 0.0100, 0.0185, 0.0195, 0.0205, 0.0215, 0.0225, 0.0250 };
  //  /** Generators for the Fwd 3M USD curve */
  //  public static final GeneratorInstrument[] FWD_2_GENERATORS = new GeneratorInstrument[] {GENERATOR_DEPOSIT_2, EUR1YEURIBOR3M, EUR1YEURIBOR3M, EUR1YEURIBOR3M, EUR1YEURIBOR3M, EUR1YEURIBOR3M,
  //    EUR1YEURIBOR3M, EUR1YEURIBOR3M};
  //  /** Tenors for the Fwd 3M USD curve */
  //  public static final Period[] FWD_2_TENOR = new Period[] {Period.ofMonths(3), Period.ofMonths(6), Period.ofYears(1), Period.ofYears(2), Period.ofYears(3), Period.ofYears(4), Period.ofYears(5),
  //    Period.ofYears(10) };
  //
  //  /** Standard USD discounting curve instrument definitions */
  //  public static final List<InstrumentDefinition<?>> DEFINITIONS_DSC_1;
  //  /** Standard USD Forward 3M curve instrument definitions */
  //  public static final List<InstrumentDefinition<?>> DEFINITIONS_FWD_1;
  //  /** Standard EUR discounting curve instrument definitions */
  //  public static final List<InstrumentDefinition<?>> DEFINITIONS_DSC_2;
  //  /** Standard EUR Forward 3M curve instrument definitions */
  //  public static final List<InstrumentDefinition<?>> DEFINITIONS_FWD_2;
  //
  //  static {
  //    DEFINITIONS_DSC_1 = getDefinitions(DSC_1_MARKET_QUOTES, DSC_1_GENERATORS, DSC_1_TENOR);
  //    DEFINITIONS_FWD_1 = getDefinitions(FWD_1_MARKET_QUOTES, FWD_1_GENERATORS, FWD_1_TENOR);
  //    DEFINITIONS_DSC_2 = getDefinitions(DSC_2_MARKET_QUOTES, DSC_2_GENERATORS, DSC_2_TENOR);
  //    DEFINITIONS_FWD_2 = getDefinitions(FWD_2_MARKET_QUOTES, FWD_2_GENERATORS, FWD_2_TENOR);
  //    CCY_MAP.put(CURVE_NAME_DSC_1, CCY1);
  //    CCY_MAP.put(CURVE_NAME_FWD_1, CCY1);
  //    CCY_MAP.put(CURVE_NAME_DSC_2, CCY2);
  //    CCY_MAP.put(CURVE_NAME_FWD_2, CCY2);
  //  }
  //
  //  /**
  //   * Curve types used in the curve construction
  //   */
  //  public enum CurveType {
  //    /** USD Discounting **/
  //    DSC_1,
  //    /** EUR Discounting **/
  //    DSC_2,
  //    /** USD Forward 3M **/
  //    FWD_1,
  //    /** EUR Forward 3M **/
  //    FWD_2;
  //  }
  //
  //  public static List<InstrumentDefinition<?>> getDefinitions(final double[] marketQuotes, final GeneratorInstrument[] generators, final Period[] tenors) {
  //    final List<InstrumentDefinition<?>> definitions = new ArrayList<InstrumentDefinition<?>>();
  //    for (int loopmv = 0; loopmv < marketQuotes.length; loopmv++) {
  //      definitions.add(generators[loopmv].generateInstrument(NOW, tenors[loopmv], marketQuotes[loopmv], NOTIONAL, FX_MATRIX));
  //    }
  //    return definitions;
  //  }
  //
  //  private static double initialGuess(final InstrumentDefinition<?> instrument) {
  //    if (instrument instanceof SwapFixedONDefinition) {
  //      return ((SwapFixedONDefinition) instrument).getFixedLeg().getNthPayment(0).getRate();
  //    }
  //    if (instrument instanceof SwapFixedIborDefinition) {
  //      return ((SwapFixedIborDefinition) instrument).getFixedLeg().getNthPayment(0).getRate();
  //    }
  //    if (instrument instanceof ForwardRateAgreementDefinition) {
  //      return ((ForwardRateAgreementDefinition) instrument).getRate();
  //    }
  //    if (instrument instanceof CashDefinition) {
  //      return ((CashDefinition) instrument).getRate();
  //    }
  //    return 0.01;
  //  }
  //
  //  @SuppressWarnings({"unchecked"})
  //  /**
  //   * The returned pair contains 1) the yield curve bundle and 2) the inverse Jacobian (derivative of the curve parameters with respect to the market quotes).
  //   */
  //  public static Pair<YieldCurveBundle, DoubleMatrix2D> makeCurves(final List<InstrumentDefinition<?>> dsc1Definitions, final List<InstrumentDefinition<?>> fwd1Definitions,
  //      final List<InstrumentDefinition<?>> dsc2Definitions, final List<InstrumentDefinition<?>> fwd2Definitions,
  //      final InstrumentDerivativeVisitor<YieldCurveBundle, Double> calculator,
  //      final InstrumentDerivativeVisitor<YieldCurveBundle, InterestRateCurveSensitivity> sensitivityCalculator, final boolean withToday, final boolean isPV) {
  //    final int nbDsc1 = dsc1Definitions.size();
  //    final int nbFwd1 = fwd1Definitions.size();
  //    final int nbDsc2 = dsc2Definitions.size();
  //    final int nbFwd2 = fwd2Definitions.size();
  //    final InstrumentDerivative[] instruments = new InstrumentDerivative[nbDsc1 + nbFwd1 + nbDsc2 + nbFwd2];
  //    final double[] dsc1Node = new double[nbDsc1];
  //    final double[] fwd1Node = new double[nbFwd1];
  //    final double[] dsc2Node = new double[nbDsc2];
  //    final double[] fwd2Node = new double[nbFwd2];
  //    final double[] initGuess = new double[nbDsc1 + nbFwd1 + nbDsc2 + nbFwd2];
  //    int i = 0;
  //    for (final InstrumentDefinition<?> instrument : dsc1Definitions) {
  //      InstrumentDerivative ird;
  //      if (instrument instanceof SwapFixedONDefinition) {
  //        final String[] curveNames = new String[] {CURVE_NAME_DSC_1, CURVE_NAME_DSC_1 };
  //        ird = ((SwapFixedONDefinition) instrument).toDerivative(NOW, withToday ? TS_FIXED_OIS_USD_WITH_TODAY : TS_FIXED_OIS_USD_WITHOUT_TODAY, curveNames);
  //      } else {
  //        final String[] curveNames = new String[] {CURVE_NAME_DSC_1 };
  //        ird = instrument.toDerivative(NOW, curveNames);
  //      }
  //      instruments[i] = ird;
  //      initGuess[i] = initialGuess(instrument);
  //      dsc1Node[i++] = ird.accept(MATURITY_CALCULATOR);
  //    }
  //    int j = 0;
  //    for (final InstrumentDefinition<?> instrument : fwd1Definitions) {
  //      InstrumentDerivative ird;
  //      if (instrument instanceof SwapFixedIborDefinition) {
  //        final String[] curveNames = new String[] {CURVE_NAME_DSC_1, CURVE_NAME_FWD_1 };
  //        ird = ((SwapFixedIborDefinition) instrument).toDerivative(NOW, withToday ? TS_FIXED_IBOR_USD3M_WITH_TODAY : TS_FIXED_IBOR_USD3M_WITHOUT_TODAY, curveNames);
  //      } else {
  //        final String[] curveNames = new String[] {CURVE_NAME_FWD_1 };
  //        ird = instrument.toDerivative(NOW, curveNames);
  //      }
  //      instruments[i] = ird;
  //      initGuess[i++] = initialGuess(instrument);
  //      fwd1Node[j++] = ird.accept(MATURITY_CALCULATOR);
  //    }
  //    j = 0;
  //    for (final InstrumentDefinition<?> instrument : dsc2Definitions) {
  //      InstrumentDerivative ird;
  //      if (instrument instanceof SwapXCcyIborIborDefinition) {
  //        final String[] curveNames = new String[] {CURVE_NAME_DSC_2, CURVE_NAME_FWD_2, CURVE_NAME_DSC_1, CURVE_NAME_FWD_1 };
  //        ird = ((SwapXCcyIborIborDefinition) instrument).toDerivative(NOW, withToday ? TS_FIXED_IBOR_EURUSD3M_WITH_TODAY : TS_FIXED_IBOR_EURUSD3M_WITHOUT_TODAY, curveNames);
  //      } else {
  //        if (instrument instanceof CashDefinition) {
  //          final String[] curveNames = new String[] {CURVE_NAME_DSC_2 };
  //          ird = instrument.toDerivative(NOW, curveNames);
  //        } else {
  //          final String[] curveNames = new String[] {CURVE_NAME_DSC_2, CURVE_NAME_DSC_1 };
  //          ird = instrument.toDerivative(NOW, curveNames);
  //        }
  //      }
  //      instruments[i] = ird;
  //      initGuess[i++] = initialGuess(instrument);
  //      dsc2Node[j++] = ird.accept(MATURITY_CALCULATOR);
  //    }
  //    j = 0;
  //    for (final InstrumentDefinition<?> instrument : fwd2Definitions) {
  //      InstrumentDerivative ird;
  //      if (instrument instanceof SwapFixedIborDefinition) {
  //        final String[] curveNames = new String[] {CURVE_NAME_DSC_2, CURVE_NAME_FWD_2 };
  //        ird = ((SwapFixedIborDefinition) instrument).toDerivative(NOW, withToday ? TS_FIXED_IBOR_EUR3M_WITH_TODAY : TS_FIXED_IBOR_EUR3M_WITHOUT_TODAY, curveNames);
  //      } else {
  //        final String[] curveNames = new String[] {CURVE_NAME_FWD_2 };
  //        ird = instrument.toDerivative(NOW, curveNames);
  //      }
  //      instruments[i] = ird;
  //      initGuess[i++] = initialGuess(instrument);
  //      fwd2Node[j++] = ird.accept(MATURITY_CALCULATOR);
  //    }
  //
  //    final LinkedHashMap<String, GeneratorYDCurve> curveGenerators = new LinkedHashMap<String, GeneratorYDCurve>();
  //    curveGenerators.put(CURVE_NAME_DSC_1, new GeneratorCurveYieldInterpolatedNode(dsc1Node, INTERPOLATOR));
  //    curveGenerators.put(CURVE_NAME_FWD_1, new GeneratorCurveYieldInterpolatedNode(fwd1Node, INTERPOLATOR));
  //    curveGenerators.put(CURVE_NAME_DSC_2, new GeneratorCurveYieldInterpolatedNode(dsc2Node, INTERPOLATOR));
  //    curveGenerators.put(CURVE_NAME_FWD_2, new GeneratorCurveYieldInterpolatedNode(fwd2Node, INTERPOLATOR));
  //    final YieldCurveBundle knowData = new YieldCurveBundle(FX_MATRIX, CCY_MAP);
  //    final MultipleYieldCurveFinderGeneratorDataBundle data = new MultipleYieldCurveFinderGeneratorDataBundle(instruments, knowData, curveGenerators);
  //    final Function1D<DoubleMatrix1D, DoubleMatrix1D> curveCalculator = new MultipleYieldCurveFinderGeneratorFunction(calculator, data);
  //    final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacobianCalculator = new MultipleYieldCurveFinderGeneratorJacobian(new ParameterSensitivityCalculator(sensitivityCalculator), data);
  //    final double[] parameters = ROOT_FINDER.getRoot(curveCalculator, jacobianCalculator, new DoubleMatrix1D(initGuess)).getData();
  //    final YieldCurveBundle newCurves = data.getBuildingFunction().evaluate(new DoubleMatrix1D(parameters));
  //    final YieldCurveBundle bundle = knowData.copy();
  //    bundle.addAll(newCurves);
  //    final DoubleMatrix2D inverseJacobian;
  //    if (isPV) {
  //      final DoubleMatrix2D jacobianPV = jacobianCalculator.evaluate(new DoubleMatrix1D(parameters));
  //      final DoubleMatrix2D inverseJacobianPV = MATRIX_ALGEBRA.getInverse(jacobianPV);
  //      final double[][] inverseJacobianPVArray = inverseJacobianPV.getData();
  //      final int dim = inverseJacobianPV.getNumberOfColumns();
  //      final double[] pvmqs = new double[dim];
  //      // Implementation note: pvmqs: Present Value Sensitivity with respect to Market Quote.
  //      //   To be coherent, the pv calculator should provide a pv in the first currency of FX swaps and XCcy swaps.
  //      i = 0;
  //      for (final InstrumentDerivative ird : instruments) {
  //        pvmqs[i++] = ird.accept(PVBP_CALCULATOR, bundle);
  //      }
  //      final double[][] inverseJacobianArray = new double[dim][dim];
  //      for (int loopi = 0; loopi < dim; loopi++) {
  //        for (int loopj = 0; loopj < dim; loopj++) {
  //          inverseJacobianArray[loopi][loopj] = -inverseJacobianPVArray[loopi][loopj] * pvmqs[loopj];
  //        }
  //      }
  //      inverseJacobian = new DoubleMatrix2D(inverseJacobianArray);
  //    } else {
  //      final DoubleMatrix2D jacobian = jacobianCalculator.evaluate(new DoubleMatrix1D(parameters));
  //      inverseJacobian = MATRIX_ALGEBRA.getInverse(jacobian);
  //    }
  //    return new ObjectsPair<YieldCurveBundle, DoubleMatrix2D>(bundle, inverseJacobian);
  //  }
  //
  //  @SuppressWarnings({"unchecked"})
  //  /**
  //   * Build the curves and returns a pair containing
  //   * 1) the yield curve bundle (4 curves) and
  //   * 2) the inverse Jacobian (derivative of the curve parameters with respect to the market quotes) for the full bundle.
  //   * The curves are build in two blocks: first USD and then EUR.
  //   */
  //  public static Pair<YieldCurveBundle, DoubleMatrix2D> makeCurves2Blocks(final List<InstrumentDefinition<?>> dsc1Definitions, final List<InstrumentDefinition<?>> fwd1Definitions,
  //      final List<InstrumentDefinition<?>> dsc2Definitions, final List<InstrumentDefinition<?>> fwd2Definitions, final InstrumentDerivativeVisitorAdapter<YieldCurveBundle, Double> calculator,
  //      final InstrumentDerivativeVisitorAdapter<YieldCurveBundle, InterestRateCurveSensitivity> sensitivityCalculator, final boolean withToday, final boolean isPV) {
  //
  //    // First block
  //    final int nbDsc1 = dsc1Definitions.size();
  //    final int nbFwd1 = fwd1Definitions.size();
  //    final InstrumentDerivative[] instruments1 = new InstrumentDerivative[nbDsc1 + nbFwd1];
  //    final double[] dsc1Node = new double[nbDsc1];
  //    final double[] fwd1Node = new double[nbFwd1];
  //    final double[] initGuess1 = new double[nbDsc1 + nbFwd1];
  //    int i1 = 0;
  //    for (final InstrumentDefinition<?> instrument : dsc1Definitions) {
  //      InstrumentDerivative ird;
  //      if (instrument instanceof SwapFixedONDefinition) {
  //        final String[] curveNames = new String[] {CURVE_NAME_DSC_1, CURVE_NAME_DSC_1 };
  //        ird = ((SwapFixedONDefinition) instrument).toDerivative(NOW, withToday ? TS_FIXED_OIS_USD_WITH_TODAY : TS_FIXED_OIS_USD_WITHOUT_TODAY, curveNames);
  //      } else {
  //        final String[] curveNames = new String[] {CURVE_NAME_DSC_1 };
  //        ird = instrument.toDerivative(NOW, curveNames);
  //      }
  //      instruments1[i1] = ird;
  //      initGuess1[i1] = initialGuess(instrument);
  //      dsc1Node[i1++] = ird.accept(MATURITY_CALCULATOR);
  //    }
  //    int j1 = 0;
  //    for (final InstrumentDefinition<?> instrument : fwd1Definitions) {
  //      InstrumentDerivative ird;
  //      if (instrument instanceof SwapFixedIborDefinition) {
  //        final String[] curveNames = new String[] {CURVE_NAME_DSC_1, CURVE_NAME_FWD_1 };
  //        ird = ((SwapFixedIborDefinition) instrument).toDerivative(NOW, withToday ? TS_FIXED_IBOR_USD3M_WITH_TODAY : TS_FIXED_IBOR_USD3M_WITHOUT_TODAY, curveNames);
  //      } else {
  //        final String[] curveNames = new String[] {CURVE_NAME_FWD_1 };
  //        ird = instrument.toDerivative(NOW, curveNames);
  //      }
  //      instruments1[i1] = ird;
  //      initGuess1[i1++] = initialGuess(instrument);
  //      fwd1Node[j1++] = ird.accept(MATURITY_CALCULATOR);
  //    }
  //    final LinkedHashMap<String, GeneratorYDCurve> curveGenerators1 = new LinkedHashMap<String, GeneratorYDCurve>();
  //    curveGenerators1.put(CURVE_NAME_DSC_1, new GeneratorCurveYieldInterpolatedNode(dsc1Node, INTERPOLATOR));
  //    curveGenerators1.put(CURVE_NAME_FWD_1, new GeneratorCurveYieldInterpolatedNode(fwd1Node, INTERPOLATOR));
  //    final YieldCurveBundle knowData = new YieldCurveBundle(FX_MATRIX, CCY_MAP);
  //    final MultipleYieldCurveFinderGeneratorDataBundle data1 = new MultipleYieldCurveFinderGeneratorDataBundle(instruments1, knowData, curveGenerators1);
  //    final Function1D<DoubleMatrix1D, DoubleMatrix1D> curveCalculator1 = new MultipleYieldCurveFinderGeneratorFunction(calculator, data1);
  //    final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacobianCalculator1 = new MultipleYieldCurveFinderGeneratorJacobian(new ParameterSensitivityCalculator(sensitivityCalculator), data1);
  //    final double[] parameters1 = ROOT_FINDER.getRoot(curveCalculator1, jacobianCalculator1, new DoubleMatrix1D(initGuess1)).getData();
  //    final YieldCurveBundle newCurves = data1.getBuildingFunction().evaluate(new DoubleMatrix1D(parameters1));
  //    final YieldCurveBundle bundle1 = knowData.copy();
  //    bundle1.addAll(newCurves);
  //
  //    // Second block
  //    final int nbDsc2 = dsc2Definitions.size();
  //    final int nbFwd2 = fwd2Definitions.size();
  //    final InstrumentDerivative[] instruments2 = new InstrumentDerivative[nbDsc2 + nbFwd2];
  //    final double[] dsc2Node = new double[nbDsc2];
  //    final double[] fwd2Node = new double[nbFwd2];
  //    final double[] initGuess2 = new double[nbDsc2 + nbFwd2];
  //    int i2 = 0;
  //    for (final InstrumentDefinition<?> instrument : dsc2Definitions) {
  //      InstrumentDerivative ird;
  //      if (instrument instanceof SwapXCcyIborIborDefinition) {
  //        final String[] curveNames = new String[] {CURVE_NAME_DSC_2, CURVE_NAME_FWD_2, CURVE_NAME_DSC_1, CURVE_NAME_FWD_1 };
  //        ird = ((SwapXCcyIborIborDefinition) instrument).toDerivative(NOW, withToday ? TS_FIXED_IBOR_EURUSD3M_WITH_TODAY : TS_FIXED_IBOR_EURUSD3M_WITHOUT_TODAY, curveNames);
  //      } else {
  //        if (instrument instanceof CashDefinition) {
  //          final String[] curveNames = new String[] {CURVE_NAME_DSC_2 };
  //          ird = instrument.toDerivative(NOW, curveNames);
  //        } else {
  //          final String[] curveNames = new String[] {CURVE_NAME_DSC_2, CURVE_NAME_DSC_1 };
  //          ird = instrument.toDerivative(NOW, curveNames);
  //        }
  //      }
  //      instruments2[i2] = ird;
  //      initGuess2[i2] = initialGuess(instrument);
  //      dsc2Node[i2++] = ird.accept(MATURITY_CALCULATOR);
  //    }
  //    int j2 = 0;
  //    for (final InstrumentDefinition<?> instrument : fwd2Definitions) {
  //      InstrumentDerivative ird;
  //      if (instrument instanceof SwapFixedIborDefinition) {
  //        final String[] curveNames = new String[] {CURVE_NAME_DSC_2, CURVE_NAME_FWD_2 };
  //        ird = ((SwapFixedIborDefinition) instrument).toDerivative(NOW, withToday ? TS_FIXED_IBOR_EUR3M_WITH_TODAY : TS_FIXED_IBOR_EUR3M_WITHOUT_TODAY, curveNames);
  //      } else {
  //        final String[] curveNames = new String[] {CURVE_NAME_FWD_2 };
  //        ird = instrument.toDerivative(NOW, curveNames);
  //      }
  //      instruments2[i2] = ird;
  //      initGuess2[i2++] = initialGuess(instrument);
  //      fwd2Node[j2++] = ird.accept(MATURITY_CALCULATOR);
  //    }
  //
  //    final LinkedHashMap<String, GeneratorYDCurve> curveGenerators2 = new LinkedHashMap<String, GeneratorYDCurve>();
  //    curveGenerators2.put(CURVE_NAME_DSC_2, new GeneratorCurveYieldInterpolatedNode(dsc2Node, INTERPOLATOR));
  //    curveGenerators2.put(CURVE_NAME_FWD_2, new GeneratorCurveYieldInterpolatedNode(fwd2Node, INTERPOLATOR));
  //    final MultipleYieldCurveFinderGeneratorDataBundle data2 = new MultipleYieldCurveFinderGeneratorDataBundle(instruments2, bundle1, curveGenerators2);
  //    final Function1D<DoubleMatrix1D, DoubleMatrix1D> curveCalculator2 = new MultipleYieldCurveFinderGeneratorFunction(calculator, data2);
  //    final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacobianCalculator2 = new MultipleYieldCurveFinderGeneratorJacobian(new ParameterSensitivityCalculator(sensitivityCalculator), data2);
  //    final double[] parameters2 = ROOT_FINDER.getRoot(curveCalculator2, jacobianCalculator2, new DoubleMatrix1D(initGuess2)).getData();
  //    final YieldCurveBundle newCurves2 = data2.getBuildingFunction().evaluate(new DoubleMatrix1D(parameters2));
  //    final YieldCurveBundle bundle2 = bundle1.copy();
  //    bundle2.addAll(newCurves2);
  //
  //    final InstrumentDerivative[] instrumentsT = new InstrumentDerivative[nbDsc1 + nbFwd1 + nbDsc2 + nbFwd2];
  //    System.arraycopy(instruments1, 0, instrumentsT, 0, nbDsc1 + nbFwd1);
  //    System.arraycopy(instruments2, 0, instrumentsT, nbDsc1 + nbFwd1, nbDsc2 + nbFwd2);
  //    final LinkedHashMap<String, GeneratorYDCurve> curveGeneratorsT = new LinkedHashMap<String, GeneratorYDCurve>();
  //    curveGeneratorsT.put(CURVE_NAME_DSC_1, new GeneratorCurveYieldInterpolatedNode(dsc1Node, INTERPOLATOR));
  //    curveGeneratorsT.put(CURVE_NAME_FWD_1, new GeneratorCurveYieldInterpolatedNode(fwd1Node, INTERPOLATOR));
  //    curveGeneratorsT.put(CURVE_NAME_DSC_2, new GeneratorCurveYieldInterpolatedNode(dsc2Node, INTERPOLATOR));
  //    curveGeneratorsT.put(CURVE_NAME_FWD_2, new GeneratorCurveYieldInterpolatedNode(fwd2Node, INTERPOLATOR));
  //    final MultipleYieldCurveFinderGeneratorDataBundle dataT = new MultipleYieldCurveFinderGeneratorDataBundle(instrumentsT, knowData, curveGeneratorsT);
  //    final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacobianCalculatorT = new MultipleYieldCurveFinderGeneratorJacobian(new ParameterSensitivityCalculator(sensitivityCalculator), dataT);
  //    final double[] parametersT = new double[parameters1.length + parameters2.length];
  //    System.arraycopy(parameters1, 0, parametersT, 0, parameters1.length);
  //    System.arraycopy(parameters2, 0, parametersT, parameters1.length, parameters2.length);
  //    final DoubleMatrix2D inverseJacobian;
  //    if (isPV) {
  //      final DoubleMatrix2D jacobianPV = jacobianCalculatorT.evaluate(new DoubleMatrix1D(parametersT));
  //      final DoubleMatrix2D inverseJacobianPV = MATRIX_ALGEBRA.getInverse(jacobianPV);
  //      final double[][] inverseJacobianPVArray = inverseJacobianPV.getData();
  //      final int dim = inverseJacobianPV.getNumberOfColumns();
  //      final double[] pvmqs = new double[dim];
  //      // Implementation note: pvmqs: Present Value Sensitivity with respect to Market Quote.
  //      //   To be coherent, the pv calculator should provide a pv in the first currency of FX swaps and XCcy swaps.
  //      int i = 0;
  //      for (final InstrumentDerivative ird : instrumentsT) {
  //        pvmqs[i++] = ird.accept(PVBP_CALCULATOR, bundle2);
  //      }
  //      final double[][] inverseJacobianArray = new double[dim][dim];
  //      for (int loopi = 0; loopi < dim; loopi++) {
  //        for (int loopj = 0; loopj < dim; loopj++) {
  //          inverseJacobianArray[loopi][loopj] = -inverseJacobianPVArray[loopi][loopj] * pvmqs[loopj];
  //        }
  //      }
  //      inverseJacobian = new DoubleMatrix2D(inverseJacobianArray);
  //    } else {
  //      final DoubleMatrix2D jacobian = jacobianCalculatorT.evaluate(new DoubleMatrix1D(parametersT));
  //      inverseJacobian = MATRIX_ALGEBRA.getInverse(jacobian);
  //    }
  //    return new ObjectsPair<YieldCurveBundle, DoubleMatrix2D>(bundle2, inverseJacobian);
  //  }

}


text:
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using IFramework.Infrastructure.Logging;
using IFramework.IoC;
using Kafka.Client.Cfg;
using Kafka.Client.Cluster;
using Kafka.Client.Requests;

namespace Kafka.Client.Consumers
{
    internal class PartitionLeaderFinder
    {
        private const string clientId = "LeaderFetcher";
        public static ILogger Logger = IoCFactory.Resolve<ILoggerFactory>().Create(typeof(PartitionLeaderFinder));

        private static readonly int FailureRetryDelayMs = (int) TimeSpan.FromSeconds(5).TotalMilliseconds;

        private readonly Cluster.Cluster _brokers;

        private readonly ConsumerConfiguration _config;

        private readonly Action<PartitionTopicInfo, Broker> _createNewFetcher;

        private readonly ConcurrentQueue<PartitionTopicInfo> _partitionsNeedingLeader;

        private volatile bool _stop;

        public PartitionLeaderFinder(ConcurrentQueue<PartitionTopicInfo> partitionsNeedingLeaders,
                                     Cluster.Cluster brokers,
                                     ConsumerConfiguration config,
                                     Action<PartitionTopicInfo, Broker> createNewFetcher)
        {
            _partitionsNeedingLeader = partitionsNeedingLeaders;
            _brokers = brokers;
            _config = config;
            _createNewFetcher = createNewFetcher;
        }

        public void Start()
        {
            while (!_stop)
            {
                try
                {
                    if (_partitionsNeedingLeader.IsEmpty)
                    {
                        Thread.Sleep(_config.ConsumeGroupFindNewLeaderSleepIntervalMs);
                        continue;
                    }

                    PartitionTopicInfo partition;
                    if (_partitionsNeedingLeader.TryDequeue(out partition))
                    {
                        Logger.DebugFormat("Finding new leader for topic {0}, partition {1}", partition.Topic,
                                           partition.PartitionId);
                        Broker newLeader = null;
                        foreach (var broker in _brokers.Brokers)
                        {
                            var consumer = new Consumer(_config, broker.Value.Host, broker.Value.Port);
                            try
                            {
                                var metaData =
                                    consumer.GetMetaData(
                                                         TopicMetadataRequest.Create(new[] {partition.Topic}, 1, 0, clientId));
                                if (metaData != null && metaData.Any())
                                {
                                    var newPartitionData = metaData.First()
                                                                   .PartitionsMetadata
                                                                   .FirstOrDefault(p => p.PartitionId == partition.PartitionId);
                                    if (newPartitionData != null)
                                    {
                                        Logger.DebugFormat("New leader for {0} ({1}) is broker {2}", partition.Topic,
                                                           partition.PartitionId, newPartitionData.Leader.Id);
                                        newLeader = newPartitionData.Leader;
                                        break;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.WarnFormat("Error retrieving meta data from broker {0}: {1}", broker.Value.Id,
                                                  ex.FormatException());
                            }
                        }

                        if (newLeader == null)
                        {
                            Logger.ErrorFormat("New leader information could not be retrieved for {0} ({1})",
                                               partition.Topic, partition.PartitionId);
                        }
                        else
                        {
                            _createNewFetcher(partition, newLeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("PartitionLeaderFinder encountered an error: {0}", ex.FormatException());
                    Thread.Sleep(FailureRetryDelayMs);
                }
            }

            Logger.Info("Partition leader finder thread shutting down.");
        }

        public void Stop()
        {
            _stop = true;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ro.nextreports.engine.util;

/**
 * Created by IntelliJ IDEA.
 * User: mihai.panaitescu
 * Date: Feb 17, 2009
 * Time: 5:25:33 PM
 */
public class OS {

    private static final String osName;

    static {
        osName = System.getProperty("os.name");
    }

    /**
     * Returns true if the current operating system is
     * Microsoft Windows.
     */
    public static boolean isWindows() {
        return osName.startsWith("Windows");
    }

    /**
     * Returns true if the current operating system is
     * Linux.
     */
    public static boolean isLinux() {
        return osName.startsWith("Linux");
    }

    /**
     * Returns true if the current operating system is
     * Sun Microsystem's Solaris.
     */
    public static boolean isSolaris() {
        return osName.startsWith("Solaris");
    }

    /**
     * Returns true if the current operating system is
     * either Linux or Solaris. Need to add support of other OSes
     */
    public static boolean isUnix() {
        return isLinux() || isSolaris();
    }

}


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.jakefallin.rhsapp;

public final class Manifest {
    public static final class permission {
        public static final String C2D_MESSAGE="com.jakefallin.rhsapp.permission.C2D_MESSAGE";
    }
}


text:
'use strict';

/**
 * @ngdoc function
 * @name recappApp.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the recappApp
 */
angular.module('recappApp')
  .controller('OrganizationIndexCtrl', function($scope, Organization) {

    Organization.query(function(data) {
      $scope.organizations = data;
    });

  });


text:
package de.thi.mymusic.web.model;

import de.thi.mymusic.domain.Album;
import de.thi.mymusic.domain.Interpret;
import de.thi.mymusic.domain.SearchResultEntity;
import de.thi.mymusic.domain.Song;
import de.thi.mymusic.service.SearchService;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.List;

/**
 * Created by Michael on 05.11.2015.
 */
@Named
@SessionScoped
public class Search implements Serializable {

    private List<Album> albumResult;
    private List<Song> songResult;
    private List<Interpret> interpretResult;
    private String searchString;
    private SearchService searchService;

    @Inject
    public Search(SearchService searchService) {
        this.searchService = searchService;
    }

    //*******************************************************
    // Getter and Setter
    //*******************************************************

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public List<Album> getAlbumResult() {
        return albumResult;
    }

    public List<Song> getSongResult() {
        return songResult;
    }

    public List<Interpret> getInterpretResult() {
        return interpretResult;
    }

    public long getCountAlbumResult() {
        return albumResult.size();
    }

    public long getCountInterpretResult() {
        return interpretResult.size();
    }

    public long getCountSongResult() {
        return songResult.size();
    }

    //*******************************************************
    // Action Methods
    //*******************************************************
    public String doSearch(){
        albumResult = searchService.findAlbumByName(searchString);
        songResult = searchService.findSongByName(searchString);
        interpretResult = searchService.findInterpretByName(searchString);

        // Reset search string
        searchString = "";
        return "listSearchResult";
    }

    /**
     * CompleteSearchInput is responsible for ajax auto complete search values
     * @param query is search string
     * @return List of five SearchResultEntity
     */
    public List<SearchResultEntity> completeSearchInput(String query) {
        return searchService.findEntitiesByName(query);
    }
}


text:
package com.intellij.openapi.fileTypes.impl.associate.ui;

import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypesBundle;
import com.intellij.openapi.ui.DialogWrapper;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.List;

public class FileTypeAssociationDialog extends DialogWrapper {
  private FileTypeAssociationForm myForm;

  public FileTypeAssociationDialog() {
    super(false);
    init();
    setTitle(FileTypesBundle.message("filetype.associate.dialog.title"));
  }

  @Override
  protected @Nullable JComponent createCenterPanel() {
    myForm = new FileTypeAssociationForm();
    return myForm.getTopPanel();
  }

  @Override
  public @Nullable JComponent getPreferredFocusedComponent() {
    return myForm.getPreferredFocusedComponent();
  }

  public List<FileType> getSelectedFileTypes() {
    return myForm.getSelectedFileTypes();
  }
}


text:
<?php $TRANSLATIONS = array(
"Activity" => "Aktivität",
"No more activities to load." => "Keine weiteren Aktivitäten zum Laden.",
"Loading older activities" => "Lade ältere Aktivitäten",
"RSS feed" => "RSS-Feed",
"No activities yet." => "Bisher keine Aktivitäten.",
"You will see a list of events here when you start to use your %s." => "Sie werden hier eine Liste von Ereignissen sehen, sobald Sie Ihre %s nutzen."
);


text:
import smtplib
from email.mime.text import MIMEText

class GmailHandler():
	"""
	IMPORTANT NOTE:
	in order to access a gmail account with this handler,
	your account needs 'foreign-access' enabled (follow these steps):
	login to the account
	go here--> https://accounts.google.com/b/0/DisplayUnlockCaptcha
	press 'Continue'
	Done.
	"""

	def __init__(self, gmail, password):
		self.gmail = gmail
		self.password = password

	def send_mail(self, receivers, subject, text):

		if not isinstance(receivers, list):
			receivers = [receivers]

		# Send the message via our own SMTP server, but don't include the envelope header
		smtp = smtplib.SMTP("smtp.gmail.com", 587)
		smtp.ehlo()
		smtp.starttls()
		smtp.ehlo()
		smtp.login(self.gmail, self.password)

		for receiver in receivers:

			msg = MIMEText(text)
			msg['Subject'] = subject
			msg['From'] = self.gmail
			msg['To'] = receiver
			smtp.sendmail(self.gmail, receiver, str(msg))

		smtp.quit()


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace SSEF.Models.Models
{
    public class Student
    {

        [Key]
        public int ID { get; set; }

        public string Email { get; set; }

        [StringLength(50)]
        public string FirstName { get; set; }

        [StringLength(50)]
        public string LastName { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime EnrollmentDate { get; set; }

        public string Secret { get; set; }

        [Display(Name = "Full Name")]
        public string FullName
        {
            get
            {
                return FirstName + " " + LastName;
            }
        }

        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
}


text:
<?php

namespace ZendTest\ServiceManager\TestAsset;

use stdClass;
use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class WaitingAbstractFactory implements AbstractFactoryInterface
{
    public $waitingService = null;

    public $canCreateCallCount = 0;

    public $createNullService = false;

    public $throwExceptionWhenCreate = false;

    public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        $this->canCreateCallCount++;
        return $requestedName === $this->waitingService;
    }

    public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        if ($this->throwExceptionWhenCreate) {
            throw new FooException('E');
        }
        if ($this->createNullService) {
            return null;
        }
        return new stdClass;
    }
}


text:
/*
 * This file is generated by jOOQ.
*/
package com.jbsc.jooq.domain.tables.records;

import com.jbsc.jooq.domain.tables.SubscriptionData;

import java.sql.Timestamp;

import javax.annotation.Generated;

import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record5;
import org.jooq.Row5;
import org.jooq.impl.UpdatableRecordImpl;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.9.1"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class SubscriptionDataRecord extends UpdatableRecordImpl<SubscriptionDataRecord> implements Record5<Timestamp, Integer, Long, String, Boolean> {

    private static final long serialVersionUID = -1591455232;

    /**
     * Setter for public.subscription_data.date_of_delivery.
     */
    public void setDateOfDelivery(Timestamp value) {
        set(0, value);
    }

    /**
     * Getter for public.subscription_data.date_of_delivery.
     */
    public Timestamp getDateOfDelivery() {
        return (Timestamp) get(0);
    }

    /**
     * Setter for public.subscription_data.order_id.
     */
    public void setOrderId(Integer value) {
        set(1, value);
    }

    /**
     * Getter for public.subscription_data.order_id.
     */
    public Integer getOrderId() {
        return (Integer) get(1);
    }

    /**
     * Setter for public.subscription_data.subscription_no.
     */
    public void setSubscriptionNo(Long value) {
        set(2, value);
    }

    /**
     * Getter for public.subscription_data.subscription_no.
     */
    public Long getSubscriptionNo() {
        return (Long) get(2);
    }

    /**
     * Setter for public.subscription_data.delivery_status.
     */
    public void setDeliveryStatus(String value) {
        set(3, value);
    }

    /**
     * Getter for public.subscription_data.delivery_status.
     */
    public String getDeliveryStatus() {
        return (String) get(3);
    }

    /**
     * Setter for public.subscription_data.parent.
     */
    public void setParent(Boolean value) {
        set(4, value);
    }

    /**
     * Getter for public.subscription_data.parent.
     */
    public Boolean getParent() {
        return (Boolean) get(4);
    }

    // -------------------------------------------------------------------------
    // Primary key information
    // -------------------------------------------------------------------------

    /**
     * {@inheritDoc}
     */
    @Override
    public Record1<Long> key() {
        return (Record1) super.key();
    }

    // -------------------------------------------------------------------------
    // Record5 type implementation
    // -------------------------------------------------------------------------

    /**
     * {@inheritDoc}
     */
    @Override
    public Row5<Timestamp, Integer, Long, String, Boolean> fieldsRow() {
        return (Row5) super.fieldsRow();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Row5<Timestamp, Integer, Long, String, Boolean> valuesRow() {
        return (Row5) super.valuesRow();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Timestamp> field1() {
        return SubscriptionData.SUBSCRIPTION_DATA.DATE_OF_DELIVERY;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Integer> field2() {
        return SubscriptionData.SUBSCRIPTION_DATA.ORDER_ID;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Long> field3() {
        return SubscriptionData.SUBSCRIPTION_DATA.SUBSCRIPTION_NO;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field4() {
        return SubscriptionData.SUBSCRIPTION_DATA.DELIVERY_STATUS;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Boolean> field5() {
        return SubscriptionData.SUBSCRIPTION_DATA.PARENT;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Timestamp value1() {
        return getDateOfDelivery();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Integer value2() {
        return getOrderId();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Long value3() {
        return getSubscriptionNo();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value4() {
        return getDeliveryStatus();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Boolean value5() {
        return getParent();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SubscriptionDataRecord value1(Timestamp value) {
        setDateOfDelivery(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SubscriptionDataRecord value2(Integer value) {
        setOrderId(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SubscriptionDataRecord value3(Long value) {
        setSubscriptionNo(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SubscriptionDataRecord value4(String value) {
        setDeliveryStatus(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SubscriptionDataRecord value5(Boolean value) {
        setParent(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SubscriptionDataRecord values(Timestamp value1, Integer value2, Long value3, String value4, Boolean value5) {
        value1(value1);
        value2(value2);
        value3(value3);
        value4(value4);
        value5(value5);
        return this;
    }

    // -------------------------------------------------------------------------
    // Constructors
    // -------------------------------------------------------------------------

    /**
     * Create a detached SubscriptionDataRecord
     */
    public SubscriptionDataRecord() {
        super(SubscriptionData.SUBSCRIPTION_DATA);
    }

    /**
     * Create a detached, initialised SubscriptionDataRecord
     */
    public SubscriptionDataRecord(Timestamp dateOfDelivery, Integer orderId, Long subscriptionNo, String deliveryStatus, Boolean parent) {
        super(SubscriptionData.SUBSCRIPTION_DATA);

        set(0, dateOfDelivery);
        set(1, orderId);
        set(2, subscriptionNo);
        set(3, deliveryStatus);
        set(4, parent);
    }
}


text:
package org.hisp.dhis.sms.outbound;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

/**
 * Simple {@link OutboundSmsService sms service} storing the sms in a store and
 * forwards the request to a {@link OutboundSmsTransportService sms transport
 * service} for sending.
 */
@Transactional
public class DefaultOutboundSmsService
    implements OutboundSmsService
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private OutboundSmsStore outboundSmsStore;

    public void setOutboundSmsStore( OutboundSmsStore outboundSmsStore )
    {
        this.outboundSmsStore = outboundSmsStore;
    }

    // -------------------------------------------------------------------------
    // Implementation
    // -------------------------------------------------------------------------

    @Override
    public List<OutboundSms> getAllOutboundSms()
    {
        return outboundSmsStore.getAllOutboundSms();
    }

    @Override
    public List<OutboundSms> getOutboundSms( OutboundSmsStatus status )
    {
        return outboundSmsStore.get( status );
    }

    @Override
    public void updateOutboundSms( OutboundSms sms )
    {
        outboundSmsStore.updateOutboundSms( sms );
    }

    @Override
    public int saveOutboundSms( OutboundSms sms )
    {
        return outboundSmsStore.saveOutboundSms( sms );
    }

    @Override
    public void deleteById( Integer outboundSmsId )
    {
        OutboundSms sms = outboundSmsStore.getOutboundSmsbyId( outboundSmsId );
        outboundSmsStore.deleteOutboundSms( sms );
    }

    @Override
    public OutboundSms getOutboundSms( int id )
    {
        return outboundSmsStore.getOutboundSmsbyId( id );
    }

    @Override
    public List<OutboundSms> getOutboundSms( OutboundSmsStatus status, Integer min, Integer max )
    {
        return outboundSmsStore.get( status, min, max );
    }

    @Override
    public List<OutboundSms> getAllOutboundSms( Integer min, Integer max )
    {
        return outboundSmsStore.getAllOutboundSms( min, max );
    }
}


text:
package com.tinytimrob.ppse.nmo;

import java.util.LinkedHashMap;

public abstract class Integration
{
	public Integration(String id)
	{
		this.id = id;
	}

	public final String id;

	public abstract boolean isEnabled();

	public abstract void init() throws Exception;

	public abstract void update() throws Exception;

	public abstract void shutdown() throws Exception;

	public final LinkedHashMap<String, Action> actions = new LinkedHashMap<String, Action>();

	public final LinkedHashMap<String, Action> getActions()
	{
		return this.actions;
	}
}


text:
int a;
#pragma omp threadprivate(a, b)
#pragma omp parallel


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Gate extends CI_Controller {

	function __construct() {
		parent::__construct();
        if ( !isset($_SESSION['login']) ) {
			redirect('login');
		}
		$this->load->vars(load_default());
		$this->load->model('notif_model');
    }

	public function index()
	{
		$data['title'] = "Dashboard";
		$this->load->view('dashboard', $data);
	}

	public function unauthorized()
	{
		$data['title'] = "This Page is Unauthorized";
		$this->load->view('no-auth-page', $data);
	}

	public function all_notification()
	{
		$data['title'] = "Notifikasi";
		$data['menu_title'] = "Notifikasi";

		$notif_list = notif_list(0, 0, 10);
		$data['notif_list'] = $notif_list['notif_updates'];

		$this->load->view('all_notif', $data);
	}
}


text:
require 'rails_helper'

module StashApi
  RSpec.describe GeneralController, type: :controller do

  end
end


text:
/**@file
 * @addtogroup nrf_log Logger module
 * @ingroup    app_common
 *
 * @defgroup nrf_log_backend Backend of nrf_log
 * @{
 * @ingroup  nrf_log
 * @brief    The nrf_log backend interface.
 */

#ifndef NRF_LOG_BACKEND_H__
#define NRF_LOG_BACKEND_H__

#include "nrf_log_ctrl.h"
#include "sdk_errors.h"
#include <stdbool.h>

/**
 * @brief Function for initializing the logger backend.
 *
 * param blocking Set true if handler functions should block until completion.
 *
 * @return NRF_SUCCESS after successful initialization, error code otherwise.
 */
ret_code_t nrf_log_backend_init(bool blocking);

/**
 * @brief Function for returning a pointer to a function for handling standard
 * log entries (@ref NRF_LOG_ERROR, etc.).
 *
 * @return Pointer to a handler.
 */
nrf_log_std_handler_t nrf_log_backend_std_handler_get(void);

/**
 * @brief Function for returning a pointer to a function for handling
 * hexdumps (@ref NRF_LOG_HEXDUMP_ERROR, etc.).
 *
 * @return Pointer to a handler.
 */
nrf_log_hexdump_handler_t nrf_log_backend_hexdump_handler_get(void);

/**
 * @brief Function for blocking reading of a byte from the backend.
 *
 * @return Byte.
 */
uint8_t nrf_log_backend_getchar(void);
#endif // NRF_LOG_BACKEND_H__
/** @} */


text:
@interface PodsDummy_Pods_MFControlLibrary_Tests : NSObject
@end
@implementation PodsDummy_Pods_MFControlLibrary_Tests
@end


text:
"""
This test module focuses on typical-flow business logic tests with the API
resource classes. For RBAC tests of these classes, see the
'resources_policy_test.py' module.
"""
import logging
import mimetypes

import mock
import pecan
from testtools import testcase
import webtest

from barbican import api
from barbican.api import app
from barbican.api import controllers
from barbican.common import exception as excep
from barbican.common import hrefs
from barbican.common import utils as barbican_utils
import barbican.context
from barbican.model import models
from barbican.tests import utils

LOG = logging.getLogger(__name__)

def get_barbican_env(external_project_id):
    """Create and return a barbican.context for use with the RBAC decorator

    Injects the provided external_project_id.
    """
    kwargs = {'roles': None,
              'user': None,
              'project': external_project_id,
              'is_admin': True}
    ctx = barbican.context.RequestContext(**kwargs)
    ctx.policy_enforcer = None
    barbican_env = {'barbican.context': ctx}
    return barbican_env

def create_secret(id_ref="id", name="name",
                  algorithm=None, bit_length=None,
                  mode=None, encrypted_datum=None, content_type=None):
    """Generate a Secret entity instance."""
    info = {'id': id_ref,
            'name': name,
            'algorithm': algorithm,
            'bit_length': bit_length,
            'mode': mode}
    secret = models.Secret(info)
    secret.id = id_ref
    if encrypted_datum:
        secret.encrypted_data = [encrypted_datum]
    if content_type:
        content_meta = models.SecretStoreMetadatum('content_type',
                                                   content_type)
        secret.secret_store_metadata['content_type'] = content_meta
    return secret

def create_order_with_meta(id_ref="id", order_type="certificate", meta={},
                           status='PENDING'):
    """Generate an Order entity instance with Metadata."""
    order = models.Order()
    order.id = id_ref
    order.type = order_type
    order.meta = meta
    order.status = status
    return order

def validate_datum(test, datum):
    test.assertIsNone(datum.kek_meta_extended)
    test.assertIsNotNone(datum.kek_meta_project)
    test.assertTrue(datum.kek_meta_project.bind_completed)
    test.assertIsNotNone(datum.kek_meta_project.plugin_name)
    test.assertIsNotNone(datum.kek_meta_project.kek_label)

def create_container(id_ref, project_id=None, external_project_id=None):
    """Generate a Container entity instance."""
    container = models.Container()
    container.id = id_ref
    container.name = 'test name'
    container.type = 'rsa'
    container_secret = models.ContainerSecret()
    container_secret.container_id = id
    container_secret.secret_id = '123'
    container.container_secrets.append(container_secret)

    if project_id:
        project = models.Project()
        project.id = project_id
        project.external_id = external_project_id
        container.project = project
    return container

def create_consumer(container_id, id_ref):
    """Generate a ContainerConsumerMetadatum entity instance."""
    data = {
        'name': 'test name',
        'URL': 'http://test/url'
    }
    consumer = models.ContainerConsumerMetadatum(container_id, data)
    consumer.id = id_ref
    return consumer

class SecretAllowAllMimeTypesDecoratorTest(utils.BaseTestCase):

    def setUp(self):
        super(SecretAllowAllMimeTypesDecoratorTest, self).setUp()
        self.mimetype_values = set(mimetypes.types_map.values())

    @pecan.expose(generic=True)
    @barbican_utils.allow_all_content_types
    def _empty_pecan_exposed_function(self):
        pass

    def _empty_function(self):
        pass

    def test_mimetypes_successfully_added_to_mocked_function(self):
        empty_function = mock.MagicMock()
        empty_function._pecan = {}
        func = barbican_utils.allow_all_content_types(empty_function)
        cfg = func._pecan
        self.assertEqual(len(self.mimetype_values), len(cfg['content_types']))

    def test_mimetypes_successfully_added_to_pecan_exposed_function(self):
        cfg = self._empty_pecan_exposed_function._pecan
        self.assertEqual(len(self.mimetype_values), len(cfg['content_types']))

    def test_decorator_raises_if_function_not_pecan_exposed(self):
        self.assertRaises(AttributeError,
                          barbican_utils.allow_all_content_types,
                          self._empty_function)

class FunctionalTest(utils.BaseTestCase, utils.MockModelRepositoryMixin,
                     testcase.WithAttributes):

    def setUp(self):
        super(FunctionalTest, self).setUp()
        root = self.root
        config = {'app': {'root': root}}
        pecan.set_config(config, overwrite=True)
        self.app = webtest.TestApp(pecan.make_app(root))

    def tearDown(self):
        super(FunctionalTest, self).tearDown()
        pecan.set_config({}, overwrite=True)

    @property
    def root(self):
        return controllers.versions.VersionController()

class BaseSecretsResource(FunctionalTest):
    """Base test class for the Secrets resource."""

    def setUp(self):
        super(BaseSecretsResource, self).setUp()
        self.app = webtest.TestApp(app.build_wsgi_app(self.root))
        self.app.extra_environ = get_barbican_env(self.external_project_id)

    @property
    def root(self):
        self._init()

        class RootController(object):
            secrets = controllers.secrets.SecretsController()

        return RootController()

    def _init(self, payload=b'not-encrypted',
              payload_content_type='text/plain',
              payload_content_encoding=None):
        self.name = 'name'
        self.payload = payload
        self.payload_content_type = payload_content_type
        self.payload_content_encoding = payload_content_encoding
        self.secret_algorithm = 'AES'
        self.secret_bit_length = 256
        self.secret_mode = 'CBC'
        self.secret_req = {'name': self.name,
                           'algorithm': self.secret_algorithm,
                           'bit_length': self.secret_bit_length,
                           'creator_id': None,
                           'mode': self.secret_mode}
        if payload:
            self.secret_req['payload'] = payload
        if payload_content_type:
            self.secret_req['payload_content_type'] = payload_content_type
        if payload_content_encoding:
            self.secret_req['payload_content_encoding'] = (
                payload_content_encoding)

        # Set up mocked project
        self.external_project_id = 'keystone1234'
        self.project_entity_id = 'tid1234'
        self.project = models.Project()
        self.project.id = self.project_entity_id
        self.project.external_id = self.external_project_id

        # Set up mocked project repo
        self.project_repo = mock.MagicMock()
        self.project_repo.find_by_external_project_id.return_value = (
            self.project)
        self.setup_project_repository_mock(self.project_repo)

        # Set up mocked secret
        self.secret = models.Secret()
        self.secret.id = utils.generate_test_uuid(tail_value=1)

        # Set up mocked secret repo
        self.secret_repo = mock.MagicMock()
        self.secret_repo.create_from.return_value = self.secret
        self.setup_secret_repository_mock(self.secret_repo)

        # Set up mocked encrypted datum repo
        self.datum_repo = mock.MagicMock()
        self.datum_repo.create_from.return_value = None
        self.setup_encrypted_datum_repository_mock(self.datum_repo)

        # Set up mocked kek datum
        self.kek_datum = models.KEKDatum()
        self.kek_datum.kek_label = "kek_label"
        self.kek_datum.bind_completed = False
        self.kek_datum.algorithm = ''
        self.kek_datum.bit_length = 0
        self.kek_datum.mode = ''
        self.kek_datum.plugin_meta = ''

        # Set up mocked kek datum repo
        self.kek_repo = mock.MagicMock()
        self.kek_repo.find_or_create_kek_datum.return_value = self.kek_datum
        self.setup_kek_datum_repository_mock(self.kek_repo)

        # Set up mocked secret meta repo
        self.setup_secret_meta_repository_mock()

        # Set up mocked transport key
        self.transport_key = models.TransportKey(
            'default_plugin_name', 'XXXABCDEF')
        self.transport_key_id = 'tkey12345'
        self.tkey_url = hrefs.convert_transport_key_to_href(
            self.transport_key.id)

        # Set up mocked transport key
        self.setup_transport_key_repository_mock()

class WhenGettingPuttingOrDeletingSecretUsingSecretResource(FunctionalTest):
    def setUp(self):
        super(
            WhenGettingPuttingOrDeletingSecretUsingSecretResource, self
        ).setUp()
        self.app = webtest.TestApp(app.build_wsgi_app(self.root))
        self.app.extra_environ = get_barbican_env(self.external_project_id)

    @property
    def root(self):
        self._init()

        class RootController(object):
            secrets = controllers.secrets.SecretsController()

        return RootController()

    def _init(self):
        self.project_id = 'projectid1234'
        self.external_project_id = 'keystone1234'
        self.name = 'name1234'

        secret_id = utils.generate_test_uuid(tail_value=1)
        datum_id = "iddatum1"
        kek_id = "idkek1"

        self.secret_algorithm = "AES"
        self.secret_bit_length = 256
        self.secret_mode = "CBC"

        self.kek_project = models.KEKDatum()
        self.kek_project.id = kek_id
        self.kek_project.active = True
        self.kek_project.bind_completed = False
        self.kek_project.kek_label = "kek_label"

        self.datum = models.EncryptedDatum()
        self.datum.id = datum_id
        self.datum.secret_id = secret_id
        self.datum.kek_id = kek_id
        self.datum.kek_meta_project = self.kek_project
        self.datum.content_type = "text/plain"
        self.datum.cypher_text = "aaaa"  # base64 value.

        self.secret = create_secret(id_ref=secret_id,
                                    name=self.name,
                                    algorithm=self.secret_algorithm,
                                    bit_length=self.secret_bit_length,
                                    mode=self.secret_mode,
                                    encrypted_datum=self.datum,
                                    content_type=self.datum.content_type)

        self.secret.secret_acls = []
        self.secret.project = mock.MagicMock()
        self.secret.project.external_id = self.external_project_id

        # Set up mocked project
        self.project = models.Project()
        self.project.id = self.project_id
        self.project.external_id = self.external_project_id

        # Set up mocked project repo
        self.project_repo = mock.MagicMock()
        self.project_repo.get.return_value = self.project
        self.project_repo.find_by_external_project_id.return_value = (
            self.project)
        self.setup_project_repository_mock(self.project_repo)

        # Set up mocked secret repo
        self.secret_repo = mock.Mock()
        self.secret_repo.get = mock.Mock(return_value=self.secret)
        self.secret_repo.get_secret_by_id = mock.Mock(return_value=self.secret)
        self.secret_repo.delete_entity_by_id = mock.Mock(return_value=None)
        self.setup_secret_repository_mock(self.secret_repo)

        # Set up mocked encrypted datum repo
        self.datum_repo = mock.MagicMock()
        self.datum_repo.create_from.return_value = None
        self.setup_encrypted_datum_repository_mock(self.datum_repo)

        # Set up mocked kek datum repo
        self.setup_kek_datum_repository_mock()

        # Set up mocked secret meta repo
        self.secret_meta_repo = mock.MagicMock()
        self.secret_meta_repo.get_metadata_for_secret.return_value = None
        self.setup_secret_meta_repository_mock(self.secret_meta_repo)

        # Set up mocked transport key
        self.transport_key_model = models.TransportKey(
            "default_plugin", "my transport key")

        # Set up mocked transport key repo
        self.transport_key_repo = mock.MagicMock()
        self.transport_key_repo.get.return_value = self.transport_key_model
        self.setup_transport_key_repository_mock(self.transport_key_repo)

        self.transport_key_id = 'tkey12345'

    @mock.patch('barbican.plugin.resources.get_transport_key_id_for_retrieval')
    def test_should_get_secret_as_json(self, mock_get_transport_key):
        mock_get_transport_key.return_value = None
        resp = self.app.get(
            '/secrets/{0}/'.format(self.secret.id),
            headers={'Accept': 'application/json', 'Accept-Encoding': 'gzip'}
        )
        self.secret_repo.get_secret_by_id.assert_called_once_with(
            entity_id=self.secret.id,
            suppress_exception=True)
        self.assertEqual(resp.status_int, 200)

        self.assertNotIn('content_encodings', resp.namespace)
        self.assertIn('content_types', resp.namespace)
        self.assertIn(self.datum.content_type,
                      resp.namespace['content_types'].itervalues())
        self.assertNotIn('mime_type', resp.namespace)

    @testcase.attr('deprecated')
    @mock.patch('barbican.plugin.resources.get_secret')
    def test_should_get_secret_as_plain_based_on_content_type(self,
                                                              mock_get_secret):
        data = 'unencrypted_data'
        mock_get_secret.return_value = data

        resp = self.app.get(
            '/secrets/{0}/payload/'.format(self.secret.id),
            headers={'Accept': 'text/plain'}
        )

        self.secret_repo.get_secret_by_id.assert_called_once_with(
            entity_id=self.secret.id,
            suppress_exception=True)
        self.assertEqual(resp.status_int, 200)

        self.assertEqual(resp.body, data)
        mock_get_secret.assert_called_once_with(
            'text/plain',
            self.secret,
            self.project,
            None,
            None
        )

    @mock.patch('barbican.plugin.resources.get_secret')
    def test_should_get_secret_as_plain_with_twsk(self, mock_get_secret):
        data = 'encrypted_data'
        mock_get_secret.return_value = data

        twsk = "trans_wrapped_session_key"
        resp = self.app.get(
            ('/secrets/{0}/payload/'
             '?trans_wrapped_session_key={1}&transport_key_id={2}')
            .format(self.secret.id, twsk, self.transport_key_id),
            headers={'Accept': 'text/plain'}
        )

        self.secret_repo.get_secret_by_id.assert_called_once_with(
            entity_id=self.secret.id,
            suppress_exception=True)
        self.assertEqual(resp.status_int, 200)

        self.assertEqual(resp.body, data)
        mock_get_secret.assert_called_once_with(
            'text/plain',
            self.secret,
            self.project,
            twsk,
            self.transport_key_model.transport_key
        )

    @testcase.attr('deprecated')
    @mock.patch('barbican.plugin.resources.get_secret')
    def test_should_get_secret_as_plain_with_twsk_based_on_content_type(
            self, mock_get_secret):
        data = 'encrypted_data'
        mock_get_secret.return_value = data

        twsk = "trans_wrapped_session_key"
        resp = self.app.get(
            ('/secrets/{0}/'
             '?trans_wrapped_session_key={1}&transport_key_id={2}')
            .format(self.secret.id, twsk, self.transport_key_id),
            headers={'Accept': 'text/plain'}
        )

        self.secret_repo.get_secret_by_id.assert_called_once_with(
            entity_id=self.secret.id,
            suppress_exception=True)
        self.assertEqual(resp.status_int, 200)

        self.assertEqual(resp.body, data)
        mock_get_secret.assert_called_once_with(
            'text/plain',
            self.secret,
            self.project,
            twsk,
            self.transport_key_model.transport_key
        )

    @mock.patch('barbican.plugin.resources.get_secret')
    def test_should_throw_exception_for_get_when_twsk_but_no_tkey_id(
            self, mock_get_secret):
        data = 'encrypted_data'
        mock_get_secret.return_value = data

        twsk = "trans_wrapped_session_key"
        resp = self.app.get(
            '/secrets/{0}/payload/?trans_wrapped_session_key={1}'.format(
                self.secret.id, twsk),
            headers={'Accept': 'text/plain'},
            expect_errors=True
        )

        self.secret_repo.get_secret_by_id.assert_called_once_with(
            entity_id=self.secret.id,
            suppress_exception=True)
        self.assertEqual(resp.status_int, 400)

    @testcase.attr('deprecated')
    @mock.patch('barbican.plugin.resources.get_secret')
    def test_should_throw_exception_for_get_when_twsk_but_no_tkey_id_old_way(
            self, mock_get_secret):
        data = 'encrypted_data'
        mock_get_secret.return_value = data

        twsk = "trans_wrapped_session_key"
        resp = self.app.get(
            '/secrets/{0}/payload/?trans_wrapped_session_key={1}'.format(
                self.secret.id, twsk),
            headers={'Accept': 'text/plain'},
            expect_errors=True
        )

        self.secret_repo.get_secret_by_id.assert_called_once_with(
            entity_id=self.secret.id,
            suppress_exception=True)
        self.assertEqual(resp.status_int, 400)

    @mock.patch('barbican.plugin.resources.get_transport_key_id_for_retrieval')
    def test_should_get_secret_meta_for_binary(self, mock_get_transport_key):
        mock_get_transport_key.return_value = None
        self.datum.content_type = "application/octet-stream"
        self.secret.secret_store_metadata['content_type'].value = (
            self.datum.content_type
        )
        self.datum.cypher_text = 'aaaa'

        resp = self.app.get(
            '/secrets/{0}/'.format(self.secret.id),
            headers={'Accept': 'application/json', 'Accept-Encoding': 'gzip'}
        )

        self.secret_repo.get_secret_by_id.assert_called_once_with(
            entity_id=self.secret.id,
            suppress_exception=True)

        self.assertEqual(resp.status_int, 200)

        self.assertIsNotNone(resp.namespace)
        self.assertIn('content_types', resp.namespace)
        self.assertIn(self.datum.content_type,
                      resp.namespace['content_types'].itervalues())

    @mock.patch('barbican.plugin.resources.get_transport_key_id_for_retrieval')
    def test_should_get_secret_meta_for_binary_with_tkey(
            self, mock_get_transport_key_id):
        mock_get_transport_key_id.return_value = self.transport_key_id
        self.datum.content_type = "application/octet-stream"
        self.secret.secret_store_metadata['content_type'].value = (
            self.datum.content_type
        )
        self.datum.cypher_text = 'aaaa'

        resp = self.app.get(
            '/secrets/{0}/?transport_key_needed=true'.format(
                self.secret.id),
            headers={'Accept': 'application/json', 'Accept-Encoding': 'gzip'}
        )

        self.secret_repo.get_secret_by_id.assert_called_once_with(
            entity_id=self.secret.id,
            suppress_exception=True)

        self.assertEqual(resp.status_int, 200)

        self.assertIsNotNone(resp.namespace)
        self.assertIn('content_types', resp.namespace)
        self.assertIn(self.datum.content_type,
                      resp.namespace['content_types'].itervalues())
        self.assertIn('transport_key_ref', resp.namespace)
        self.assertEqual(
            resp.namespace['transport_key_ref'],
            hrefs.convert_transport_key_to_href(
                self.transport_key_id)
        )

    @testcase.attr('deprecated')
    @mock.patch('barbican.plugin.resources.get_secret')
    def test_should_get_secret_as_binary_based_on_content_type(
            self, mock_get_secret):
        data = 'unencrypted_data'
        mock_get_secret.return_value = data

        self.datum.content_type = "application/octet-stream"
        self.datum.cypher_text = 'aaaa'

        resp = self.app.get(
            '/secrets/{0}/'.format(self.secret.id),
            headers={
                'Accept': 'application/octet-stream',
                'Accept-Encoding': 'gzip'
            }
        )

        self.assertEqual(resp.body, data)

        mock_get_secret.assert_called_once_with(
            'application/octet-stream',
            self.secret,
            self.project,
            None,
            None
        )

    @mock.patch('barbican.plugin.resources.store_secret')
    def test_should_put_secret_as_plain_with_tkey_id(self, mock_store_secret):
        self.secret.encrypted_data = []
        self.secret.secret_store_metadata = {}

        resp = self.app.put(
            '/secrets/{0}/?transport_key_id={1}'.format(
                self.secret.id, self.transport_key_id),
            'plain text',
            headers={'Accept': 'text/plain', 'Content-Type': 'text/plain'},
        )

        self.assertEqual(resp.status_int, 204)

        mock_store_secret.assert_called_once_with(
            unencrypted_raw='plain text',
            content_type_raw='text/plain',
            content_encoding=None,
            secret_model=self.secret,
            project_model=self.project,
            transport_key_id=self.transport_key_id
        )

    @mock.patch('barbican.plugin.resources.store_secret')
    def test_should_put_secret_as_binary_with_tkey_id(self, mock_store_secret):
        self.secret.encrypted_data = []
        self.secret.secret_store_metadata = {}

        resp = self.app.put(
            '/secrets/{0}/?transport_key_id={1}'.format(
                self.secret.id, self.transport_key_id),
            'plain text',
            headers={
                'Accept': 'text/plain',
                'Content-Type': 'application/octet-stream'
            },
        )

        self.assertEqual(resp.status_int, 204)

        mock_store_secret.assert_called_once_with(
            unencrypted_raw='plain text',
            content_type_raw='application/octet-stream',
            content_encoding=None,
            secret_model=self.secret,
            project_model=self.project,
            transport_key_id=self.transport_key_id
        )

class WhenAddingNavigationHrefs(utils.BaseTestCase):

    def setUp(self):
        super(WhenAddingNavigationHrefs, self).setUp()

        self.resource_name = 'orders'
        self.external_project_id = '12345'
        self.num_elements = 100
        self.data = {}

    def test_add_nav_hrefs_adds_next_only(self):
        offset = 0
        limit = 10

        data_with_hrefs = hrefs.add_nav_hrefs(
            self.resource_name, offset, limit, self.num_elements, self.data)

        self.assertNotIn('previous', data_with_hrefs)
        self.assertIn('next', data_with_hrefs)

    def test_add_nav_hrefs_adds_both_next_and_previous(self):
        offset = 10
        limit = 10

        data_with_hrefs = hrefs.add_nav_hrefs(
            self.resource_name, offset, limit, self.num_elements, self.data)

        self.assertIn('previous', data_with_hrefs)
        self.assertIn('next', data_with_hrefs)

    def test_add_nav_hrefs_adds_previous_only(self):
        offset = 90
        limit = 10

        data_with_hrefs = hrefs.add_nav_hrefs(
            self.resource_name, offset, limit, self.num_elements, self.data)

        self.assertIn('previous', data_with_hrefs)
        self.assertNotIn('next', data_with_hrefs)

class TestingJsonSanitization(utils.BaseTestCase):

    def test_json_sanitization_without_array(self):
        json_without_array = {"name": "name", "algorithm": "AES",
                              "payload_content_type": "  text/plain   ",
                              "mode": "CBC", "bit_length": 256,
                              "payload": "not-encrypted"}

        self.assertTrue(json_without_array['payload_content_type']
                        .startswith(' '), "whitespace should be there")
        self.assertTrue(json_without_array['payload_content_type']
                        .endswith(' '), "whitespace should be there")
        api.strip_whitespace(json_without_array)
        self.assertFalse(json_without_array['payload_content_type']
                         .startswith(' '), "whitespace should be gone")
        self.assertFalse(json_without_array['payload_content_type']
                         .endswith(' '), "whitespace should be gone")

    def test_json_sanitization_with_array(self):
        json_with_array = {"name": "name", "algorithm": "AES",
                           "payload_content_type": "text/plain",
                           "mode": "CBC", "bit_length": 256,
                           "payload": "not-encrypted",
                           "an-array":
                           [{"name": " item 1"},
                            {"name": "item2 "}]}

        self.assertTrue(json_with_array['an-array'][0]['name']
                        .startswith(' '), "whitespace should be there")
        self.assertTrue(json_with_array['an-array'][1]['name']
                        .endswith(' '), "whitespace should be there")
        api.strip_whitespace(json_with_array)
        self.assertFalse(json_with_array['an-array'][0]['name']
                         .startswith(' '), "whitespace should be gone")
        self.assertFalse(json_with_array['an-array'][1]['name']
                         .endswith(' '), "whitespace should be gone")

class WhenCreatingConsumersUsingConsumersResource(FunctionalTest):
    def setUp(self):
        super(
            WhenCreatingConsumersUsingConsumersResource, self
        ).setUp()
        self.app = webtest.TestApp(app.build_wsgi_app(self.root))
        self.app.extra_environ = get_barbican_env(self.external_project_id)

    @property
    def root(self):
        self._init()

        class RootController(object):
            containers = controllers.containers.ContainersController()

        return RootController()

    def _init(self):
        self.name = 'test container name'
        self.type = 'generic'
        self.secret_refs = [
            {
                'name': 'test secret 1',
                'secret_ref': '1231'
            },
            {
                'name': 'test secret 2',
                'secret_ref': '1232'
            },
            {
                'name': 'test secret 3',
                'secret_ref': '1233'
            }
        ]

        self.consumer_ref = {
            'name': 'test_consumer1',
            'URL': 'http://consumer/1'
        }

        self.project_internal_id = 'projectid1234'
        self.external_project_id = 'keystoneid1234'

        # Set up mocked project
        self.project = models.Project()
        self.project.id = self.project_internal_id
        self.project.external_id = self.external_project_id

        # Set up mocked project repo
        self.project_repo = mock.MagicMock()
        self.project_repo.get.return_value = self.project
        self.setup_project_repository_mock(self.project_repo)

        # Set up mocked container
        self.container = create_container(
            id_ref='id1',
            project_id=self.project_internal_id,
            external_project_id=self.external_project_id)

        # Set up mocked container repo
        self.container_repo = mock.MagicMock()
        self.container_repo.get.return_value = self.container
        self.container_repo.get_container_by_id.return_value = self.container
        self.setup_container_repository_mock(self.container_repo)

        # Set up secret repo
        self.secret_repo = mock.MagicMock()
        self.secret_repo.create_from.return_value = None
        self.setup_secret_repository_mock(self.secret_repo)

        # Set up container consumer repo
        self.consumer_repo = mock.MagicMock()
        self.consumer_repo.create_from.return_value = None
        self.setup_container_consumer_repository_mock(self.consumer_repo)

        self.container_req = {'name': self.name,
                              'type': self.type,
                              'secret_refs': self.secret_refs}

    def test_should_add_new_consumer(self):
        resp = self.app.post_json(
            '/containers/{0}/consumers/'.format(self.container.id),
            self.consumer_ref
        )
        self.assertEqual(resp.status_int, 200)
        self.assertNotIn(self.external_project_id, resp.headers['Location'])

        args, kwargs = self.consumer_repo.create_or_update_from.call_args
        consumer = args[0]
        self.assertIsInstance(consumer, models.ContainerConsumerMetadatum)

    def test_should_fail_consumer_bad_json(self):
        resp = self.app.post(
            '/containers/{0}/consumers/'.format(self.container.id),
            '',
            expect_errors=True
        )
        self.assertEqual(resp.status_int, 415)

    def test_should_404_consumer_bad_container_id(self):
        self.container_repo.get.side_effect = excep.NotFound()
        resp = self.app.post_json(
            '/containers/{0}/consumers/'.format('bad_id'),
            self.consumer_ref, expect_errors=True
        )
        self.container_repo.get.side_effect = None
        self.assertEqual(resp.status_int, 404)

    def test_should_raise_exception_when_container_ref_doesnt_exist(self):
        self.container_repo.get.return_value = None
        resp = self.app.post_json(
            '/containers/{0}/consumers/'.format(self.container.id),
            self.consumer_ref,
            expect_errors=True
        )
        self.assertEqual(resp.status_int, 404)

class WhenGettingOrDeletingConsumersUsingConsumerResource(FunctionalTest):

    def setUp(self):
        super(
            WhenGettingOrDeletingConsumersUsingConsumerResource, self
        ).setUp()
        self.app = webtest.TestApp(app.build_wsgi_app(self.root))
        self.app.extra_environ = get_barbican_env(self.external_project_id)

    @property
    def root(self):
        self._init()

        class RootController(object):
            containers = controllers.containers.ContainersController()

        return RootController()

    def _init(self):
        self.external_project_id = 'keystoneid1234'
        self.project_internal_id = 'projectid1234'

        # Set up mocked project
        self.project = models.Project()
        self.project.id = self.project_internal_id
        self.project.external_id = self.external_project_id

        # Set up mocked project repo
        self.project_repo = mock.MagicMock()
        self.project_repo.get.return_value = self.project
        self.setup_project_repository_mock(self.project_repo)

        # Set up mocked container
        self.container = create_container(
            id_ref='id1',
            project_id=self.project_internal_id,
            external_project_id=self.external_project_id)

        # Set up mocked consumers
        self.consumer = create_consumer(self.container.id, id_ref='id2')
        self.consumer2 = create_consumer(self.container.id, id_ref='id3')

        self.consumer_ref = {
            'name': self.consumer.name,
            'URL': self.consumer.URL
        }

        # Set up mocked container repo
        self.container_repo = mock.MagicMock()
        self.container_repo.get.return_value = self.container
        self.container_repo.get_container_by_id.return_value = self.container
        self.setup_container_repository_mock(self.container_repo)

        # Set up mocked container consumer repo
        self.consumer_repo = mock.MagicMock()
        self.consumer_repo.get_by_values.return_value = self.consumer
        self.consumer_repo.delete_entity_by_id.return_value = None
        self.setup_container_consumer_repository_mock(self.consumer_repo)

        # Set up mocked secret repo
        self.setup_secret_repository_mock()

    def test_should_get_consumer(self):
        ret_val = ([self.consumer], 0, 0, 1)
        self.consumer_repo.get_by_container_id.return_value = ret_val

        resp = self.app.get('/containers/{0}/consumers/'.format(
            self.container.id
        ))
        self.assertEqual(resp.status_int, 200)

        self.consumer_repo.get_by_container_id.assert_called_once_with(
            self.container.id,
            limit_arg=None,
            offset_arg=0,
            suppress_exception=True
        )

        self.assertEqual(self.consumer.name, resp.json['consumers'][0]['name'])
        self.assertEqual(self.consumer.URL, resp.json['consumers'][0]['URL'])

    def test_should_404_with_bad_container_id(self):
        self.container_repo.get.side_effect = excep.NotFound()
        resp = self.app.get('/containers/{0}/consumers/'.format(
            'bad_id'
        ), expect_errors=True)
        self.container_repo.get.side_effect = None
        self.assertEqual(resp.status_int, 404)

    def test_should_get_consumer_by_id(self):
        self.consumer_repo.get.return_value = self.consumer
        resp = self.app.get('/containers/{0}/consumers/{1}/'.format(
            self.container.id, self.consumer.id
        ))
        self.assertEqual(resp.status_int, 200)

    def test_should_404_with_bad_consumer_id(self):
        self.consumer_repo.get.return_value = None
        resp = self.app.get('/containers/{0}/consumers/{1}/'.format(
            self.container.id, 'bad_id'
        ), expect_errors=True)
        self.assertEqual(resp.status_int, 404)

    def test_should_get_no_consumers(self):
        self.consumer_repo.get_by_container_id.return_value = ([], 0, 0, 0)
        resp = self.app.get('/containers/{0}/consumers/'.format(
            self.container.id
        ))
        self.assertEqual(resp.status_int, 200)

    def test_should_delete_consumer(self):
        self.app.delete_json('/containers/{0}/consumers/'.format(
            self.container.id
        ), self.consumer_ref)

        self.consumer_repo.delete_entity_by_id.assert_called_once_with(
            self.consumer.id, self.external_project_id)

    def test_should_fail_deleting_consumer_bad_json(self):
        resp = self.app.delete(
            '/containers/{0}/consumers/'.format(self.container.id),
            '',
            expect_errors=True
        )
        self.assertEqual(resp.status_int, 415)

    def test_should_404_on_delete_when_consumer_not_found(self):
        old_return = self.consumer_repo.get_by_values.return_value
        self.consumer_repo.get_by_values.return_value = None
        resp = self.app.delete_json('/containers/{0}/consumers/'.format(
            self.container.id
        ), self.consumer_ref, expect_errors=True)
        self.consumer_repo.get_by_values.return_value = old_return
        self.assertEqual(resp.status_int, 404)
        # Error response should have json content type
        self.assertEqual(resp.content_type, "application/json")

    def test_should_404_on_delete_when_consumer_not_found_later(self):
        self.consumer_repo.delete_entity_by_id.side_effect = excep.NotFound()
        resp = self.app.delete_json('/containers/{0}/consumers/'.format(
            self.container.id
        ), self.consumer_ref, expect_errors=True)
        self.consumer_repo.delete_entity_by_id.side_effect = None
        self.assertEqual(resp.status_int, 404)
        # Error response should have json content type
        self.assertEqual(resp.content_type, "application/json")

    def test_should_delete_consumers_on_container_delete(self):
        consumers = [self.consumer, self.consumer2]
        ret_val = (consumers, 0, 0, 1)
        self.consumer_repo.get_by_container_id.return_value = ret_val

        resp = self.app.delete(
            '/containers/{0}/'.format(self.container.id)
        )
        self.assertEqual(resp.status_int, 204)

        # Verify consumers were deleted
        calls = []
        for consumer in consumers:
            calls.append(mock.call(consumer.id, self.external_project_id))
        self.consumer_repo.delete_entity_by_id.assert_has_calls(
            calls, any_order=True
        )

    def test_should_pass_on_container_delete_with_missing_consumers(self):
        consumers = [self.consumer, self.consumer2]
        ret_val = (consumers, 0, 0, 1)
        self.consumer_repo.get_by_container_id.return_value = ret_val
        self.consumer_repo.delete_entity_by_id.side_effect = excep.NotFound

        resp = self.app.delete(
            '/containers/{0}/'.format(self.container.id)
        )
        self.assertEqual(resp.status_int, 204)

        # Verify consumers were deleted
        calls = []
        for consumer in consumers:
            calls.append(mock.call(consumer.id, self.external_project_id))
        self.consumer_repo.delete_entity_by_id.assert_has_calls(
            calls, any_order=True
        )

class WhenPerformingUnallowedOperationsOnConsumers(FunctionalTest):
    def setUp(self):
        super(
            WhenPerformingUnallowedOperationsOnConsumers, self
        ).setUp()
        self.app = webtest.TestApp(app.build_wsgi_app(self.root))
        self.app.extra_environ = get_barbican_env(self.external_project_id)

    @property
    def root(self):
        self._init()

        class RootController(object):
            containers = controllers.containers.ContainersController()

        return RootController()

    def _init(self):
        self.name = 'test container name'
        self.type = 'generic'
        self.secret_refs = [
            {
                'name': 'test secret 1',
                'secret_ref': '1231'
            },
            {
                'name': 'test secret 2',
                'secret_ref': '1232'
            },
            {
                'name': 'test secret 3',
                'secret_ref': '1233'
            }
        ]

        self.consumer_ref = {
            'name': 'test_consumer1',
            'URL': 'http://consumer/1'
        }
        self.external_project_id = 'keystoneid1234'
        self.project_internal_id = 'projectid1234'

        # Set up mocked project
        self.project = models.Project()
        self.project.id = self.project_internal_id
        self.project.external_id = self.external_project_id

        # Set up mocked project repo
        self.project_repo = mock.MagicMock()
        self.project_repo.get.return_value = self.project
        self.setup_project_repository_mock(self.project_repo)

        # Set up mocked container
        self.container = create_container(
            id_ref='id1',
            project_id=self.project_internal_id,
            external_project_id=self.external_project_id)

        # Set up mocked container consumers
        self.consumer = create_consumer(self.container.id, id_ref='id2')
        self.consumer2 = create_consumer(self.container.id, id_ref='id3')

        self.consumer_ref = {
            'name': self.consumer.name,
            'URL': self.consumer.URL
        }

        # Set up container repo
        self.container_repo = mock.MagicMock()
        self.container_repo.get.return_value = self.container
        self.setup_container_repository_mock(self.container_repo)

        # Set up container consumer repo
        self.consumer_repo = mock.MagicMock()
        self.consumer_repo.get_by_values.return_value = self.consumer
        self.consumer_repo.delete_entity_by_id.return_value = None
        self.setup_container_consumer_repository_mock(self.consumer_repo)

        # Set up secret repo
        self.setup_secret_repository_mock()

    def test_should_not_allow_put_on_consumers(self):
        ret_val = ([self.consumer], 0, 0, 1)
        self.consumer_repo.get_by_container_id.return_value = ret_val

        resp = self.app.put_json(
            '/containers/{0}/consumers/'.format(self.container.id),
            self.consumer_ref,
            expect_errors=True
        )
        self.assertEqual(resp.status_int, 405)

    def test_should_not_allow_post_on_consumer_by_id(self):
        self.consumer_repo.get.return_value = self.consumer
        resp = self.app.post_json(
            '/containers/{0}/consumers/{1}/'.format(self.container.id,
                                                    self.consumer.id),
            self.consumer_ref,
            expect_errors=True
        )
        self.assertEqual(resp.status_int, 405)

    def test_should_not_allow_put_on_consumer_by_id(self):
        self.consumer_repo.get.return_value = self.consumer
        resp = self.app.put_json(
            '/containers/{0}/consumers/{1}/'.format(self.container.id,
                                                    self.consumer.id),
            self.consumer_ref,
            expect_errors=True
        )
        self.assertEqual(resp.status_int, 405)

    def test_should_not_allow_delete_on_consumer_by_id(self):
        self.consumer_repo.get.return_value = self.consumer
        resp = self.app.delete(
            '/containers/{0}/consumers/{1}/'.format(self.container.id,
                                                    self.consumer.id),
            expect_errors=True
        )
        self.assertEqual(resp.status_int, 405)