answer
stringlengths
17
10.2M
package com.opengamma.analytics.financial.instrument; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.testng.collections.Sets; import org.threeten.bp.Period; import org.threeten.bp.ZoneOffset; import org.threeten.bp.ZonedDateTime; import com.mcleodmoores.date.WeekendWorkingDayCalendar; import com.mcleodmoores.date.WorkingDayCalendar; import com.opengamma.analytics.financial.ExerciseDecisionType; import com.opengamma.analytics.financial.commodity.definition.AgricultureForwardDefinition; import com.opengamma.analytics.financial.commodity.definition.AgricultureFutureDefinition; import com.opengamma.analytics.financial.commodity.definition.AgricultureFutureOptionDefinition; import com.opengamma.analytics.financial.commodity.definition.EnergyForwardDefinition; import com.opengamma.analytics.financial.commodity.definition.EnergyFutureDefinition; import com.opengamma.analytics.financial.commodity.definition.EnergyFutureOptionDefinition; import com.opengamma.analytics.financial.commodity.definition.MetalForwardDefinition; import com.opengamma.analytics.financial.commodity.definition.MetalFutureDefinition; import com.opengamma.analytics.financial.commodity.definition.MetalFutureOptionDefinition; import com.opengamma.analytics.financial.commodity.definition.SettlementType; import com.opengamma.analytics.financial.equity.future.definition.EquityIndexDividendFutureDefinition; import com.opengamma.analytics.financial.equity.future.definition.IndexFutureDefinition; import com.opengamma.analytics.financial.equity.option.EquityIndexFutureOptionDefinition; import com.opengamma.analytics.financial.equity.option.EquityIndexOptionDefinition; import com.opengamma.analytics.financial.equity.option.EquityOptionDefinition; import com.opengamma.analytics.financial.equity.variance.EquityVarianceSwapDefinition; import com.opengamma.analytics.financial.forex.definition.ForexDefinition; import com.opengamma.analytics.financial.forex.definition.ForexNonDeliverableForwardDefinition; import com.opengamma.analytics.financial.forex.definition.ForexNonDeliverableOptionDefinition; import com.opengamma.analytics.financial.forex.definition.ForexOptionDigitalDefinition; import com.opengamma.analytics.financial.forex.definition.ForexOptionSingleBarrierDefinition; import com.opengamma.analytics.financial.forex.definition.ForexOptionVanillaDefinition; import com.opengamma.analytics.financial.forex.definition.ForexSwapDefinition; import com.opengamma.analytics.financial.instrument.annuity.AnnuityCouponCMSDefinition; import com.opengamma.analytics.financial.instrument.annuity.AnnuityCouponFixedDefinition; import com.opengamma.analytics.financial.instrument.annuity.AnnuityCouponIborDefinition; import com.opengamma.analytics.financial.instrument.annuity.AnnuityCouponIborSpreadDefinition; import com.opengamma.analytics.financial.instrument.annuity.AnnuityDefinition; import com.opengamma.analytics.financial.instrument.bond.BillSecurityDefinition; import com.opengamma.analytics.financial.instrument.bond.BillTransactionDefinition; import com.opengamma.analytics.financial.instrument.bond.BondCapitalIndexedSecurityDefinition; import com.opengamma.analytics.financial.instrument.bond.BondCapitalIndexedTransactionDefinition; import com.opengamma.analytics.financial.instrument.bond.BondFixedSecurityDefinition; import com.opengamma.analytics.financial.instrument.bond.BondFixedTransactionDefinition; import com.opengamma.analytics.financial.instrument.bond.BondIborSecurityDefinition; import com.opengamma.analytics.financial.instrument.bond.BondIborTransactionDefinition; import com.opengamma.analytics.financial.instrument.cash.CashDefinition; import com.opengamma.analytics.financial.instrument.cash.DepositCounterpartDefinition; import com.opengamma.analytics.financial.instrument.cash.DepositIborDefinition; import com.opengamma.analytics.financial.instrument.cash.DepositZeroDefinition; import com.opengamma.analytics.financial.instrument.cds.ISDACDSDefinition; import com.opengamma.analytics.financial.instrument.cds.ISDACDSPremiumDefinition; import com.opengamma.analytics.financial.instrument.fra.ForwardRateAgreementDefinition; import com.opengamma.analytics.financial.instrument.future.BondFutureDefinition; import com.opengamma.analytics.financial.instrument.future.BondFutureOptionPremiumSecurityDefinition; import com.opengamma.analytics.financial.instrument.future.BondFutureOptionPremiumTransactionDefinition; import com.opengamma.analytics.financial.instrument.future.FederalFundsFutureSecurityDefinition; import com.opengamma.analytics.financial.instrument.future.FederalFundsFutureTransactionDefinition; import com.opengamma.analytics.financial.instrument.future.FutureInstrumentsDescriptionDataSet; import com.opengamma.analytics.financial.instrument.future.InterestRateFutureOptionMarginSecurityDefinition; import com.opengamma.analytics.financial.instrument.future.InterestRateFutureOptionMarginTransactionDefinition; import com.opengamma.analytics.financial.instrument.future.InterestRateFutureOptionPremiumSecurityDefinition; import com.opengamma.analytics.financial.instrument.future.InterestRateFutureOptionPremiumTransactionDefinition; import com.opengamma.analytics.financial.instrument.future.InterestRateFutureSecurityDefinition; import com.opengamma.analytics.financial.instrument.future.SwapFuturesPriceDeliverableSecurityDefinition; import com.opengamma.analytics.financial.instrument.index.GeneratorSwapXCcyIborIbor; import com.opengamma.analytics.financial.instrument.index.IborIndex; import com.opengamma.analytics.financial.instrument.index.IndexON; import com.opengamma.analytics.financial.instrument.index.IndexPrice; import com.opengamma.analytics.financial.instrument.index.IndexSwap; import com.opengamma.analytics.financial.instrument.inflation.CouponInflationZeroCouponInterpolationDefinition; import com.opengamma.analytics.financial.instrument.inflation.CouponInflationZeroCouponInterpolationGearingDefinition; import com.opengamma.analytics.financial.instrument.inflation.CouponInflationZeroCouponMonthlyDefinition; import com.opengamma.analytics.financial.instrument.inflation.CouponInflationZeroCouponMonthlyGearingDefinition; import com.opengamma.analytics.financial.instrument.payment.CapFloorCMSDefinition; import com.opengamma.analytics.financial.instrument.payment.CapFloorCMSSpreadDefinition; import com.opengamma.analytics.financial.instrument.payment.CapFloorIborDefinition; import com.opengamma.analytics.financial.instrument.payment.CouponCMSDefinition; import com.opengamma.analytics.financial.instrument.payment.CouponFixedDefinition; import com.opengamma.analytics.financial.instrument.payment.CouponIborCompoundingDefinition; import com.opengamma.analytics.financial.instrument.payment.CouponIborDefinition; import com.opengamma.analytics.financial.instrument.payment.CouponIborGearingDefinition; import com.opengamma.analytics.financial.instrument.payment.CouponIborRatchetDefinition; import com.opengamma.analytics.financial.instrument.payment.CouponIborSpreadDefinition; import com.opengamma.analytics.financial.instrument.payment.CouponONDefinition; import com.opengamma.analytics.financial.instrument.payment.CouponONSimplifiedDefinition; import com.opengamma.analytics.financial.instrument.payment.PaymentFixedDefinition; import com.opengamma.analytics.financial.instrument.swap.SwapDefinition; import com.opengamma.analytics.financial.instrument.swap.SwapFixedIborDefinition; import com.opengamma.analytics.financial.instrument.swap.SwapFixedIborSpreadDefinition; import com.opengamma.analytics.financial.instrument.swap.SwapIborIborDefinition; import com.opengamma.analytics.financial.instrument.swap.SwapXCcyIborIborDefinition; import com.opengamma.analytics.financial.instrument.swaption.SwaptionBermudaFixedIborDefinition; import com.opengamma.analytics.financial.instrument.swaption.SwaptionCashFixedIborDefinition; import com.opengamma.analytics.financial.instrument.swaption.SwaptionInstrumentsDescriptionDataSet; import com.opengamma.analytics.financial.instrument.swaption.SwaptionPhysicalFixedIborDefinition; import com.opengamma.analytics.financial.instrument.swaption.SwaptionPhysicalFixedIborSpreadDefinition; import com.opengamma.analytics.financial.instrument.varianceswap.VarianceSwapDefinition; import com.opengamma.analytics.financial.interestrate.ContinuousInterestRate; import com.opengamma.analytics.financial.interestrate.InstrumentDerivative; import com.opengamma.analytics.financial.model.option.definition.Barrier; import com.opengamma.analytics.financial.model.option.definition.Barrier.BarrierType; import com.opengamma.analytics.financial.model.option.definition.Barrier.KnockType; import com.opengamma.analytics.financial.model.option.definition.Barrier.ObservationType; import com.opengamma.financial.convention.StubType; import com.opengamma.financial.convention.businessday.BusinessDayConvention; import com.opengamma.financial.convention.businessday.BusinessDayConventions; import com.opengamma.financial.convention.calendar.Calendar; import com.opengamma.financial.convention.calendar.MondayToFridayCalendar; import com.opengamma.financial.convention.daycount.DayCount; import com.opengamma.financial.convention.daycount.DayCounts; import com.opengamma.financial.convention.frequency.PeriodFrequency; import com.opengamma.financial.convention.yield.SimpleYieldConvention; import com.opengamma.id.ExternalId; import com.opengamma.timeseries.DoubleTimeSeries; import com.opengamma.timeseries.date.localdate.ImmutableLocalDateDoubleTimeSeries; import com.opengamma.timeseries.precise.zdt.ImmutableZonedDateTimeDoubleTimeSeries; import com.opengamma.timeseries.precise.zdt.ZonedDateTimeDoubleTimeSeries; import com.opengamma.util.money.Currency; import com.opengamma.util.time.DateUtils; @SuppressWarnings("unchecked") public class TestInstrumentDefinitionsAndDerivatives { public static final Currency CUR = Currency.USD; public static final BusinessDayConvention BD = BusinessDayConventions.FOLLOWING; public static final WorkingDayCalendar C = WeekendWorkingDayCalendar.SATURDAY_SUNDAY; public static final Calendar OLD_C = new MondayToFridayCalendar("F"); public static final ZonedDateTime SETTLE_DATE = DateUtils.getUTCDate(2011, 1, 1); public static final Period TENOR = Period.ofYears(2); public static final Period FIXED_PERIOD = Period.ofMonths(6); public static final DayCount FIXED_DAY_COUNT = DayCounts.THIRTY_U_360; public static final boolean IS_EOM = true; public static final double NOTIONAL = 100000000; // 100m public static final double FIXED_RATE = 0.05; public static final boolean IS_PAYER = true; public static final Period IBOR_PERIOD_1 = Period.ofMonths(3); public static final int SPOT_LAG = 2; public static final DayCount IBOR_DAY_COUNT = DayCounts.ACT_360; public static final IborIndex IBOR_INDEX_1 = new IborIndex(CUR, IBOR_PERIOD_1, SPOT_LAG, IBOR_DAY_COUNT, BD, IS_EOM, "Ibor1"); public static final IndexON INDEX_ON = new IndexON("A", CUR, FIXED_DAY_COUNT, 0); public static final IndexSwap CMS_INDEX = new IndexSwap(IBOR_PERIOD_1, IBOR_DAY_COUNT, IBOR_INDEX_1, IBOR_PERIOD_1, OLD_C); public static final Period IBOR_PERIOD_2 = Period.ofMonths(6); public static final IborIndex IBOR_INDEX_2 = new IborIndex(CUR, IBOR_PERIOD_2, SPOT_LAG, IBOR_DAY_COUNT, BD, IS_EOM, "Ibor2"); public static final double SPREAD = 0.001; public static final GeneratorSwapXCcyIborIbor XCCY_GENERATOR = new GeneratorSwapXCcyIborIbor("XCCY", IBOR_INDEX_2, IBOR_INDEX_1, OLD_C, OLD_C); public static final IndexPrice INDEX_PRICE = new IndexPrice("CPI", CUR); public static final Convention CONVENTION = new Convention(2, FIXED_DAY_COUNT, BD, OLD_C, ""); public static final ISDACDSPremiumDefinition ISDA_PREMIUM = ISDACDSPremiumDefinition.from(SETTLE_DATE, SETTLE_DATE.plusYears(5), PeriodFrequency.SEMI_ANNUAL, CONVENTION, StubType.LONG_END, false, NOTIONAL, SPREAD, CUR, OLD_C); public static final CouponFixedDefinition COUPON_FIXED = CouponFixedDefinition.from(CUR, SETTLE_DATE, SETTLE_DATE, SETTLE_DATE, SPOT_LAG, NOTIONAL, FIXED_RATE); public static final CouponIborDefinition COUPON_IBOR = CouponIborDefinition.from(NOTIONAL, SETTLE_DATE, IBOR_INDEX_1, OLD_C); public static final CouponIborGearingDefinition COUPON_IBOR_GEARING = CouponIborGearingDefinition.from(COUPON_IBOR, 0.3, 2); public static final CouponIborSpreadDefinition COUPON_IBOR_SPREAD = CouponIborSpreadDefinition.from(COUPON_IBOR, 0.3); public static final CouponIborCompoundingDefinition COUPON_IBOR_COMPOUNDED = CouponIborCompoundingDefinition.from(NOTIONAL, SETTLE_DATE, TENOR, IBOR_INDEX_1, OLD_C); public static final CouponIborRatchetDefinition COUPON_IBOR_RATCHET = new CouponIborRatchetDefinition(CUR, SETTLE_DATE.plusMonths(3), SETTLE_DATE, SETTLE_DATE.plusMonths(3), 0.01, NOTIONAL, SETTLE_DATE.plusMonths(1), IBOR_INDEX_1, new double[] { 1, 2, 3 }, new double[] { 3, 4, 5 }, new double[] { 5, 6, 7 }, OLD_C); public static final CouponCMSDefinition COUPON_CMS = CouponCMSDefinition.from(CouponIborDefinition.from(1000, SETTLE_DATE, IBOR_INDEX_1, OLD_C), CMS_INDEX, OLD_C); public static final CouponONSimplifiedDefinition COUPON_OIS_SIMPLIFIED = CouponONSimplifiedDefinition.from(INDEX_ON, SETTLE_DATE, SETTLE_DATE.plusDays(28), NOTIONAL, 2, OLD_C); public static final CouponONDefinition COUPON_OIS = CouponONDefinition.from(INDEX_ON, SETTLE_DATE, SETTLE_DATE.plusYears(1), NOTIONAL, SPOT_LAG, OLD_C); public static final CouponInflationZeroCouponMonthlyDefinition INFLATION_ZERO_COUPON = CouponInflationZeroCouponMonthlyDefinition.from(SETTLE_DATE, SETTLE_DATE.plusMonths(3), NOTIONAL, INDEX_PRICE, 1, 1, true); public static final CouponInflationZeroCouponInterpolationDefinition INFLATION_INTERPOLATED_COUPON = CouponInflationZeroCouponInterpolationDefinition .from(SETTLE_DATE, SETTLE_DATE.plusYears(1), NOTIONAL, INDEX_PRICE, 2, 2, false); public static final CouponInflationZeroCouponMonthlyGearingDefinition INFLATION_ZERO_GEARING_COUPON = CouponInflationZeroCouponMonthlyGearingDefinition .from(SETTLE_DATE, SETTLE_DATE.plusYears(1), NOTIONAL, INDEX_PRICE, 100.0, 2, 2, false, 0.4); public static final CouponInflationZeroCouponInterpolationGearingDefinition INFLATION_INTERPOLATED_GEARING_COUPON = CouponInflationZeroCouponInterpolationGearingDefinition .from(SETTLE_DATE, SETTLE_DATE.plusYears(1), NOTIONAL, INDEX_PRICE, 100.0, 2, 2, false, 1.4); public static final BondCapitalIndexedSecurityDefinition<CouponInflationZeroCouponMonthlyGearingDefinition> CAPITAL_INDEXED_BOND_SECURITY = BondCapitalIndexedSecurityDefinition .fromMonthly(INDEX_PRICE, SPOT_LAG, SETTLE_DATE, 100, SETTLE_DATE.plusYears(5), FIXED_PERIOD, NOTIONAL, FIXED_RATE, BD, 2, OLD_C, FIXED_DAY_COUNT, SimpleYieldConvention.AUSTRIA_ISMA_METHOD, IS_EOM, ""); public static final BondCapitalIndexedTransactionDefinition<CouponInflationZeroCouponMonthlyGearingDefinition> CAPITAL_INDEXED_BOND_TRANSACTION = new BondCapitalIndexedTransactionDefinition<>( CAPITAL_INDEXED_BOND_SECURITY, 1, SETTLE_DATE, 100); public static final PaymentFixedDefinition PAYMENT_FIXED = new PaymentFixedDefinition(CUR, SETTLE_DATE, NOTIONAL); public static final DepositCounterpartDefinition DEPOSIT_COUNTERPART = new DepositCounterpartDefinition(CUR, SETTLE_DATE, SETTLE_DATE.plusDays(3), NOTIONAL, FIXED_RATE, FIXED_RATE, "a"); public static final DepositIborDefinition DEPOSIT_IBOR = DepositIborDefinition.fromStart(SETTLE_DATE, NOTIONAL, FIXED_RATE, IBOR_INDEX_1, OLD_C); public static final DepositZeroDefinition DEPOSIT_ZERO = DepositZeroDefinition.from(CUR, SETTLE_DATE, SETTLE_DATE.plusDays(3), FIXED_DAY_COUNT, new ContinuousInterestRate(0.03), OLD_C, FIXED_DAY_COUNT); public static final AnnuityCouponCMSDefinition ANNUITY_COUPON_CMS = new AnnuityCouponCMSDefinition(new CouponCMSDefinition[] { COUPON_CMS }, OLD_C); public static final AnnuityCouponFixedDefinition ANNUITY_FIXED = AnnuityCouponFixedDefinition.from(CUR, SETTLE_DATE, TENOR, FIXED_PERIOD, OLD_C, FIXED_DAY_COUNT, BD, IS_EOM, NOTIONAL, FIXED_RATE, IS_PAYER); public static final AnnuityCouponFixedDefinition ANNUITY_FIXED_UNIT_NOTIONAL = AnnuityCouponFixedDefinition.from(CUR, SETTLE_DATE, TENOR, FIXED_PERIOD, OLD_C, FIXED_DAY_COUNT, BD, IS_EOM, 1, FIXED_RATE, !IS_PAYER); public static final AnnuityCouponIborDefinition ANNUITY_IBOR = AnnuityCouponIborDefinition.from(SETTLE_DATE, TENOR, NOTIONAL, IBOR_INDEX_1, !IS_PAYER, OLD_C); public static final AnnuityCouponIborDefinition ANNUITY_IBOR_UNIT_NOTIONAL = AnnuityCouponIborDefinition.from(SETTLE_DATE, TENOR, 1, IBOR_INDEX_1, IS_PAYER, OLD_C); public static final AnnuityCouponIborSpreadDefinition ANNUITY_IBOR_SPREAD_RECEIVE = AnnuityCouponIborSpreadDefinition.from(SETTLE_DATE, TENOR, NOTIONAL, IBOR_INDEX_2, SPREAD, !IS_PAYER, OLD_C); public static final AnnuityCouponIborSpreadDefinition ANNUITY_IBOR_SPREAD_PAY = AnnuityCouponIborSpreadDefinition.from(SETTLE_DATE, TENOR, NOTIONAL, IBOR_INDEX_1, 0.0, IS_PAYER, OLD_C); public static final AnnuityDefinition<PaymentFixedDefinition> GENERAL_ANNUITY = new AnnuityDefinition<>(new PaymentFixedDefinition[] { new PaymentFixedDefinition(CUR, DateUtils.getUTCDate(2011, 1, 1), 1000), new PaymentFixedDefinition(CUR, DateUtils.getUTCDate(2012, 1, 1), 1000) }, OLD_C); public static final BillSecurityDefinition BILL_SECURITY = new BillSecurityDefinition(CUR, SETTLE_DATE.plusYears(1), NOTIONAL, 0, C, SimpleYieldConvention.BANK_OF_CANADA, FIXED_DAY_COUNT, ""); public static final BillTransactionDefinition BILL_TRANSACTION = new BillTransactionDefinition(BILL_SECURITY, 100, SETTLE_DATE, -100); public static final BondFixedSecurityDefinition BOND_FIXED_SECURITY = BondFixedSecurityDefinition.from(CUR, SETTLE_DATE.plusYears(2), SETTLE_DATE, FIXED_PERIOD, FIXED_RATE, SPOT_LAG, OLD_C, FIXED_DAY_COUNT, BD, SimpleYieldConvention.DISCOUNT, IS_EOM, ""); public static final BondFixedTransactionDefinition BOND_FIXED_TRANSACTION = new BondFixedTransactionDefinition(BOND_FIXED_SECURITY, 100, SETTLE_DATE, -100); public static final BondIborSecurityDefinition BOND_IBOR_SECURITY = BondIborSecurityDefinition.from(SETTLE_DATE.plusYears(2), SETTLE_DATE, IBOR_INDEX_1, 2, FIXED_DAY_COUNT, BD, IS_EOM, "", OLD_C); public static final BondIborTransactionDefinition BOND_IBOR_TRANSACTION = new BondIborTransactionDefinition(BOND_IBOR_SECURITY, 100, SETTLE_DATE, -100); public static final BondFutureDefinition BNDFUT_SECURITY_DEFINITION = FutureInstrumentsDescriptionDataSet.createBondFutureSecurityDefinition(); public static final BondFutureOptionPremiumSecurityDefinition BFO_SECURITY = FutureInstrumentsDescriptionDataSet .createBondFutureOptionPremiumSecurityDefinition(); public static final BondFutureOptionPremiumTransactionDefinition BFO_TRANSACTION = new BondFutureOptionPremiumTransactionDefinition(BFO_SECURITY, -100, BFO_SECURITY.getExpirationDate().minusMonths(3), 100); public static final CashDefinition CASH = new CashDefinition(CUR, DateUtils.getUTCDate(2011, 1, 2), DateUtils.getUTCDate(2012, 1, 2), 1.0, 0.04, 1.0); public static final ForwardRateAgreementDefinition FRA = ForwardRateAgreementDefinition.from(SETTLE_DATE, SETTLE_DATE.plusMonths(3), NOTIONAL, IBOR_INDEX_1, FIXED_RATE, OLD_C); public static final FederalFundsFutureSecurityDefinition FF_SECURITY = FederalFundsFutureSecurityDefinition.from(SETTLE_DATE, INDEX_ON, NOTIONAL, 0.25, "a", OLD_C); public static final FederalFundsFutureTransactionDefinition FF_TRANSACTION = new FederalFundsFutureTransactionDefinition(FF_SECURITY, 100, SETTLE_DATE, 0.97); public static final AgricultureForwardDefinition AG_FWD = AgricultureForwardDefinition.withCashSettlement(SETTLE_DATE.plusYears(1), ExternalId.of("a", "b"), 100, NOTIONAL, "tonnes", 76, CUR, SETTLE_DATE); public static final AgricultureFutureDefinition AG_FUTURE = AgricultureFutureDefinition.withPhysicalSettlement(SETTLE_DATE, ExternalId.of("a", "b"), 100, SETTLE_DATE, SETTLE_DATE, NOTIONAL, "tonnes", 100, CUR, SETTLE_DATE.minusYears(1)); public static final AgricultureFutureOptionDefinition AG_FUTURE_OPTION = new AgricultureFutureOptionDefinition(SETTLE_DATE, AG_FUTURE, 100, ExerciseDecisionType.AMERICAN, true); public static final EnergyForwardDefinition ENERGY_FWD = EnergyForwardDefinition.withCashSettlement(SETTLE_DATE.plusYears(1), ExternalId.of("a", "b"), 100, NOTIONAL, "watts", 76, CUR, SETTLE_DATE); public static final EnergyFutureDefinition ENERGY_FUTURE = EnergyFutureDefinition.withPhysicalSettlement(SETTLE_DATE, ExternalId.of("a", "b"), 100, SETTLE_DATE, SETTLE_DATE, NOTIONAL, "tonnes", 100, CUR, SETTLE_DATE.minusYears(1)); public static final EnergyFutureOptionDefinition ENERGY_FUTURE_OPTION = new EnergyFutureOptionDefinition(SETTLE_DATE, ENERGY_FUTURE, 100, ExerciseDecisionType.AMERICAN, true); public static final MetalForwardDefinition METAL_FWD = MetalForwardDefinition.withCashSettlement(SETTLE_DATE.plusYears(1), ExternalId.of("a", "b"), 100, NOTIONAL, "troy oz", 1776, CUR, SETTLE_DATE); public static final MetalFutureDefinition METAL_FUTURE = MetalFutureDefinition.withPhysicalSettlement(SETTLE_DATE, ExternalId.of("a", "b"), 100, SETTLE_DATE, SETTLE_DATE, NOTIONAL, "tonnes", 100, CUR, SETTLE_DATE.minusYears(1)); public static final MetalFutureOptionDefinition METAL_FUTURE_OPTION = new MetalFutureOptionDefinition(SETTLE_DATE, METAL_FUTURE, 100, ExerciseDecisionType.AMERICAN, true); public static final IndexFutureDefinition INDEX_FUTURE = new IndexFutureDefinition(SETTLE_DATE, SETTLE_DATE, 100, CUR, 100, ExternalId.of("a", "b")); public static final EquityIndexDividendFutureDefinition EQUITY_INDEX_DIVIDEND_FUTURE = new EquityIndexDividendFutureDefinition(SETTLE_DATE, SETTLE_DATE, 1200, CUR, 100); public static final EquityIndexOptionDefinition EQUITY_INDEX_OPTION = new EquityIndexOptionDefinition(true, 100, CUR, ExerciseDecisionType.AMERICAN, SETTLE_DATE, SETTLE_DATE.toLocalDate(), 25, SettlementType.CASH); public static final EquityOptionDefinition EQUITY_OPTION = new EquityOptionDefinition(false, 34, CUR, ExerciseDecisionType.EUROPEAN, SETTLE_DATE, SETTLE_DATE.toLocalDate(), 25, SettlementType.PHYSICAL); public static final EquityIndexFutureOptionDefinition EQUITY_INDEX_FUTURE_OPTION = new EquityIndexFutureOptionDefinition(SETTLE_DATE, INDEX_FUTURE, 100, ExerciseDecisionType.EUROPEAN, true, 100, 0); public static final InterestRateFutureSecurityDefinition IR_FUT_SECURITY_DEFINITION = FutureInstrumentsDescriptionDataSet .createInterestRateFutureSecurityDefinition(); public static final InterestRateFutureOptionMarginSecurityDefinition IR_FUT_OPT_MARGIN_SEC_DEF = FutureInstrumentsDescriptionDataSet .createInterestRateFutureOptionMarginSecurityDefinition(); public static final InterestRateFutureOptionMarginTransactionDefinition IR_FUT_OPT_MARGIN_T_DEF = FutureInstrumentsDescriptionDataSet .createInterestRateFutureOptionMarginTransactionDefinition(); public static final InterestRateFutureOptionPremiumSecurityDefinition IR_FUT_OPT_PREMIUM_SEC_DEF = FutureInstrumentsDescriptionDataSet .createInterestRateFutureOptionPremiumSecurityDefinition(); public static final InterestRateFutureOptionPremiumTransactionDefinition IR_FUT_OPT_PREMIUM_T_DEF = FutureInstrumentsDescriptionDataSet .createInterestRateFutureOptionPremiumTransactionDefinition(); public static final SwapDefinition SWAP = new SwapDefinition(ANNUITY_FIXED, ANNUITY_COUPON_CMS); public static final SwapFixedIborSpreadDefinition SWAP_FIXED_IBOR_SPREAD = new SwapFixedIborSpreadDefinition(ANNUITY_FIXED, ANNUITY_IBOR_SPREAD_RECEIVE); public static final SwapFixedIborDefinition SWAP_FIXED_IBOR = new SwapFixedIborDefinition(ANNUITY_FIXED, ANNUITY_IBOR); public static final SwapIborIborDefinition SWAP_IBOR_IBOR = new SwapIborIborDefinition(ANNUITY_IBOR_SPREAD_PAY, ANNUITY_IBOR_SPREAD_RECEIVE); public static final SwapFuturesPriceDeliverableSecurityDefinition DELIVERABLE_SWAP_FUTURE = new SwapFuturesPriceDeliverableSecurityDefinition(SETTLE_DATE, new SwapFixedIborDefinition(ANNUITY_FIXED_UNIT_NOTIONAL, ANNUITY_IBOR_UNIT_NOTIONAL), NOTIONAL); public static final SwaptionCashFixedIborDefinition SWAPTION_CASH = SwaptionInstrumentsDescriptionDataSet.createSwaptionCashFixedIborDefinition(); public static final SwaptionPhysicalFixedIborDefinition SWAPTION_PHYS = SwaptionInstrumentsDescriptionDataSet.createSwaptionPhysicalFixedIborDefinition(); public static final SwaptionPhysicalFixedIborSpreadDefinition SWAPTION_PHYS_SPREAD = SwaptionPhysicalFixedIborSpreadDefinition.from(SETTLE_DATE, SWAP_FIXED_IBOR_SPREAD, true, IS_EOM); public static final SwaptionBermudaFixedIborDefinition SWAPTION_BERMUDA = SwaptionBermudaFixedIborDefinition.from(SWAP_FIXED_IBOR, false, new ZonedDateTime[] { SETTLE_DATE.minusMonths(6), SETTLE_DATE.minusMonths(5), SETTLE_DATE.minusMonths(4), SETTLE_DATE.minusMonths(3) }); public static final CapFloorIborDefinition CAP_FLOOR_IBOR = CapFloorIborDefinition.from(COUPON_IBOR, FIXED_RATE, true); public static final CapFloorCMSDefinition CAP_FLOOR_CMS = CapFloorCMSDefinition.from(COUPON_CMS, FIXED_RATE, true); public static final CapFloorCMSSpreadDefinition CAP_FLOOR_CMS_SPREAD = CapFloorCMSSpreadDefinition.from(SETTLE_DATE.plusMonths(3), SETTLE_DATE, SETTLE_DATE.plusMonths(3), 0.1, NOTIONAL, CMS_INDEX, CMS_INDEX, FIXED_RATE, false, OLD_C, OLD_C); public static final SwapXCcyIborIborDefinition XCCY_SWAP = SwapXCcyIborIborDefinition.from(SETTLE_DATE, TENOR, XCCY_GENERATOR, NOTIONAL, NOTIONAL, SPREAD, IS_PAYER, OLD_C, OLD_C); public static final ISDACDSDefinition ISDA_CDS = new ISDACDSDefinition(SETTLE_DATE, SETTLE_DATE.plusYears(2), ISDA_PREMIUM, NOTIONAL, SPREAD, FIXED_RATE, false, false, true, PeriodFrequency.SEMI_ANNUAL, CONVENTION, StubType.LONG_END); public static final ForexDefinition FX = ForexDefinition.fromAmounts(CUR, Currency.AUD, SETTLE_DATE, NOTIONAL, -NOTIONAL * 1.5); public static final ForexSwapDefinition FX_SWAP = new ForexSwapDefinition(FX, ForexDefinition.fromAmounts(CUR, Currency.AUD, SETTLE_DATE.plusMonths(3), -NOTIONAL, NOTIONAL * 1.5)); public static final ForexOptionVanillaDefinition FX_VANILLA_OPTION = new ForexOptionVanillaDefinition(FX, SETTLE_DATE.minusMonths(6), false, false); public static final ForexOptionSingleBarrierDefinition FX_BARRIER_OPTION = new ForexOptionSingleBarrierDefinition(FX_VANILLA_OPTION, new Barrier(KnockType.IN, BarrierType.DOWN, ObservationType.CONTINUOUS, 1.5)); public static final ForexNonDeliverableForwardDefinition FX_NDF = new ForexNonDeliverableForwardDefinition(CUR, Currency.AUD, NOTIONAL, -1.5 * NOTIONAL, SETTLE_DATE.minusMonths(2), SETTLE_DATE); public static final ForexNonDeliverableOptionDefinition FX_NDO = new ForexNonDeliverableOptionDefinition(FX_NDF, true, false); public static final ForexOptionDigitalDefinition FX_DIGITAL = new ForexOptionDigitalDefinition(FX, SETTLE_DATE, IS_PAYER, IS_EOM); public static final VarianceSwapDefinition VARIANCE_SWAP = VarianceSwapDefinition.fromVarianceParams(SETTLE_DATE, SETTLE_DATE.plusYears(1), SETTLE_DATE, PeriodFrequency.DAILY, CUR, OLD_C, 1, 0.03, 1000); public static final EquityVarianceSwapDefinition EQUITY_VARIANCE_SWAP = EquityVarianceSwapDefinition.fromVarianceParams(SETTLE_DATE, SETTLE_DATE.plusYears(1), SETTLE_DATE, PeriodFrequency.DAILY, CUR, OLD_C, 1, 0.03, 1000, true); private static final Set<InstrumentDefinition<?>> ALL_INSTRUMENTS = Sets.newHashSet(); private static final Set<InstrumentDerivative> ALL_DERIVATIVES = Sets.newHashSet(); static { ALL_INSTRUMENTS.add(AG_FUTURE); ALL_INSTRUMENTS.add(AG_FUTURE_OPTION); ALL_INSTRUMENTS.add(AG_FWD); ALL_INSTRUMENTS.add(ANNUITY_FIXED); ALL_INSTRUMENTS.add(ANNUITY_IBOR); ALL_INSTRUMENTS.add(ANNUITY_COUPON_CMS); ALL_INSTRUMENTS.add(ANNUITY_IBOR_SPREAD_RECEIVE); ALL_INSTRUMENTS.add(ANNUITY_IBOR_SPREAD_PAY); ALL_INSTRUMENTS.add(BFO_SECURITY); ALL_INSTRUMENTS.add(BFO_TRANSACTION); ALL_INSTRUMENTS.add(BILL_SECURITY); ALL_INSTRUMENTS.add(BILL_TRANSACTION); ALL_INSTRUMENTS.add(BNDFUT_SECURITY_DEFINITION); ALL_INSTRUMENTS.add(BOND_FIXED_SECURITY); ALL_INSTRUMENTS.add(BOND_FIXED_TRANSACTION); ALL_INSTRUMENTS.add(BOND_IBOR_SECURITY); ALL_INSTRUMENTS.add(BOND_IBOR_TRANSACTION); ALL_INSTRUMENTS.add(CAP_FLOOR_CMS); ALL_INSTRUMENTS.add(CAP_FLOOR_CMS_SPREAD); ALL_INSTRUMENTS.add(CAP_FLOOR_IBOR); ALL_INSTRUMENTS.add(CAPITAL_INDEXED_BOND_SECURITY); ALL_INSTRUMENTS.add(CAPITAL_INDEXED_BOND_TRANSACTION); ALL_INSTRUMENTS.add(CASH); ALL_INSTRUMENTS.add(COUPON_CMS); ALL_INSTRUMENTS.add(COUPON_FIXED); ALL_INSTRUMENTS.add(COUPON_IBOR); ALL_INSTRUMENTS.add(COUPON_IBOR_COMPOUNDED); ALL_INSTRUMENTS.add(COUPON_IBOR_GEARING); ALL_INSTRUMENTS.add(COUPON_IBOR_RATCHET); ALL_INSTRUMENTS.add(COUPON_IBOR_SPREAD); ALL_INSTRUMENTS.add(COUPON_OIS); ALL_INSTRUMENTS.add(COUPON_OIS_SIMPLIFIED); ALL_INSTRUMENTS.add(DELIVERABLE_SWAP_FUTURE); ALL_INSTRUMENTS.add(DEPOSIT_COUNTERPART); ALL_INSTRUMENTS.add(DEPOSIT_IBOR); ALL_INSTRUMENTS.add(DEPOSIT_ZERO); ALL_INSTRUMENTS.add(ENERGY_FUTURE); ALL_INSTRUMENTS.add(ENERGY_FUTURE_OPTION); ALL_INSTRUMENTS.add(ENERGY_FWD); ALL_INSTRUMENTS.add(INDEX_FUTURE); ALL_INSTRUMENTS.add(EQUITY_INDEX_DIVIDEND_FUTURE); ALL_INSTRUMENTS.add(EQUITY_INDEX_FUTURE_OPTION); ALL_INSTRUMENTS.add(EQUITY_INDEX_OPTION); ALL_INSTRUMENTS.add(EQUITY_OPTION); ALL_INSTRUMENTS.add(EQUITY_VARIANCE_SWAP); ALL_INSTRUMENTS.add(FF_SECURITY); ALL_INSTRUMENTS.add(FF_TRANSACTION); ALL_INSTRUMENTS.add(FRA); ALL_INSTRUMENTS.add(FX); ALL_INSTRUMENTS.add(FX_BARRIER_OPTION); ALL_INSTRUMENTS.add(FX_DIGITAL); ALL_INSTRUMENTS.add(FX_NDF); ALL_INSTRUMENTS.add(FX_NDO); ALL_INSTRUMENTS.add(FX_SWAP); ALL_INSTRUMENTS.add(FX_VANILLA_OPTION); ALL_INSTRUMENTS.add(GENERAL_ANNUITY); ALL_INSTRUMENTS.add(INFLATION_INTERPOLATED_COUPON); ALL_INSTRUMENTS.add(INFLATION_INTERPOLATED_GEARING_COUPON); ALL_INSTRUMENTS.add(INFLATION_ZERO_COUPON); ALL_INSTRUMENTS.add(INFLATION_ZERO_GEARING_COUPON); ALL_INSTRUMENTS.add(IR_FUT_OPT_MARGIN_SEC_DEF); ALL_INSTRUMENTS.add(IR_FUT_OPT_MARGIN_T_DEF); ALL_INSTRUMENTS.add(IR_FUT_OPT_PREMIUM_SEC_DEF); ALL_INSTRUMENTS.add(IR_FUT_OPT_PREMIUM_T_DEF); ALL_INSTRUMENTS.add(IR_FUT_SECURITY_DEFINITION); ALL_INSTRUMENTS.add(ISDA_CDS); ALL_INSTRUMENTS.add(METAL_FUTURE); ALL_INSTRUMENTS.add(METAL_FUTURE_OPTION); ALL_INSTRUMENTS.add(METAL_FWD); ALL_INSTRUMENTS.add(PAYMENT_FIXED); ALL_INSTRUMENTS.add(SWAP); ALL_INSTRUMENTS.add(SWAP_IBOR_IBOR); ALL_INSTRUMENTS.add(SWAP_FIXED_IBOR); ALL_INSTRUMENTS.add(SWAP_FIXED_IBOR_SPREAD); ALL_INSTRUMENTS.add(SWAPTION_BERMUDA); ALL_INSTRUMENTS.add(SWAPTION_CASH); ALL_INSTRUMENTS.add(SWAPTION_PHYS); ALL_INSTRUMENTS.add(SWAPTION_PHYS_SPREAD); ALL_INSTRUMENTS.add(VARIANCE_SWAP); ALL_INSTRUMENTS.add(XCCY_SWAP); final ZonedDateTime endDate = DateUtils.getUTCDate(2013, 11, 1); ZonedDateTime date = DateUtils.getUTCDate(2000, 1, 1); final List<ZonedDateTime> dates = new ArrayList<>(); final List<Double> data = new ArrayList<>(); while (!date.isAfter(endDate)) { dates.add(date); data.add(0.01); date = date.plusDays(1); } final ZonedDateTimeDoubleTimeSeries ts = ImmutableZonedDateTimeDoubleTimeSeries.of(dates, data, ZoneOffset.UTC); ALL_DERIVATIVES.add(AG_FUTURE.toDerivative(AG_FUTURE.getSettlementDate())); ALL_DERIVATIVES.add(AG_FUTURE_OPTION.toDerivative(AG_FUTURE_OPTION.getExpiryDate().minusDays(1))); ALL_DERIVATIVES.add(AG_FWD.toDerivative(AG_FWD.getSettlementDate())); ALL_DERIVATIVES.add(ANNUITY_FIXED.toDerivative(ANNUITY_FIXED.getPayments()[0].getPaymentDate(), ts)); ALL_DERIVATIVES.add(ANNUITY_IBOR.toDerivative(ANNUITY_IBOR.getPayments()[0].getFixingDate(), ts)); ALL_DERIVATIVES.add(ANNUITY_COUPON_CMS.toDerivative(ANNUITY_COUPON_CMS.getPayments()[0].getFixingDate().minusDays(1), ts)); ALL_DERIVATIVES.add(ANNUITY_IBOR_SPREAD_RECEIVE.toDerivative(ANNUITY_IBOR.getPayments()[0].getFixingDate().minusDays(1), ts)); ALL_DERIVATIVES.add(ANNUITY_IBOR_SPREAD_PAY.toDerivative(ANNUITY_IBOR.getPayments()[0].getFixingDate().minusDays(1), ts)); ALL_DERIVATIVES.add(BFO_SECURITY.toDerivative(BFO_SECURITY.getUnderlyingFuture().getDeliveryLastDate().minusDays(1))); ALL_DERIVATIVES.add(BFO_TRANSACTION.toDerivative(BFO_TRANSACTION.getUnderlyingOption().getUnderlyingFuture().getDeliveryLastDate().minusDays(1))); ALL_DERIVATIVES.add(BILL_SECURITY.toDerivative(BILL_SECURITY.getEndDate().minusDays(2))); ALL_DERIVATIVES.add(BILL_TRANSACTION.toDerivative(BILL_TRANSACTION.getSettlementDate())); ALL_DERIVATIVES.add(BNDFUT_SECURITY_DEFINITION.toDerivative(BNDFUT_SECURITY_DEFINITION.getTradingLastDate(), 2.)); ALL_DERIVATIVES.add(BOND_FIXED_SECURITY.toDerivative(BOND_FIXED_SECURITY.getCoupons().getPayments()[0].getPaymentDate())); ALL_DERIVATIVES.add(BOND_FIXED_TRANSACTION.toDerivative(BOND_FIXED_TRANSACTION.getSettlementDate())); ALL_DERIVATIVES.add(BOND_IBOR_SECURITY.toDerivative(BOND_IBOR_SECURITY.getCoupons().getPayments()[0].getAccrualStartDate().minusDays(1), ts)); ALL_DERIVATIVES.add(BOND_IBOR_TRANSACTION.toDerivative(BOND_IBOR_TRANSACTION.getSettlementDate(), ts)); ALL_DERIVATIVES.add(CAP_FLOOR_CMS.toDerivative(CAP_FLOOR_CMS.getFixingDate(), ts)); ALL_DERIVATIVES.add(CAP_FLOOR_CMS_SPREAD.toDerivative(CAP_FLOOR_CMS_SPREAD.getFixingDate(), ts)); ALL_DERIVATIVES.add(CAP_FLOOR_IBOR.toDerivative(CAP_FLOOR_IBOR.getFixingDate(), ts)); ALL_DERIVATIVES.add(CAPITAL_INDEXED_BOND_SECURITY.toDerivative(CAPITAL_INDEXED_BOND_SECURITY.getCoupons().getPayments()[0].getPaymentDate(), ts)); ALL_DERIVATIVES.add(CAPITAL_INDEXED_BOND_TRANSACTION.toDerivative(CAPITAL_INDEXED_BOND_TRANSACTION.getSettlementDate(), ts)); ALL_DERIVATIVES.add(CASH.toDerivative(CASH.getStartDate())); ALL_DERIVATIVES.add(COUPON_CMS.toDerivative(COUPON_CMS.getAccrualStartDate(), ts)); ALL_DERIVATIVES.add(COUPON_FIXED.toDerivative(COUPON_FIXED.getPaymentDate())); ALL_DERIVATIVES.add(COUPON_IBOR.toDerivative(COUPON_IBOR.getPaymentDate(), ts)); ALL_DERIVATIVES.add(COUPON_IBOR_COMPOUNDED.toDerivative(COUPON_IBOR_COMPOUNDED.getPaymentDate(), ts)); ALL_DERIVATIVES.add(COUPON_IBOR_GEARING.toDerivative(COUPON_IBOR_GEARING.getFixingDate(), ts)); ALL_DERIVATIVES.add(COUPON_IBOR_RATCHET.toDerivative(COUPON_IBOR_RATCHET.getFixingDate())); ALL_DERIVATIVES.add(COUPON_IBOR_SPREAD.toDerivative(COUPON_IBOR_SPREAD.getFixingDate(), ts)); ALL_DERIVATIVES.add(COUPON_OIS.toDerivative(COUPON_OIS.getAccrualStartDate(), ts)); ALL_DERIVATIVES.add(COUPON_OIS_SIMPLIFIED.toDerivative(COUPON_OIS_SIMPLIFIED.getAccrualStartDate())); ALL_DERIVATIVES.add(DELIVERABLE_SWAP_FUTURE.toDerivative(DELIVERABLE_SWAP_FUTURE.getLastTradingDate().minusDays(10))); ALL_DERIVATIVES.add(DEPOSIT_COUNTERPART.toDerivative(DEPOSIT_COUNTERPART.getStartDate())); ALL_DERIVATIVES.add(DEPOSIT_IBOR.toDerivative(DEPOSIT_IBOR.getStartDate())); ALL_DERIVATIVES.add(DEPOSIT_ZERO.toDerivative(DEPOSIT_ZERO.getStartDate())); ALL_DERIVATIVES.add(ENERGY_FUTURE.toDerivative(ENERGY_FUTURE.getSettlementDate())); ALL_DERIVATIVES.add(ENERGY_FUTURE_OPTION.toDerivative(ENERGY_FUTURE_OPTION.getExpiryDate().minusDays(1))); ALL_DERIVATIVES.add(ENERGY_FWD.toDerivative(ENERGY_FWD.getSettlementDate())); ALL_DERIVATIVES.add(INDEX_FUTURE.toDerivative(SETTLE_DATE.minusDays(10))); ALL_DERIVATIVES.add(EQUITY_INDEX_DIVIDEND_FUTURE.toDerivative(SETTLE_DATE.minusDays(10))); ALL_DERIVATIVES.add(EQUITY_INDEX_OPTION.toDerivative(SETTLE_DATE.minusDays(100))); ALL_DERIVATIVES.add(EQUITY_INDEX_FUTURE_OPTION.toDerivative(SETTLE_DATE.minusDays(100))); ALL_DERIVATIVES.add(EQUITY_OPTION.toDerivative(SETTLE_DATE.minusDays(100))); ALL_DERIVATIVES.add(EQUITY_VARIANCE_SWAP.toDerivative(SETTLE_DATE.minusDays(100), ImmutableLocalDateDoubleTimeSeries.EMPTY_SERIES)); ALL_DERIVATIVES.add(FF_SECURITY.toDerivative(FF_SECURITY.getFixingPeriodDate()[0])); ALL_DERIVATIVES.add(FF_TRANSACTION.toDerivative(FF_TRANSACTION.getTradeDate(), new DoubleTimeSeries[] { ts, ts })); ALL_DERIVATIVES.add(FRA.toDerivative(FRA.getAccrualStartDate(), ts)); ALL_DERIVATIVES.add(FX.toDerivative(FX.getPaymentCurrency1().getPaymentDate())); ALL_DERIVATIVES.add(FX_BARRIER_OPTION.toDerivative(FX_BARRIER_OPTION.getUnderlyingOption().getExpirationDate().minusDays(1))); ALL_DERIVATIVES.add(FX_DIGITAL.toDerivative(FX_DIGITAL.getExpirationDate().minusDays(1))); ALL_DERIVATIVES.add(FX_NDF.toDerivative(FX_NDF.getFixingDate())); ALL_DERIVATIVES.add(FX_NDO.toDerivative(FX_NDO.getUnderlyingNDF().getFixingDate())); ALL_DERIVATIVES.add(FX_SWAP.toDerivative(FX_SWAP.getNearLeg().getExchangeDate().minusDays(1))); ALL_DERIVATIVES.add(FX_VANILLA_OPTION.toDerivative(FX_VANILLA_OPTION.getExpirationDate().minusDays(1))); ALL_DERIVATIVES.add(GENERAL_ANNUITY.toDerivative(GENERAL_ANNUITY.getPayments()[0].getPaymentDate(), ts)); ALL_DERIVATIVES.add(INFLATION_INTERPOLATED_COUPON.toDerivative(INFLATION_INTERPOLATED_COUPON.getAccrualStartDate(), ts)); ALL_DERIVATIVES.add(INFLATION_INTERPOLATED_GEARING_COUPON.toDerivative(INFLATION_INTERPOLATED_GEARING_COUPON.getAccrualStartDate(), ts)); ALL_DERIVATIVES.add(INFLATION_ZERO_COUPON.toDerivative(INFLATION_ZERO_COUPON.getAccrualStartDate().minusDays(3), ts)); ALL_DERIVATIVES.add(INFLATION_ZERO_GEARING_COUPON.toDerivative(INFLATION_ZERO_GEARING_COUPON.getAccrualStartDate().minusDays(3), ts)); ALL_DERIVATIVES.add(IR_FUT_OPT_MARGIN_SEC_DEF.toDerivative(IR_FUT_OPT_MARGIN_SEC_DEF.getExpirationDate().minusDays(1))); ALL_DERIVATIVES.add(IR_FUT_OPT_MARGIN_T_DEF.toDerivative(IR_FUT_OPT_MARGIN_T_DEF.getTradeDate(), 0.99)); ALL_DERIVATIVES.add(IR_FUT_OPT_PREMIUM_SEC_DEF.toDerivative(IR_FUT_OPT_PREMIUM_SEC_DEF.getExpirationDate().minusDays(1))); ALL_DERIVATIVES.add(IR_FUT_OPT_PREMIUM_T_DEF.toDerivative(IR_FUT_OPT_PREMIUM_T_DEF.getUnderlyingOption().getExpirationDate().minusDays(1))); ALL_DERIVATIVES.add(IR_FUT_SECURITY_DEFINITION.toDerivative(IR_FUT_SECURITY_DEFINITION.getLastTradingDate().minusDays(1))); ALL_DERIVATIVES.add(ISDA_CDS.toDerivative(ISDA_CDS.getMaturity().minusDays(10))); ALL_DERIVATIVES.add(METAL_FUTURE.toDerivative(METAL_FUTURE.getSettlementDate())); ALL_DERIVATIVES.add(METAL_FUTURE_OPTION.toDerivative(METAL_FUTURE_OPTION.getExpiryDate().minusDays(1))); ALL_DERIVATIVES.add(METAL_FWD.toDerivative(METAL_FWD.getSettlementDate())); ALL_DERIVATIVES.add(PAYMENT_FIXED.toDerivative(PAYMENT_FIXED.getPaymentDate().minusDays(1))); ALL_DERIVATIVES.add(SWAP.toDerivative(SWAP.getSecondLeg().getPayments()[0].getPaymentDate(), new ZonedDateTimeDoubleTimeSeries[] { ts, ts })); ALL_DERIVATIVES .add(SWAP_IBOR_IBOR.toDerivative(SWAP_IBOR_IBOR.getFirstLeg().getPayments()[0].getPaymentDate(), new ZonedDateTimeDoubleTimeSeries[] { ts, ts })); ALL_DERIVATIVES .add(SWAP_FIXED_IBOR.toDerivative(SWAP_FIXED_IBOR.getFirstLeg().getPayments()[0].getPaymentDate(), new ZonedDateTimeDoubleTimeSeries[] { ts, ts })); ALL_DERIVATIVES.add(SWAP_FIXED_IBOR_SPREAD.toDerivative(SWAP_FIXED_IBOR_SPREAD.getFirstLeg().getPayments()[0].getPaymentDate(), new ZonedDateTimeDoubleTimeSeries[] { ts, ts })); ALL_DERIVATIVES.add(SWAPTION_BERMUDA.toDerivative(SWAPTION_BERMUDA.getExpiryDate()[0].minusDays(1))); ALL_DERIVATIVES.add(SWAPTION_CASH.toDerivative(SWAPTION_CASH.getExpiry().getExpiry().minusDays(1))); ALL_DERIVATIVES.add(SWAPTION_PHYS.toDerivative(SWAPTION_PHYS.getExpiry().getExpiry().minusDays(1))); ALL_DERIVATIVES.add(SWAPTION_PHYS_SPREAD.toDerivative(SWAPTION_PHYS_SPREAD.getExpiry().getExpiry().minusDays(10))); ALL_DERIVATIVES.add(VARIANCE_SWAP.toDerivative(SETTLE_DATE.minusDays(100), ImmutableLocalDateDoubleTimeSeries.EMPTY_SERIES)); ALL_DERIVATIVES.add(XCCY_SWAP.toDerivative(XCCY_SWAP.getFirstLeg().getPayments()[0].getPaymentDate(), new ZonedDateTimeDoubleTimeSeries[] { ts, ts })); } public static Set<InstrumentDefinition<?>> getAllInstruments() { return ALL_INSTRUMENTS; } public static Set<InstrumentDerivative> getAllDerivatives() { return ALL_DERIVATIVES; } }
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions; public class AddOutreachProviderRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator { private static String template = "addOutreachProviderRoleToPerson.ftl"; private static String OPTION_CLASS_URI = "http://xmlns.com/foaf/0.1/Organization"; @Override String getTemplate() { return template; } @Override String getRoleType() { return "http://vivoweb.org/ontology/core#OutreachProviderRole"; } //Outreach Provider role involves hard-coded options for the "right side" of the role or activity @Override FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception { return new ConstantFieldOptions( "","Select type", "http://vivoweb.org/ontology/core#Association","Association", "http://vivoweb.org/ontology/core#Center","Center", "http://vivoweb.org/ontology/core#ClinicalOrganization","Clinical Organization", "http://vivoweb.org/ontology/core#College","College", "http://vivoweb.org/ontology/core#Committee","Committee", "http://vivoweb.org/ontology/core#Consortium","Consortium", "http://vivoweb.org/ontology/core#CoreLaboratory","Core Laboratory", "http://vivoweb.org/ontology/core#Department","Department", "http://vivoweb.org/ontology/core#Division","Division", "http://vivoweb.org/ontology/core#ExtensionUnit","Extension Unit", "http://vivoweb.org/ontology/core#Foundation","Foundation", "http://vivoweb.org/ontology/core#FundingOrganization","Funding Organization", "http://vivoweb.org/ontology/core#GovernmentAgency","Government Agency", "http://vivoweb.org/ontology/core#Hospital","Hospital", "http://vivoweb.org/ontology/core#Institute","Institute", "http://vivoweb.org/ontology/core#Laboratory","Laboratory", "http://vivoweb.org/ontology/core#Library","Library", "http://vivoweb.org/ontology/core#Museum","Museum", "http://xmlns.com/foaf/0.1/Organization","Organization", "http://vivoweb.org/ontology/core#PrivateCompany","Private Company", "http://vivoweb.org/ontology/core#Program","Program", "http://vivoweb.org/ontology/core#Publisher","Publisher", "http://vivoweb.org/ontology/core#ResearchOrganization","Research Organization", "http://vivoweb.org/ontology/core#Team","Team", "http://vivoweb.org/ontology/core#School","School", "http://vivoweb.org/ontology/core#ServiceProvidingLaboratory","Service Providing Lab", "http://vivoweb.org/ontology/core#StudentOrganization","Student Organization", "http://purl.obolibrary.org/obo/ERO_0000565","Technology Transfer Office", "http://vivoweb.org/ontology/core#University","University"); } @Override boolean isShowRoleLabelField(){return true;} /* * Use the methods below to change the date/time precision in the * custom form associated with this generator. When not used, the * precision will be YEAR. The other precisons are MONTH, DAY, HOUR, * MINUTE, TIME and NONE. */ /* public String getStartDatePrecision() { String precision = VitroVocabulary.Precision.MONTH.uri(); return precision; } public String getEndDatePrecision() { String precision = VitroVocabulary.Precision.DAY.uri(); return precision; } */ }
package org.eclipse.smarthome.core.common.osgi; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.nio.charset.Charset; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.Properties; import org.osgi.framework.Bundle; /** * The {@link ResourceBundleClassLoader} is a user defined classloader which is * responsible to map files within an <i>OSGi</i> bundle to {@link URL}s. This * implementation only supports the method {@link #getResource(String)} for * mappings. * * @author Michael Grammling - Initial Contribution * @author Martin Herbst - UTF-8 replaced by ISO-8859-1 to follow Java standards */ public class ResourceBundleClassLoader extends ClassLoader { private static final Charset SUPPORTED_CHARSET = Charset.forName("ISO-8859-1"); private Bundle bundle; private String path; private String filePattern; public ResourceBundleClassLoader(Bundle bundle, String path, String filePattern) throws IllegalArgumentException { if (bundle == null) { throw new IllegalArgumentException("The bundle must not be null!"); } this.bundle = bundle; this.path = (path != null) ? path : "/"; this.filePattern = (filePattern != null) ? filePattern : "*"; } @Override public URL getResource(String name) { Enumeration<URL> resourceFiles = this.bundle.findEntries(this.path, this.filePattern, true); List<URL> allResources = new LinkedList<URL>(); if (resourceFiles != null) { while (resourceFiles.hasMoreElements()) { URL resourceURL = resourceFiles.nextElement(); String resourcePath = resourceURL.getFile(); File resourceFile = new File(resourcePath); String resourceFileName = resourceFile.getName(); if (resourceFileName.equals(name)) { allResources.add(resourceURL); } } } if (allResources.isEmpty()) { return null; } if (allResources.size() == 1) { return allResources.get(0); } // handle fragment resources. return first one. for (URL url : allResources) { boolean isHostResource = bundle.getEntry(url.getPath()) != null && bundle.getEntry(url.getPath()).equals(url); if (isHostResource) { continue; } return url; } return null; } @Override public InputStream getResourceAsStream(String name) { URL resourceURL = getResource(name); if (resourceURL != null) { try (InputStream resourceStream = resourceURL.openStream()) { if (resourceStream != null) { try (Reader resourceReader = new InputStreamReader(resourceStream, SUPPORTED_CHARSET)) { Properties props = new Properties(); props.load(resourceReader); ByteArrayOutputStream baos = new ByteArrayOutputStream(); props.store(baos, "converted"); return new ByteArrayInputStream(baos.toByteArray()); } } } catch (IOException e) { } return super.getResourceAsStream(name); } return null; } }
package io.cattle.platform.servicediscovery.dao.impl; import static io.cattle.platform.core.model.tables.InstanceLinkTable.INSTANCE_LINK; import static io.cattle.platform.core.model.tables.InstanceTable.INSTANCE; import static io.cattle.platform.core.model.tables.ServiceConsumeMapTable.SERVICE_CONSUME_MAP; import static io.cattle.platform.core.model.tables.ServiceExposeMapTable.SERVICE_EXPOSE_MAP; import static io.cattle.platform.core.model.tables.ServiceTable.SERVICE; import io.cattle.platform.core.constants.CommonStatesConstants; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.InstanceLink; import io.cattle.platform.core.model.ServiceConsumeMap; import io.cattle.platform.core.model.tables.records.InstanceLinkRecord; import io.cattle.platform.core.model.tables.records.InstanceRecord; import io.cattle.platform.core.model.tables.records.ServiceConsumeMapRecord; import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao; import io.cattle.platform.object.ObjectManager; import io.cattle.platform.servicediscovery.api.dao.ServiceConsumeMapDao; import java.util.List; import javax.inject.Inject; public class ServiceConsumeMapDaoImpl extends AbstractJooqDao implements ServiceConsumeMapDao { @Inject ObjectManager objectManager; @Override public ServiceConsumeMap findMapToRemove(long serviceId, long consumedServiceId) { List<ServiceConsumeMap> maps = objectManager.find(ServiceConsumeMap.class, SERVICE_CONSUME_MAP.SERVICE_ID, serviceId, SERVICE_CONSUME_MAP.CONSUMED_SERVICE_ID, consumedServiceId); for (ServiceConsumeMap map : maps) { if (map != null && (map.getRemoved() == null || map.getState().equals(CommonStatesConstants.REMOVING))) { return map; } } return null; } @Override public ServiceConsumeMap findNonRemovedMap(long serviceId, long consumedServiceId, String linkName) { ServiceConsumeMap map = null; if (linkName == null) { map = objectManager.findOne(ServiceConsumeMap.class, SERVICE_CONSUME_MAP.SERVICE_ID, serviceId, SERVICE_CONSUME_MAP.CONSUMED_SERVICE_ID, consumedServiceId, SERVICE_CONSUME_MAP.REMOVED, null); } else { map = objectManager.findOne(ServiceConsumeMap.class, SERVICE_CONSUME_MAP.SERVICE_ID, serviceId, SERVICE_CONSUME_MAP.CONSUMED_SERVICE_ID, consumedServiceId, SERVICE_CONSUME_MAP.NAME, linkName, SERVICE_CONSUME_MAP.REMOVED, null); } if (map != null && !map.getState().equalsIgnoreCase(CommonStatesConstants.REMOVING)) { return map; } return null; } @Override public List<? extends ServiceConsumeMap> findConsumedServices(long serviceId) { return create() .selectFrom(SERVICE_CONSUME_MAP) .where( SERVICE_CONSUME_MAP.SERVICE_ID.eq(serviceId) .and(SERVICE_CONSUME_MAP.REMOVED.isNull())).fetchInto(ServiceConsumeMapRecord.class); } @Override public List<? extends ServiceConsumeMap> findConsumedServicesForInstance(long instanceId, String kind) { return create() .select(SERVICE_CONSUME_MAP.fields()) .from(SERVICE_CONSUME_MAP) .join(SERVICE_EXPOSE_MAP) .on(SERVICE_EXPOSE_MAP.SERVICE_ID.eq(SERVICE_CONSUME_MAP.SERVICE_ID)) .join(SERVICE) .on(SERVICE.ID.eq(SERVICE_CONSUME_MAP.CONSUMED_SERVICE_ID)) .where( SERVICE_EXPOSE_MAP.INSTANCE_ID.eq(instanceId) .and(SERVICE.KIND.eq(kind)) .and(SERVICE_CONSUME_MAP.REMOVED.isNull()) //Don't include yourself .and(SERVICE_CONSUME_MAP.SERVICE_ID.ne(SERVICE_CONSUME_MAP.CONSUMED_SERVICE_ID)) .and(SERVICE_EXPOSE_MAP.REMOVED.isNull())) .fetchInto(ServiceConsumeMapRecord.class); } @Override public List<? extends InstanceLink> findServiceBasedInstanceLinks(long instanceId) { return create() .select(INSTANCE_LINK.fields()) .from(INSTANCE_LINK) .where(INSTANCE_LINK.INSTANCE_ID.eq(instanceId) .and(INSTANCE_LINK.SERVICE_CONSUME_MAP_ID.isNotNull()) .and(INSTANCE_LINK.REMOVED.isNull())) .fetchInto(InstanceLinkRecord.class); } @Override public Instance findOneInstanceForService(long serviceId) { Instance last = null; List<? extends Instance> instances = create() .select(INSTANCE.fields()) .from(INSTANCE) .join(SERVICE_EXPOSE_MAP) .on(SERVICE_EXPOSE_MAP.INSTANCE_ID.eq(INSTANCE.ID)) .where(INSTANCE.REMOVED.isNull() .and(SERVICE_EXPOSE_MAP.SERVICE_ID.eq(serviceId)) .and(SERVICE_EXPOSE_MAP.REMOVED.isNull())) .orderBy(INSTANCE.CREATED.desc()) .fetchInto(InstanceRecord.class); for (Instance instance : instances) { last = instance; if (last.getFirstRunning() != null) { return last; } } return last; } @Override public List<String> findInstanceNamesForService(long serviceId) { return create() .select(INSTANCE.NAME) .from(INSTANCE) .join(SERVICE_EXPOSE_MAP) .on(SERVICE_EXPOSE_MAP.INSTANCE_ID.eq(INSTANCE.ID)) .where(INSTANCE.REMOVED.isNull() .and(SERVICE_EXPOSE_MAP.REMOVED.isNull()) .and(SERVICE_EXPOSE_MAP.SERVICE_ID.eq(serviceId))) .orderBy(INSTANCE.NAME.asc()) .fetch(INSTANCE.NAME); } @Override public List<? extends ServiceConsumeMap> findConsumedMapsToRemove(long serviceId) { return create() .selectFrom(SERVICE_CONSUME_MAP) .where( SERVICE_CONSUME_MAP.SERVICE_ID.eq(serviceId) .and((SERVICE_CONSUME_MAP.REMOVED.isNull(). or(SERVICE_CONSUME_MAP.STATE.eq(CommonStatesConstants.REMOVING))))). fetchInto(ServiceConsumeMapRecord.class); } @Override public List<? extends ServiceConsumeMap> findConsumingServices(long serviceId) { return create() .selectFrom(SERVICE_CONSUME_MAP) .where( SERVICE_CONSUME_MAP.CONSUMED_SERVICE_ID.eq(serviceId) .and(SERVICE_CONSUME_MAP.REMOVED.isNull())).fetchInto(ServiceConsumeMapRecord.class); } @Override public List<? extends ServiceConsumeMap> findConsumingMapsToRemove(long serviceId) { return create() .selectFrom(SERVICE_CONSUME_MAP) .where( SERVICE_CONSUME_MAP.CONSUMED_SERVICE_ID.eq(serviceId) .and((SERVICE_CONSUME_MAP.REMOVED.isNull(). or(SERVICE_CONSUME_MAP.STATE.eq(CommonStatesConstants.REMOVING))))). fetchInto(ServiceConsumeMapRecord.class); } }
package org.apereo.cas.validation; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.Setter; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * This is {@link ChainingCasProtocolValidationSpecification}. * * @author Misagh Moayyed * @since 6.1.0 */ @Getter @Setter @NoArgsConstructor(force = true) @RequiredArgsConstructor public class ChainingCasProtocolValidationSpecification implements CasProtocolValidationSpecification { private final List<CasProtocolValidationSpecification> specifications = new ArrayList<>(0); private final boolean canBeSatisfiedByAnySpecification; private boolean renew; @Override public boolean isSatisfiedBy(final Assertion assertion, final HttpServletRequest request) { if (this.canBeSatisfiedByAnySpecification) { return this.specifications .stream() .peek(s -> s.setRenew(this.renew)) .anyMatch(s -> s.isSatisfiedBy(assertion, request)); } return this.specifications.stream() .peek(s -> s.setRenew(this.renew)) .allMatch(s -> s.isSatisfiedBy(assertion, request)); } /** * Add policy. * * @param policy the policy */ public void addSpecification(final CasProtocolValidationSpecification policy) { this.specifications.add(policy); } /** * Add policies. * * @param policies the policies */ public void addSpecifications(final CasProtocolValidationSpecification... policies) { this.specifications.addAll(Arrays.stream(policies).collect(Collectors.toList())); } /** * Size. * * @return the int */ public int size() { return specifications.size(); } @Override public void reset() { this.specifications.forEach(CasProtocolValidationSpecification::reset); setRenew(false); } }
package org.hisp.dhis.schema.descriptors; import com.google.common.collect.Lists; import org.hisp.dhis.category.CategoryOption; import org.hisp.dhis.schema.Schema; import org.hisp.dhis.schema.SchemaDescriptor; import org.hisp.dhis.security.Authority; import org.hisp.dhis.security.AuthorityType; /** * @author Morten Olav Hansen <mortenoh@gmail.com> */ public class CategoryOptionSchemaDescriptor implements SchemaDescriptor { public static final String SINGULAR = "categoryOption"; public static final String PLURAL = "categoryOptions"; public static final String API_ENDPOINT = "/" + PLURAL; @Override public Schema getSchema() { Schema schema = new Schema( CategoryOption.class, SINGULAR, PLURAL ); schema.setRelativeApiEndpoint( API_ENDPOINT ); schema.setOrder( 1140 ); schema.setDataShareable( true ); schema.getAuthorities().add( new Authority( AuthorityType.CREATE_PUBLIC, Lists.newArrayList( "F_CATEGORY_OPTION_PUBLIC_ADD" ) ) ); schema.getAuthorities().add( new Authority( AuthorityType.CREATE_PRIVATE, Lists.newArrayList( "F_CATEGORY_OPTION_PRIVATE_ADD" ) ) ); schema.getAuthorities().add( new Authority( AuthorityType.DELETE, Lists.newArrayList( "F_CATEGORY_OPTION_DELETE" ) ) ); return schema; } }
package org.estatio.capex.dom.documents.categorisation.document; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; import javax.inject.Inject; import javax.validation.constraints.Digits; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlTransient; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.wicketstuff.pdfjs.Scale; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.Editing; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.MinLength; import org.apache.isis.applib.annotation.Optionality; import org.apache.isis.applib.annotation.Parameter; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.annotation.PromptStyle; import org.apache.isis.applib.annotation.PropertyLayout; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.Where; import org.apache.isis.applib.services.bookmark.BookmarkService2; import org.apache.isis.applib.services.clock.ClockService; import org.apache.isis.applib.services.hint.HintStore; import org.apache.isis.applib.value.Blob; import org.isisaddons.wicket.pdfjs.cpt.applib.PdfJsViewer; import org.incode.module.base.dom.types.ReferenceType; import org.incode.module.base.dom.valuetypes.LocalDateInterval; import org.incode.module.country.dom.impl.Country; import org.incode.module.document.dom.impl.docs.Document; import org.incode.module.document.dom.impl.paperclips.PaperclipRepository; import org.incode.module.document.dom.impl.types.DocumentType; import org.estatio.capex.dom.project.Project; import org.estatio.capex.dom.project.ProjectRepository; import org.estatio.capex.dom.task.Task; import org.estatio.capex.dom.util.PeriodUtil; import org.estatio.dom.asset.OwnershipType; import org.estatio.dom.asset.Property; import org.estatio.dom.asset.PropertyRepository; import org.estatio.dom.asset.ownership.FixedAssetOwnership; import org.estatio.dom.asset.role.FixedAssetRole; import org.estatio.dom.asset.role.FixedAssetRoleRepository; import org.estatio.dom.asset.role.FixedAssetRoleTypeEnum; import org.estatio.dom.budgeting.budget.Budget; import org.estatio.dom.budgeting.budget.BudgetRepository; import org.estatio.dom.budgeting.budgetitem.BudgetItem; import org.estatio.dom.budgeting.budgetitem.BudgetItemRepository; import org.estatio.dom.charge.Applicability; import org.estatio.dom.charge.Charge; import org.estatio.dom.charge.ChargeRepository; import org.estatio.dom.financial.bankaccount.BankAccountRepository; import org.estatio.dom.financial.utils.IBANValidator; import org.estatio.dom.party.Organisation; import org.estatio.dom.party.OrganisationRepository; import org.estatio.dom.party.Party; import org.estatio.dom.tax.Tax; import lombok.Getter; import lombok.Setter; @XmlTransient // abstract class so do not map @XmlAccessorType(XmlAccessType.FIELD) public abstract class IncomingDocViewModel<T> implements HintStore.HintIdProvider { public IncomingDocViewModel() {} public IncomingDocViewModel(final Document document) { this.document = document; } public String title() { return getDocument().getName(); } @Getter @Setter protected Document document; public DocumentType getType() { return getDocument().getType(); } public DateTime getCreatedAt() { return getDocument().getCreatedAt(); } @org.apache.isis.applib.annotation.Property(hidden = Where.ALL_TABLES) @PdfJsViewer(initialPageNum = 1, initialScale = Scale.PAGE_WIDTH, initialHeight = 1500) public Blob getBlob() { return getDocument() != null ? getDocument().getBlob() : null; } /** * For view models with inline property edits, allows the focus to stay on the same field after OK. */ @Override public String hintId() { return bookmarkService2.bookmarkFor(getDocument()).toString(); } @Programmatic public abstract void setDomainObject(T t); /** * Optional, the (categorisation) task (ie, just completed) that was used to create the view model. * * <p> * Used in order to advance to next task after this has been classified. * </p> */ @Setter @Getter @org.apache.isis.applib.annotation.Property(hidden = Where.EVERYWHERE) private Task originatingTask; @Programmatic protected abstract String minimalRequiredDataToComplete(); @Programmatic public void modifyProperty(final Property property) { setProperty(property); deriveBuyer(); } private void deriveBuyer(){ Party ownerCandidate = null; if (hasProperty()){ for (FixedAssetOwnership fos: getProperty().getOwners()){ if (fos.getOwnershipType()== OwnershipType.FULL){ ownerCandidate = fos.getOwner(); continue; } } // temporary extra search until fixed asset ownership is fully in use if (ownerCandidate == null && getProperty().ownerCandidates().size() > 0) { ownerCandidate = getProperty().ownerCandidates().get(0).getParty(); } } setBuyer(ownerCandidate); } @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.ENABLED) private Party buyer; @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.ENABLED) private Party seller; // use of modify so can be overridden on IncomingInvoiceViewmodel public void modifySeller(final Party seller){ setSeller(seller); } @Action( semantics = SemanticsOf.IDEMPOTENT ) public IncomingDocViewModel createSeller( final @Parameter(regexPattern = ReferenceType.Meta.REGEX, regexPatternReplacement = ReferenceType.Meta.REGEX_DESCRIPTION, optionality = Optionality.OPTIONAL) String reference, final boolean useNumeratorForReference, final String name, final Country country, @Parameter(optionality = Optionality.OPTIONAL) final String ibanNumber) { Organisation organisation = organisationRepository .newOrganisation(reference, useNumeratorForReference, name, country); setSeller(organisation); if (ibanNumber != null) { bankAccountRepository.newBankAccount(organisation, ibanNumber, null); } return this; } public String validateCreateSeller( final String reference, final boolean useNumeratorForReference, final String name, final Country country, final String ibanNumber){ if (ibanNumber != null && !IBANValidator.valid(ibanNumber)){ return String.format("%s is not a valid iban number", ibanNumber); } return null; } @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.ENABLED) private String description; @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.DISABLED) private Charge charge; @MemberOrder(name = "charge", sequence = "1") @ActionLayout(promptStyle = PromptStyle.INLINE_AS_IF_EDIT) public T editCharge(@Nullable final Charge charge) { setCharge(charge); return (T) this; } public List<Charge> autoComplete0EditCharge(@MinLength(3) String search){ return chargeRepository.findByApplicabilityAndMatchOnReferenceOrName(search, Applicability.INCOMING); } @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.ENABLED) private Property property; public List<Property> choicesProperty(){ List<Property> result = new ArrayList<>(); if (hasBuyer()) { for (FixedAssetRole role : fixedAssetRoleRepository.findByPartyAndType(getBuyer(), FixedAssetRoleTypeEnum.PROPERTY_OWNER)){ if (role.getAsset().getClass().isAssignableFrom(Property.class)) { result.add((Property) role.getAsset()); } } } return result.size()>0 ? result : propertyRepository.allProperties(); } @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.ENABLED) private Project project; public List<Project> choicesProject(){ return getProperty()==null ? projectRepository.listAll() : projectRepository.findByFixedAsset(getProperty()); } @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.ENABLED) private BudgetItem budgetItem; public void modifyBudgetItem(final BudgetItem budgetItem) { setBudgetItem(budgetItem); derivePeriodFromBudgetItem(); deriveChargeFromBudgetItem(); } public List<BudgetItem> choicesBudgetItem(){ return budgetItemChooser.choicesBudgetItemFor(getProperty(), getCharge()); } @Action(semantics = SemanticsOf.IDEMPOTENT) public IncomingDocViewModel createBudgetItem(final Budget budget, final Charge charge){ budgetItemRepository.findOrCreateBudgetItem(budget, charge); deriveChargeFromBudgetItem(); derivePeriodFromBudgetItem(); return this; } public List<Budget> choices0CreateBudgetItem(final Budget budget, final Charge charge){ if (hasProperty()){ return budgetRepository.findByProperty(getProperty()); } return budgetRepository.allBudgets(); } public List<Charge> choices1CreateBudgetItem(final Budget budget, final Charge charge){ if (hasCharge()){ return Arrays.asList(getCharge()); } return chargeRepository.allIncoming(); } @Action(semantics = SemanticsOf.IDEMPOTENT) public IncomingDocViewModel createNextBudget(final Budget previousBudget){ previousBudget.createNextBudget(); return this; } public List<Budget> choices0CreateNextBudget(final Budget budget){ if (hasProperty()){ return budgetRepository.findByProperty(getProperty()); } return budgetRepository.allBudgets(); } //region > period (prop) @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.ENABLED) private String period; public String validatePeriod(final String period) { if (period==null) return null; // period is optional return !PeriodUtil.isValidPeriod(period) ? "Not a valid period; use four digits of the year with optional prefix F for a financial year (for example: F2017)" : null; } protected LocalDate getStartDateFromPeriod() { return startDateFromPeriod(getPeriod()); } protected LocalDate getEndDateFromPeriod() { return endDateFromPeriod(getPeriod()); } private static LocalDate startDateFromPeriod(final String period) { LocalDateInterval localDateInterval = fromPeriod(period); return localDateInterval != null ? localDateInterval.startDate() : null; } private static LocalDate endDateFromPeriod(final String period) { LocalDateInterval localDateInterval = fromPeriod(period); return localDateInterval != null ? localDateInterval.endDate() : null; } private static LocalDateInterval fromPeriod(final String period) { return period != null ? PeriodUtil.yearFromPeriod(period) : null; } /** * For conveniences of subclasses, reciprocal to {@link #getStartDateFromPeriod()} and {@link #getEndDateFromPeriod()}. */ protected static String periodFrom(final LocalDate startDate, final LocalDate endDate) { LocalDateInterval ldi = LocalDateInterval .including(startDate, endDate); return PeriodUtil.periodFromInterval(ldi); } //endregion @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.ENABLED) private BigDecimal netAmount; @Digits(integer=13, fraction = 2) public BigDecimal getNetAmount() { return netAmount; } public void modifyNetAmount(BigDecimal netAmount) { setNetAmount(netAmount); calculateVat(); determineAmounts(); } @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.ENABLED) private BigDecimal vatAmount; @Digits(integer=13, fraction = 2) public BigDecimal getVatAmount() { return vatAmount; } public void modifyVatAmount(BigDecimal vatAmount) { setVatAmount(vatAmount); calculateVat(); determineAmounts(); } @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.ENABLED) private Tax tax; public void modifyTax(Tax tax) { setTax(tax); calculateVat(); determineAmounts(); } @Setter @Getter @org.apache.isis.applib.annotation.Property(editing = Editing.ENABLED) @PropertyLayout(promptStyle = PromptStyle.INLINE) private BigDecimal grossAmount; @Digits(integer=13, fraction = 2) public BigDecimal getGrossAmount() { return grossAmount; } public void modifyGrossAmount(BigDecimal grossAmount) { setGrossAmount(grossAmount); if (!hasNetAmount()){ final BigDecimal valueToUse = getVatAmount()!=null ? grossAmount.subtract(getVatAmount()):getGrossAmount(); setNetAmount(valueToUse); } calculateVat(); determineAmounts(); } public IncomingDocViewModel changeDimensions( @Parameter(optionality = Optionality.OPTIONAL) final Charge charge, @Parameter(optionality = Optionality.OPTIONAL) final Property property, @Parameter(optionality = Optionality.OPTIONAL) final Project project, @Parameter(optionality = Optionality.OPTIONAL) final BudgetItem budgetItem, @Parameter(optionality = Optionality.OPTIONAL) final String period ){ setCharge(charge); setProperty(property); setProject(project); setBudgetItem(budgetItem); setPeriod(period); derivePeriodFromBudgetItem(); deriveChargeFromBudgetItem(); return this; } public Charge default0ChangeDimensions(){ return getCharge(); } public Property default1ChangeDimensions(){ return getProperty(); } public Project default2ChangeDimensions(){ return getProject(); } public BudgetItem default3ChangeDimensions(){ return getBudgetItem(); } public String default4ChangeDimensions(){ return getPeriod(); } // public List<Charge> autoComplete0ChangeDimensions(@MinLength(3) final String search) { // return autoComplete0EditCharge(search); public List<Property> choices1ChangeDimensions() { return choicesProperty(); } public List<Project> choices2ChangeDimensions() { return choicesProject(); } public List<BudgetItem> choices3ChangeDimensions() { return choicesBudgetItem(); } public String validateChangeDimensions( final Charge charge, final Property property, final Project project, final BudgetItem budgetItem, final String period ) { return validatePeriod(period); } public String disableChangeDimensions() { return reasonNotEditableIfAny(); } public IncomingDocViewModel changeItemDetails( final String description, final BigDecimal netAmount, @Nullable final BigDecimal vatAmount, @Nullable final Tax tax, @Nullable final BigDecimal grossAmount ){ setDescription(description); setNetAmount(netAmount); setVatAmount(vatAmount); setTax(tax); setGrossAmount(grossAmount); calculateVat(); determineAmounts(); return this; } public String default0ChangeItemDetails(){ return getDescription(); } public BigDecimal default1ChangeItemDetails(){ return getNetAmount(); } public BigDecimal default2ChangeItemDetails(){ return getVatAmount(); } public Tax default3ChangeItemDetails(){ return getTax(); } public BigDecimal default4ChangeItemDetails(){ return getGrossAmount(); } public String disableChangeItemDetails() { return reasonNotEditableIfAny(); } void determineAmounts(){ if (hasVatAmount() && hasNetAmount() && !hasGrossAmount()){ setGrossAmount(getNetAmount().add(getVatAmount())); return; } if (hasVatAmount() && hasGrossAmount() && !hasNetAmount()){ setNetAmount(getGrossAmount().subtract(getVatAmount())); return; } if (hasNetAmount() && hasGrossAmount() && !hasVatAmount()){ setVatAmount(getGrossAmount().subtract(getNetAmount())); return; } } void calculateVat(){ if (hasTax() && hasNetAmount() && !hasVatAmount() && !hasGrossAmount()){ BigDecimal grossAmount = getTax().grossFromNet(getNetAmount(), clockService.now()); setVatAmount(grossAmount.subtract(getNetAmount())); return; } } void derivePeriodFromBudgetItem(){ if (hasBudgetItem() && !hasPeriod()){ setPeriod(String.valueOf(getBudgetItem().getBudget().getBudgetYear())); } } void deriveChargeFromBudgetItem(){ if (hasBudgetItem() && !hasCharge()){ setCharge(getBudgetItem().getCharge()); } } protected boolean hasTax(){ return getTax() != null; } protected boolean hasNetAmount(){ return getNetAmount() != null; } protected boolean hasVatAmount(){ return getVatAmount() != null; } protected boolean hasGrossAmount(){ return getGrossAmount() != null; } protected boolean hasCharge(){ return getCharge() != null; } protected boolean hasBuyer(){ return getBuyer() != null; } protected boolean hasSeller(){ return getSeller() != null; } protected boolean hasProperty(){ return getProperty() != null; } protected boolean hasProject(){ return getProject() != null; } protected boolean hasBudgetItem(){ return getBudgetItem() != null; } protected boolean hasPeriod(){ return getPeriod() != null; } protected boolean hasDescription(){ return getDescription() != null; } /** * Mandatory hook - to disable actions that change the state. * @return */ protected abstract String reasonNotEditableIfAny(); @XmlTransient @Inject protected BookmarkService2 bookmarkService2; @Inject @XmlTransient OrganisationRepository organisationRepository; @Inject @XmlTransient ChargeRepository chargeRepository; @Inject @XmlTransient ClockService clockService; @Inject @XmlTransient PropertyRepository propertyRepository; @Inject @XmlTransient FixedAssetRoleRepository fixedAssetRoleRepository; @Inject @XmlTransient ProjectRepository projectRepository; @Inject @XmlTransient BudgetRepository budgetRepository; @Inject @XmlTransient BudgetItemRepository budgetItemRepository; @Inject @XmlTransient protected BankAccountRepository bankAccountRepository; @Inject @XmlTransient protected PaperclipRepository paperclipRepository; @XmlTransient @Inject BudgetItemChooser budgetItemChooser; }
package org.opencps.usermgt.scheduler; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.json.JSONFactoryUtil; import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.messaging.BaseMessageListener; import com.liferay.portal.kernel.messaging.DestinationNames; import com.liferay.portal.kernel.messaging.Message; import com.liferay.portal.kernel.module.framework.ModuleServiceLifecycle; import com.liferay.portal.kernel.scheduler.SchedulerEngineHelper; import com.liferay.portal.kernel.scheduler.SchedulerEntryImpl; import com.liferay.portal.kernel.scheduler.SchedulerException; import com.liferay.portal.kernel.scheduler.StorageType; import com.liferay.portal.kernel.scheduler.StorageTypeAware; import com.liferay.portal.kernel.scheduler.TimeUnit; import com.liferay.portal.kernel.scheduler.Trigger; import com.liferay.portal.kernel.scheduler.TriggerFactory; import com.liferay.portal.kernel.service.ServiceContext; import java.util.Date; import java.util.Map; import org.opencps.kernel.scheduler.StorageTypeAwareSchedulerEntryImpl; import org.opencps.usermgt.action.ApplicantActions; import org.opencps.usermgt.action.impl.ApplicantActionsImpl; import org.opencps.usermgt.model.Applicant; import org.opencps.usermgt.model.SyncScheduler; import org.opencps.usermgt.scheduler.utils.AdministrativeRegionUtils; import org.opencps.usermgt.service.SyncSchedulerLocalServiceUtil; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Modified; import org.osgi.service.component.annotations.Reference; /** * @author trungnt */ //@Component(immediate = true, service = UserRegisterUpdateSheduler.class) public class UserRegisterUpdateSheduler extends BaseMessageListener { private volatile boolean isRunning = false; @Override protected void doReceive(Message message) { if (!isRunning) { isRunning = true; } else { return; } try { doProcessRegisterUser(); } catch (Exception e) { _log.debug(e); } isRunning = false; } private void doProcessRegisterUser() throws Exception { SyncScheduler syncScheduler = SyncSchedulerLocalServiceUtil.getByClassNameAndTypeCode(Applicant.class.getName(), "citizen"); if (syncScheduler != null) { Date syncDate;// = syncScheduler.getSyncDate(); //Co thong tin rooif ServiceContext serviceContext = new ServiceContext(); long groupId = 35166; for (int i = 0; i < 5; i++) { JSONObject jsonCongDan = JSONFactoryUtil.createJSONObject(); //String idCongDan = jsonCongDan.getString("id"); String applicantName = jsonCongDan.getString("tenDayDu"); String applicantIdType = "citizen"; String applicantIdNo = jsonCongDan.getString("soCMND"); String applicantIdDate = ""; String contactEmail = jsonCongDan.getString("tenDayDu"); String address = jsonCongDan.getString("diaChiThuongTru"); String contactName = jsonCongDan.getString("tenDayDu"); String contactTelNo = jsonCongDan.getString("dienThoaiDiDong"); String secret = ""; String cityId = jsonCongDan.getString("diaChiThuongTruTinhId"); String districtId = jsonCongDan.getString("diaChiThuongTruHuyenId"); String warId = jsonCongDan.getString("diaChiThuongTruXaId"); Map<String, String> mapCity = AdministrativeRegionUtils.getInfoRegion(cityId); String cityCode = mapCity.get("ma"); String cityName = mapCity.get("ten"); Map<String, String> mapDistrict = AdministrativeRegionUtils.getInfoRegion(districtId); String districtCode = mapDistrict.get("ma"); String districtName = mapDistrict.get("ten"); Map<String, String> mapWar = AdministrativeRegionUtils.getInfoRegion(warId); String wardCode = mapWar.get("ma"); String wardName = mapWar.get("ten"); ApplicantActions actions = new ApplicantActionsImpl(); actions.register(serviceContext, groupId, applicantName, applicantIdType, applicantIdNo, applicantIdDate, contactEmail, address, cityCode, cityName, districtCode, districtName, wardCode, wardName, contactName, contactTelNo, StringPool.BLANK, secret); } } } /** * activate: Called whenever the properties for the component change (ala Config Admin) * or OSGi is activating the component. * @param properties The properties map from Config Admin. * @throws SchedulerException in case of error. */ @Activate @Modified protected void activate(Map<String,Object> properties) throws SchedulerException { String listenerClass = getClass().getName(); Trigger jobTrigger = _triggerFactory.createTrigger(listenerClass, listenerClass, new Date(), null, 5, TimeUnit.MINUTE); _schedulerEntryImpl = new SchedulerEntryImpl(getClass().getName(), jobTrigger); _schedulerEntryImpl = new StorageTypeAwareSchedulerEntryImpl(_schedulerEntryImpl, StorageType.MEMORY_CLUSTERED); // _schedulerEntryImpl.setTrigger(jobTrigger); if (_initialized) { deactivate(); } _schedulerEngineHelper.register(this, _schedulerEntryImpl, DestinationNames.SCHEDULER_DISPATCH); _initialized = true; } @Deactivate protected void deactivate() { if (_initialized) { try { _schedulerEngineHelper.unschedule(_schedulerEntryImpl, getStorageType()); } catch (SchedulerException se) { if (_log.isWarnEnabled()) { _log.warn("Unable to unschedule trigger", se); } } _schedulerEngineHelper.unregister(this); } _initialized = false; } /** * getStorageType: Utility method to get the storage type from the scheduler entry wrapper. * @return StorageType The storage type to use. */ protected StorageType getStorageType() { if (_schedulerEntryImpl instanceof StorageTypeAware) { return ((StorageTypeAware) _schedulerEntryImpl).getStorageType(); } return StorageType.MEMORY_CLUSTERED; } /** * setModuleServiceLifecycle: So this requires some explanation... * * OSGi will start a component once all of it's dependencies are satisfied. However, there * are times where you want to hold off until the portal is completely ready to go. * * This reference declaration is waiting for the ModuleServiceLifecycle's PORTAL_INITIALIZED * component which will not be available until, surprise surprise, the portal has finished * initializing. * * With this reference, this component activation waits until portal initialization has completed. * @param moduleServiceLifecycle */ @Reference(target = ModuleServiceLifecycle.PORTAL_INITIALIZED, unbind = "-") protected void setModuleServiceLifecycle(ModuleServiceLifecycle moduleServiceLifecycle) { } @Reference(unbind = "-") protected void setTriggerFactory(TriggerFactory triggerFactory) { _triggerFactory = triggerFactory; } @Reference(unbind = "-") protected void setSchedulerEngineHelper(SchedulerEngineHelper schedulerEngineHelper) { _schedulerEngineHelper = schedulerEngineHelper; } private SchedulerEngineHelper _schedulerEngineHelper; private TriggerFactory _triggerFactory; private volatile boolean _initialized; private SchedulerEntryImpl _schedulerEntryImpl = null; private Log _log = LogFactoryUtil.getLog(UserRegisterUpdateSheduler.class); }
package org.nuxeo.ecm.favorites.core; import java.util.Locale; import java.util.MissingResourceException; import org.nuxeo.common.utils.i18n.I18NUtils; import org.nuxeo.ecm.collections.api.CollectionManager; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentRef; import org.nuxeo.ecm.core.api.PathRef; import org.nuxeo.ecm.core.api.security.ACE; import org.nuxeo.ecm.core.api.security.ACL; import org.nuxeo.ecm.core.api.security.ACP; import org.nuxeo.ecm.core.api.security.SecurityConstants; import org.nuxeo.ecm.core.api.security.impl.ACLImpl; import org.nuxeo.ecm.core.api.security.impl.ACPImpl; import org.nuxeo.ecm.favorites.api.FavoritesConstants; import org.nuxeo.ecm.favorites.api.FavoritesManager; import org.nuxeo.ecm.platform.userworkspace.api.UserWorkspaceService; import org.nuxeo.ecm.platform.web.common.locale.LocaleProvider; import org.nuxeo.runtime.api.Framework; import org.nuxeo.runtime.model.DefaultComponent; import org.nuxeo.runtime.transaction.TransactionHelper; /** * @since 5.9.4 */ public class FavoritesManagerImpl extends DefaultComponent implements FavoritesManager { @Override public void addToFavorites(DocumentModel document, CoreSession session) throws ClientException { final CollectionManager collectionManager = Framework.getLocalService(CollectionManager.class); collectionManager.addToCollection(getFavorites(document, session), document, session); } @Override public boolean canAddToFavorites(DocumentModel document) throws ClientException { final CollectionManager collectionManager = Framework.getLocalService(CollectionManager.class); return collectionManager.isCollectable(document); } protected DocumentModel createFavorites(CoreSession session, DocumentModel userWorkspace) throws ClientException { DocumentModel doc = session.createDocumentModel( userWorkspace.getPath().toString(), FavoritesConstants.DEFAULT_FAVORITES_NAME, FavoritesConstants.FAVORITES_TYPE); String title = null; try { title = I18NUtils.getMessageString("messages", FavoritesConstants.DEFAULT_FAVORITES_TITLE, new Object[0], getLocale(session)); } catch (MissingResourceException e) { title = FavoritesConstants.DEFAULT_FAVORITES_NAME; } doc.setProperty("dublincore", "title", FavoritesConstants.DEFAULT_FAVORITES_TITLE); doc.setProperty("dublincore", "title", title); doc.setProperty("dublincore", "description", ""); doc = session.createDocument(doc); ACP acp = new ACPImpl(); ACE denyEverything = new ACE(SecurityConstants.EVERYONE, SecurityConstants.EVERYTHING, false); ACE allowEverything = new ACE(session.getPrincipal().getName(), SecurityConstants.EVERYTHING, true); ACL acl = new ACLImpl(); acl.setACEs(new ACE[] { allowEverything, denyEverything }); acp.addACL(acl); doc.setACP(acp, true); return doc; } @Override public DocumentModel getFavorites(final DocumentModel context, final CoreSession session) throws ClientException { final UserWorkspaceService userWorkspaceService = Framework.getLocalService(UserWorkspaceService.class); final DocumentModel userWorkspace = userWorkspaceService.getCurrentUserPersonalWorkspace( session, context); final DocumentRef lookupRef = new PathRef( userWorkspace.getPath().toString(), FavoritesConstants.DEFAULT_FAVORITES_NAME); if (session.exists(lookupRef)) { return session.getChild(userWorkspace.getRef(), FavoritesConstants.DEFAULT_FAVORITES_NAME); } else { // does not exist yet, let's create it synchronized (this) { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); if (!session.exists(lookupRef)) { boolean succeed = false; try { createFavorites(session, userWorkspace); succeed = true; } finally { if (succeed) { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } } } return session.getDocument(lookupRef); } } } protected Locale getLocale(final CoreSession session) throws ClientException { Locale locale = null; locale = Framework.getLocalService(LocaleProvider.class).getLocale( session); if (locale == null) { locale = Locale.getDefault(); } return new Locale(Locale.getDefault().getLanguage()); } @Override public boolean isFavorite(DocumentModel document, CoreSession session) throws ClientException { final CollectionManager collectionManager = Framework.getLocalService(CollectionManager.class); return collectionManager.isInCollection( getFavorites(document, session), document, session); } @Override public void removeFromFavorites(DocumentModel document, CoreSession session) throws ClientException { final CollectionManager collectionManager = Framework.getLocalService(CollectionManager.class); collectionManager.removeFromCollection(getFavorites(document, session), document, session); } }
package org.eclipse.angularjs.internal.ui.contentassist; import java.util.Collection; import java.util.List; import org.eclipse.angularjs.core.AngularProject; import org.eclipse.angularjs.core.utils.DOMUtils; import org.eclipse.angularjs.internal.core.documentModel.parser.AngularRegionContext; import org.eclipse.angularjs.internal.ui.AngularScopeHelper; import org.eclipse.angularjs.internal.ui.ImageResource; import org.eclipse.angularjs.internal.ui.Trace; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.swt.graphics.Image; import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; import org.eclipse.wst.sse.ui.contentassist.CompletionProposalInvocationContext; import org.eclipse.wst.sse.ui.internal.contentassist.ContentAssistUtils; import org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal; import org.eclipse.wst.xml.core.internal.provisional.document.IDOMAttr; import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode; import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext; import org.eclipse.wst.xml.ui.internal.contentassist.ContentAssistRequest; import org.eclipse.wst.xml.ui.internal.contentassist.DefaultXMLCompletionProposalComputer; import org.eclipse.wst.xml.ui.internal.contentassist.MarkupCompletionProposal; import org.eclipse.wst.xml.ui.internal.contentassist.XMLRelevanceConstants; import org.w3c.dom.Element; import org.w3c.dom.Node; import tern.angular.AngularType; import tern.angular.modules.AngularModulesManager; import tern.angular.modules.Directive; import tern.angular.modules.DirectiveHelper; import tern.angular.modules.DirectiveParameter; import tern.angular.modules.DirectiveValue; import tern.angular.modules.IDirectiveCollector; import tern.angular.modules.IDirectiveParameterCollector; import tern.angular.modules.Restriction; import tern.angular.protocol.TernAngularQuery; import tern.angular.protocol.completions.TernAngularCompletionsQuery; import tern.eclipse.ide.core.IDETernProject; import tern.eclipse.ide.core.scriptpath.ITernScriptPath; import tern.server.ITernServer; import tern.server.protocol.completions.ITernCompletionCollector; /** * Completion in HTML editor for : * * <ul> * <li>attribute name with angular directive (ex : ng-app).</li> * <li>attribute value with angular module, controller, model.</li> * <li>attribute expression in text node {{}} and directive attribute value.</li> * </ul> * */ public class HTMLAngularTagsCompletionProposalComputer extends DefaultXMLCompletionProposalComputer { private static final String CLASS_ATTR = "class"; @Override protected void addAttributeNameProposals( final ContentAssistRequest contentAssistRequest, CompletionProposalInvocationContext context) { // Check if project has angular nature final IDOMNode element = (IDOMNode) contentAssistRequest.getNode(); if (DOMUtils.hasAngularNature(element)) { IProject p = DOMUtils.getFile(element).getProject(); Directive directive = DOMUtils.getAngularDirective(p, element); if (directive != null) { // completion for directive parameters. String paramName = contentAssistRequest.getMatchString(); AngularModulesManager.getInstance().collectDirectiveParameters( directive, paramName, new IDirectiveParameterCollector() { @Override public void add(DirectiveParameter parameter) { addDirectiveParameter(contentAssistRequest, parameter, element); } }); } else { // completion for directive with 'A' restriction : completion // for // attribute name with angular directive (ex : // ng-app) String tagName = element.getNodeName(); String directiveName = contentAssistRequest.getMatchString(); IDOMAttr attr = DOMUtils.getAttrByRegion(element, contentAssistRequest.getRegion()); // get angular attribute name of the element final List<Directive> existingDirectives = DOMUtils .getAngularDirectives(p, element instanceof Element ? (Element) element : null, attr); AngularProject project = null; try { project = AngularProject.getAngularProject(p); } catch (CoreException e) { } // Starts directives completion. project.collectDirectives(tagName, directiveName, existingDirectives, Restriction.A, new IDirectiveCollector() { @Override public void add(Directive directive, String name) { // Add the directive in the completion. String displayString = name + " - " + directive.getModule().getName(); String additionalProposalInfo = directive .getHTMLDescription(); Image image = ImageResource .getImage(ImageResource.IMG_DIRECTIVE); addProposal(contentAssistRequest, name, directive.getDirectiveValue(), directive, displayString, image, additionalProposalInfo, element); } @Override public void add(DirectiveParameter parameter) { addDirectiveParameter(contentAssistRequest, parameter, element); } }); } } super.addAttributeNameProposals(contentAssistRequest, context); } @Override protected void addAttributeValueProposals( final ContentAssistRequest contentAssistRequest, CompletionProposalInvocationContext context) { // Check if project has angular nature IDOMNode element = (IDOMNode) contentAssistRequest.getNode(); if (DOMUtils.hasAngularNature(element)) { // check if it's class attribute IDOMAttr attr = DOMUtils.getAttrByRegion(element, contentAssistRequest.getRegion()); // is angular directive attribute? Directive directive = DOMUtils.getAngularDirectiveByRegion(element, contentAssistRequest.getRegion()); AngularType angularType = directive != null ? directive.getType() : null; if (angularType != null) { if (angularType.equals(AngularType.unknown) || angularType.equals(AngularType.repeat_expression)) angularType = AngularType.model; int startIndex = (contentAssistRequest.getMatchString() .startsWith("\"") || contentAssistRequest .getMatchString().startsWith("'")) ? 1 : 0; populateAngularProposals(contentAssistRequest, element, angularType, startIndex); } else { // is angular expression inside attribute? String matchingString = contentAssistRequest.getMatchString(); int index = matchingString.lastIndexOf("{{"); if (index != -1) { populateAngularProposals(contentAssistRequest, element, AngularType.model, index); } else { if (CLASS_ATTR.equals(attr.getName())) { addClassAttributeValueProposals(contentAssistRequest, context, attr); } } } } super.addAttributeValueProposals(contentAssistRequest, context); } public void addClassAttributeValueProposals( final ContentAssistRequest contentAssistRequest, CompletionProposalInvocationContext context, IDOMAttr attr) { // completion on "class" attribute : completion on directive // with 'C' restrict. int documentPosition = context.getInvocationOffset(); int length = documentPosition - contentAssistRequest.getStartOffset(); String text = attr.getValue().substring(0, length - 1); final int index = text.lastIndexOf(";"); if (index != -1) { text = text.substring(index + 1, text.length()); } String matchingString = text.trim(); AngularProject project = null; try { project = AngularProject.getAngularProject(DOMUtils.getFile(attr) .getProject()); } catch (CoreException e) { } // Starts directives completion. project.collectDirectives(null, matchingString, null, Restriction.C, new IDirectiveCollector() { @Override public void add(Directive directive, String name) { // Add the directive in the completion. String displayString = name + " - " + directive.getModule().getName(); String additionalProposalInfo = directive .getHTMLDescription(); Image image = ImageResource .getImage(ImageResource.IMG_DIRECTIVE); addProposal(contentAssistRequest, name, directive.getDirectiveValue(), displayString, image, additionalProposalInfo); } @Override public void add(DirectiveParameter parameter) { // bo nothing } private void addProposal( final ContentAssistRequest contentAssistRequest, String name, DirectiveValue directiveValue, String displayString, Image image, String additionalProposalInfo) { String replacementString = directiveValue == DirectiveValue.none ? name : name + ":"; int replacementOffset = contentAssistRequest .getReplacementBeginPosition(); int replacementLength = contentAssistRequest .getReplacementLength(); if (index != -1) { replacementOffset += index; replacementLength += index; } int cursorPosition = getCursorPositionForProposedText(replacementString); IContextInformation contextInformation = null; int relevance = XMLRelevanceConstants.R_NONE; ICompletionProposal proposal = new CustomCompletionProposal( replacementString, replacementOffset, replacementLength, cursorPosition, image, displayString, contextInformation, additionalProposalInfo, relevance); contentAssistRequest.addProposal(proposal); } }); } private void populateAngularProposals( final ContentAssistRequest contentAssistRequest, IDOMNode element, final AngularType angularType, final Integer startIndex) { IFile file = DOMUtils.getFile(element); IProject eclipseProject = file.getProject(); try { IDETernProject ternProject = AngularProject .getTernProject(eclipseProject); // get the expression to use for Tern completion String expression = getExpression(contentAssistRequest, startIndex); final int replacementOffset = getReplacementOffset( contentAssistRequest, angularType, element.getNodeType() != Node.TEXT_NODE); // Create Tern doc + query TernAngularQuery query = new TernAngularCompletionsQuery( angularType); query.setExpression(expression); ITernScriptPath scriptPath = AngularScopeHelper.populateScope( element, file, angularType, query); // Execute Tern completion // final ITernServer ternServer = ternProject.getTernServer(); ITernCompletionCollector collector = new ITernCompletionCollector() { @Override public void addProposal(String name, String type, String origin, Object doc, int pos, Object completion, ITernServer ternServer) { ICompletionProposal proposal = null; if (isModuleOrController(angularType)) { MarkupAngularCompletionProposal markupPproposal = new MarkupAngularCompletionProposal( name, type, origin, doc, pos, completion, ternServer, angularType, replacementOffset); // in the case of "module", "controller" completion // the value must replace the existing value. String replacementString = "\"" + name + "\""; int replacementLength = contentAssistRequest .getReplacementLength(); int cursorPosition = getCursorPositionForProposedText(replacementString) - 2; markupPproposal.setReplacementString(replacementString); markupPproposal.setReplacementLength(replacementLength); markupPproposal.setCursorPosition(cursorPosition); markupPproposal.setReplacementOffset(replacementOffset); markupPproposal.setImage(getImage(angularType)); proposal = markupPproposal; } else { proposal = new JSAngularCompletionProposal(name, type, origin, doc, pos, completion, ternServer, angularType, replacementOffset); } contentAssistRequest.addProposal(proposal); } }; if (scriptPath != null) { ternProject.request(query, query.getFiles(), scriptPath, collector); } else { ternProject.request(query, query.getFiles(), element, file, collector); } } catch (Exception e) { Trace.trace(Trace.SEVERE, "Error while tern completion.", e); } } /** * Returns the expression to use for tern completion. * * @param contentAssistRequest * @param startIndex * @return */ private String getExpression(ContentAssistRequest contentAssistRequest, Integer startIndex) { String expression = contentAssistRequest.getMatchString(); if (startIndex != null) { // start index is not null , this case comes from when completion is // done in attribute : // 1) when completion is done inside an attribute <span // ng-app="MyModu // in this case the expression to use is 'MyModu' and not // '"MyModu' // 2) when completion is done inside an // attribute which define {{ // ex : <span class="done-{{to // in this case, the expression to use is 'to' and not // '"done-{{to' expression = expression.substring(startIndex, expression.length()); } return expression; } /** * Returns the replacement offset. * * @param contentAssistRequest * @param angularType * @param isAttr * @return */ private int getReplacementOffset(ContentAssistRequest contentAssistRequest, AngularType angularType, boolean isAttr) { int replacementOffset = contentAssistRequest .getReplacementBeginPosition(); if (isAttr) { // the completion is done in an attribute. if (!isModuleOrController(angularType)) { // getReplacementBeginPosition returns the position of the // starts of the attribute value (or quote). // in the case of attribute different from "module", // "controller", the replacement offset must // be the position where completion starts (ex : ng-model="todo. // => the position should be after todo. and before. replacementOffset += contentAssistRequest.getMatchString() .length(); } } return replacementOffset; } @Override protected ContentAssistRequest computeCompletionProposals( String matchString, ITextRegion completionRegion, IDOMNode treeNode, IDOMNode xmlnode, CompletionProposalInvocationContext context) { String regionType = completionRegion.getType(); boolean isXMLContent = (regionType == DOMRegionContext.XML_CONTENT); if (regionType == AngularRegionContext.ANGULAR_EXPRESSION_OPEN || regionType == AngularRegionContext.ANGULAR_EXPRESSION_CONTENT || (isXMLContent && DOMUtils.hasAngularNature(xmlnode))) { // completion for Angular expression {{}} inside text node. int documentPosition = context.getInvocationOffset(); IStructuredDocumentRegion documentRegion = ContentAssistUtils .getStructuredDocumentRegion(context.getViewer(), documentPosition); String match = null; int length = documentPosition - documentRegion.getStartOffset(); if (isXMLContent) { // case for JSP String text = documentRegion.getText().substring(0, length); int startExprIndex = text.lastIndexOf("{{"); if (startExprIndex != -1) { int endExprIndex = text.lastIndexOf("}}"); if (endExprIndex == -1 || endExprIndex < startExprIndex) { // completion (for JSP) is done inside angular // expression {{ match = text.substring(startExprIndex + 2, text.length()); } } } else { // case for HTML where regionType is an angular expression // open/content. if (length > 1) { // here we have {{ match = documentRegion.getText().substring(2, length); } } if (match != null) { ContentAssistRequest contentAssistRequest = new ContentAssistRequest( treeNode, treeNode.getParentNode(), documentRegion, completionRegion, documentPosition, 0, match); populateAngularProposals(contentAssistRequest, treeNode, AngularType.model, null); return contentAssistRequest; } } return super.computeCompletionProposals(matchString, completionRegion, treeNode, xmlnode, context); } @Override protected void addTagNameProposals( final ContentAssistRequest contentAssistRequest, int childPosition, CompletionProposalInvocationContext context) { IDOMNode node = (IDOMNode) contentAssistRequest.getNode(); if (DOMUtils.hasAngularNature(node)) { // completion for directive with 'E' restriction. String directiveName = contentAssistRequest.getMatchString(); AngularProject project = null; try { project = AngularProject.getAngularProject(DOMUtils.getFile( node).getProject()); } catch (CoreException e) { } project.collectDirectives(DirectiveHelper.ANY_TAG, directiveName, null, Restriction.E, new IDirectiveCollector() { @Override public void add(Directive directive, String name) { // Add the directive in the completion. String displayString = name + " - " + directive.getModule().getName(); String additionalProposalInfo = directive .getHTMLDescription(); Image image = ImageResource .getImage(ImageResource.IMG_DIRECTIVE); addProposal(contentAssistRequest, directive, name, displayString, image, additionalProposalInfo); } @Override public void add(DirectiveParameter parameter) { // do nothing } private void addProposal( final ContentAssistRequest contentAssistRequest, Directive directive, String name, String displayString, Image image, String additionalProposalInfo) { StringBuilder replacementString = new StringBuilder( ""); replacementString.append(name); Collection<DirectiveParameter> parameters = directive .getParameters(); for (DirectiveParameter parameter : parameters) { if (!parameter.isOptionnal()) { replacementString.append(" ") .append(parameter.getName()) .append("=\"\""); } } replacementString.append(">"); replacementString.append("</"); replacementString.append(name); replacementString.append(">"); int replacementOffset = contentAssistRequest .getReplacementBeginPosition(); int replacementLength = contentAssistRequest .getReplacementLength(); int cursorPosition = getCursorPositionForProposedText(replacementString .toString()); IContextInformation contextInformation = null; int relevance = XMLRelevanceConstants.R_TAG_NAME; ICompletionProposal proposal = new MarkupCompletionProposal( replacementString.toString(), replacementOffset, replacementLength, cursorPosition, image, displayString, contextInformation, additionalProposalInfo, relevance); contentAssistRequest.addProposal(proposal); } }); } super.addTagNameProposals(contentAssistRequest, childPosition, context); } /** * Returns true if the given angular type is module or controller and false * otherwise. * * @param angularType * @return */ private boolean isModuleOrController(final AngularType angularType) { return angularType == AngularType.module || angularType == AngularType.controller; } public void addDirectiveParameter( final ContentAssistRequest contentAssistRequest, DirectiveParameter parameter, IDOMNode element) { // Add the directive parameter in the // completion. if (hasParameterAttribute(parameter, element)) { return; } Directive directive = parameter.getDirective(); String displayString = parameter.getName() + " - " + directive.getModule().getName() + "#" + directive.getName(); String additionalProposalInfo = parameter.getHTMLDescription(); Image image = ImageResource.getImage(ImageResource.IMG_DIRECTIVE_PARAM); addProposal(contentAssistRequest, parameter.getName(), DirectiveValue.required, null, displayString, image, additionalProposalInfo, element); } public boolean hasParameterAttribute(DirectiveParameter parameter, IDOMNode element) { if (element.getNodeType() == Node.ELEMENT_NODE && element instanceof Element && ((Element) element).hasAttribute(parameter.getName())) { // the attribute alrady exists, ignore it. return true; } return false; } private void addProposal(final ContentAssistRequest contentAssistRequest, String name, DirectiveValue directiveValue, Directive directive, String displayString, Image image, String additionalProposalInfo, IDOMNode element) { StringBuilder replacementString = new StringBuilder(name); if (directiveValue != DirectiveValue.none) replacementString.append("=\"\""); if (directive != null) { Collection<DirectiveParameter> parameters = directive .getParameters(); for (DirectiveParameter parameter : parameters) { if (!parameter.isOptionnal() && !hasParameterAttribute(parameter, element)) { replacementString.append(" ").append(parameter.getName()) .append("=\"\""); } } } int replacementOffset = contentAssistRequest .getReplacementBeginPosition(); int replacementLength = contentAssistRequest.getReplacementLength(); int cursorPosition = getCursorPositionForProposedText(replacementString .toString()); IContextInformation contextInformation = null; int relevance = XMLRelevanceConstants.R_XML_ATTRIBUTE_NAME; ICompletionProposal proposal = new CustomCompletionProposal( replacementString.toString(), replacementOffset, replacementLength, cursorPosition, image, displayString, contextInformation, additionalProposalInfo, relevance); contentAssistRequest.addProposal(proposal); } /** * Returns the image to use for completion according to teh given angular * type. * * @param angularType * @return */ private static Image getImage(AngularType angularType) { switch (angularType) { case module: return ImageResource.getImage(ImageResource.IMG_ANGULARJS); case controller: return ImageResource.getImage(ImageResource.IMG_CONTROLLER); default: return null; } } }
package org.eclipse.che.ide.ext.java; import org.eclipse.che.api.core.ConflictException; import org.eclipse.che.api.core.ForbiddenException; import org.eclipse.che.api.core.NotFoundException; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.core.model.workspace.ProjectConfig; import org.eclipse.che.api.core.notification.EventService; import org.eclipse.che.api.project.server.FolderEntry; import org.eclipse.che.api.project.server.InvalidValueException; import org.eclipse.che.api.project.server.Project; import org.eclipse.che.api.project.server.ProjectManager; import org.eclipse.che.api.project.server.ProjectMisc; import org.eclipse.che.api.project.server.ProjectTypeConstraintException; import org.eclipse.che.api.project.server.ValueStorageException; import org.eclipse.che.api.project.server.VirtualFileEntry; import org.eclipse.che.api.project.server.handlers.ProjectHandlerRegistry; import org.eclipse.che.api.project.server.type.AttributeValue; import org.eclipse.che.api.project.server.type.ProjectTypeRegistry; import org.eclipse.che.api.project.shared.dto.SourceEstimation; import org.eclipse.che.api.vfs.server.SystemPathsFilter; import org.eclipse.che.api.vfs.server.VirtualFileSystemRegistry; import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; import org.eclipse.che.commons.env.EnvironmentContext; import org.eclipse.che.commons.user.UserImpl; import org.eclipse.che.vfs.impl.fs.LocalFSMountStrategy; import org.eclipse.che.vfs.impl.fs.LocalFileSystemProvider; import org.eclipse.core.runtime.Path; import javax.validation.constraints.NotNull; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Dummy implementation of ProjectManager used for tests * * @author Evgen Vidolob * @author Dmitry Shnurenko */ public class DummyProjectManager implements ProjectManager { final String vfsUser = "dev"; final Set<String> vfsUserGroups = new LinkedHashSet<>(Arrays.asList("workspace/developer")); private final LocalFileSystemProvider localFileSystemProvider; public DummyProjectManager(String workspacePath, EventService eventService) { EnvironmentContext context = new EnvironmentContext(); context.setUser(new UserImpl(vfsUser, "", "", vfsUserGroups, false)); EnvironmentContext.setCurrent(context); localFileSystemProvider = new LocalFileSystemProvider("", new LocalFSMountStrategy() { @Override public File getMountPath(String workspaceId) throws ServerException { return new File(workspacePath); } @Override public File getMountPath() throws ServerException { return new File(workspacePath); } }, eventService, null, SystemPathsFilter.ANY, null); } @Override public List<Project> getProjects(String workspace) throws ServerException, NotFoundException, ForbiddenException { final FolderEntry myRoot = getProjectsRoot(workspace); final List<Project> projects = new ArrayList<>(); for (FolderEntry folder : myRoot.getChildFolders()) { final Project project = getProject(workspace, folder.getPath()); if (project != null) { projects.add(project); } } return projects; } @Override public Project getProject(String workspace, String projectPath) throws ForbiddenException, ServerException, NotFoundException { final FolderEntry myRoot = getProjectsRoot(workspace); final VirtualFileEntry child = myRoot.getChild(projectPath.startsWith("/") ? projectPath.substring(1) : projectPath); if (child != null && child.isFolder() && isProjectFolder((FolderEntry)child)) { return new Project((FolderEntry)child, this); } return null; } @Override public ProjectConfigDto getProjectFromWorkspace(@NotNull String wsId, @NotNull String projectPath) throws ServerException { throw new UnsupportedOperationException("The method unsupported in this mode."); } @Override public List<ProjectConfigDto> getAllProjectsFromWorkspace(@NotNull String workspaceId) throws ServerException { throw new UnsupportedOperationException("The method unsupported in this mode."); } @Override public Project createProject(String workspace, String name, ProjectConfig projectConfig, Map<String, String> options) throws ConflictException, ForbiddenException, ServerException, ProjectTypeConstraintException, NotFoundException { final FolderEntry myRoot = getProjectsRoot(workspace); final FolderEntry projectFolder = myRoot.createFolder(name); final Project project = new Project(projectFolder, this); return project; } @Override public Project updateProject(String workspace, String path, ProjectConfig newConfig) throws ForbiddenException, ServerException, NotFoundException, ConflictException, IOException { throw new UnsupportedOperationException(); } @Override public FolderEntry getProjectsRoot(String workspace) throws ServerException, NotFoundException { return new FolderEntry(workspace, localFileSystemProvider.getMountPoint(true).getRoot()); } @Override public ProjectConfig getProjectConfig(Project project) throws ServerException, ProjectTypeConstraintException, ValueStorageException { throw new UnsupportedOperationException(); } @Override public void updateProjectConfig(Project project, ProjectConfig config) throws ServerException, ValueStorageException, ProjectTypeConstraintException, InvalidValueException { throw new UnsupportedOperationException(); } @Override public ProjectMisc getProjectMisc(Project project) throws ServerException { throw new UnsupportedOperationException(); } @Override public void saveProjectMisc(Project project, ProjectMisc misc) throws ServerException { throw new UnsupportedOperationException(); } @Override public List<ProjectConfig> getProjectModules(Project project) throws ServerException, ForbiddenException, ConflictException, IOException, NotFoundException { return Collections.emptyList(); } @Override public VirtualFileSystemRegistry getVirtualFileSystemRegistry() { throw new UnsupportedOperationException(); } @Override public ProjectTypeRegistry getProjectTypeRegistry() { throw new UnsupportedOperationException(); } @Override public ProjectHandlerRegistry getHandlers() { throw new UnsupportedOperationException(); } @Override public Map<String, AttributeValue> estimateProject(String workspace, String path, String projectTypeId) throws ValueStorageException, ServerException, ForbiddenException, NotFoundException, ProjectTypeConstraintException { throw new UnsupportedOperationException(); } @Override public ProjectConfigDto addModule(String workspace, String modulePath, ProjectConfigDto moduleConfig, Map<String, String> options) throws ConflictException, ForbiddenException, ServerException, NotFoundException { throw new UnsupportedOperationException(); } @Override public List<SourceEstimation> resolveSources(String workspace, String path, boolean transientOnly) throws ServerException, ForbiddenException, NotFoundException, ValueStorageException, ProjectTypeConstraintException { throw new UnsupportedOperationException(); } @Override public Project convertFolderToProject(String workspace, String path, ProjectConfig projectConfig) throws ConflictException, ForbiddenException, ServerException, NotFoundException { throw new UnsupportedOperationException(); } @Override public VirtualFileEntry rename(String workspace, String path, String newName, String newMediaType) throws ForbiddenException, ServerException, ConflictException, NotFoundException { throw new UnsupportedOperationException(); } @Override public void delete(String workspace, String path) throws ServerException, ForbiddenException, NotFoundException, ConflictException { deleteEntry(workspace, path); } private void deleteEntry(String workspace, String deleteEntryPath) throws ServerException, NotFoundException, ForbiddenException { final FolderEntry root = getProjectsRoot(workspace); final VirtualFileEntry entry = root.getChild(deleteEntryPath); entry.remove(); } @Override public void deleteModule(String workspaceId, String pathToParent, String pathToModule) throws ServerException, NotFoundException, ForbiddenException, ConflictException { deleteEntry(workspaceId, pathToModule); } @Override public boolean isProjectFolder(FolderEntry folder) throws ServerException { return new Path(folder.getPath()).segmentCount() == 1; } @Override public boolean isModuleFolder(FolderEntry folder) throws ServerException { return false; } }
package org.xcolab.portlets.loginregister.conference; import com.ext.portlet.community.CommunityConstants; import com.ext.utils.UserAccountGenerator; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.messaging.Message; import com.liferay.portal.kernel.messaging.MessageListener; import com.liferay.portal.kernel.messaging.MessageListenerException; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.model.Role; import com.liferay.portal.model.User; import com.liferay.portal.security.auth.DefaultScreenNameGenerator; import com.liferay.portal.security.auth.PrincipalThreadLocal; import com.liferay.portal.security.auth.ScreenNameGenerator; import com.liferay.portal.security.permission.PermissionChecker; import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil; import com.liferay.portal.security.permission.PermissionThreadLocal; import com.liferay.portal.service.*; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portlet.expando.model.ExpandoColumn; import com.liferay.portlet.expando.model.ExpandoColumnConstants; import com.liferay.portlet.expando.model.ExpandoTable; import com.liferay.portlet.expando.service.ExpandoColumnLocalServiceUtil; import com.liferay.portlet.expando.service.ExpandoTableLocalServiceUtil; import com.liferay.portlet.expando.service.ExpandoValueLocalServiceUtil; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.xcolab.portlets.loginregister.LoginController; import java.io.IOException; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Locale; public class AutoregisterConferencePeople implements MessageListener { @Override public void receive(Message message) throws MessageListenerException { new Thread() { @Override public void run() { try { List<ConferenceUser> users = getConferenceUsers(); for (ConferenceUser u : users) { registerUser(u); } } catch (Exception e) { e.printStackTrace(); } } }.start(); } private void registerUser(ConferenceUser u) { try { String email = u.geteMail(); if (emailExists(email)) email = u.getSecondaryEmail(); if (!emailExists(email)) { UserAccountGenerator userAccountGenerator = new UserAccountGenerator(); String screenName = userAccountGenerator.generateUsername(u.getFirstName(), u.getLastName()); Role adminRole = RoleLocalServiceUtil.getRole(LoginController.companyId, "Administrator"); List<User> adminUsers = UserLocalServiceUtil.getRoleUsers(adminRole.getRoleId()); PrincipalThreadLocal.setName(adminUsers.get(0).getUserId()); PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(adminUsers.get(0), true); PermissionThreadLocal.setPermissionChecker(permissionChecker); // ServiceContext ctx = ServiceContextFactory.getInstance(User.class + "", null); ServiceContext ctx = new ServiceContext(); ctx.setAttribute("anonymousUser", true); User user = UserServiceUtil.addUserWithWorkflow(LoginController.companyId, true, null, null, false, screenName, email, 0, "", Locale.ENGLISH, u.getFirstName(), "", u.getLastName(), 0, 0, true, 1, 1, 1970, "", new long[]{}, new long[]{}, new long[]{}, new long[]{}, true, ctx); setConferenceAttendingExpando(user); System.out.println("automatically registered user " + screenName + ": " + user); } } catch (Exception e) { e.printStackTrace(); } } private void setConferenceAttendingExpando(User u) throws SystemException, PortalException { ExpandoTable table = null; try { table = ExpandoTableLocalServiceUtil.getTable(User.class.getName(), CommunityConstants.EXPANDO); } catch (Exception e) { e.printStackTrace(); } //create table if(table == null) { System.out.println("creating expando table"); table = ExpandoTableLocalServiceUtil.addTable(LoginController.companyId,User.class.getName(), CommunityConstants.EXPANDO); } ExpandoColumn conferenceExpando = null; try { conferenceExpando = ExpandoColumnLocalServiceUtil.getColumn(table.getTableId(), CommunityConstants.CONFERENCE2013); } catch (Exception e) { } // create column if (conferenceExpando == null) { System.out.println("creating expando column"); conferenceExpando = ExpandoColumnLocalServiceUtil.addColumn(table.getTableId(), CommunityConstants.CONFERENCE2013, ExpandoColumnConstants.STRING); } ExpandoValueLocalServiceUtil.addValue(User.class.getName(), CommunityConstants.EXPANDO, CommunityConstants.CONFERENCE2013, u.getUserId(), "1"); } private boolean emailExists(String email) { try { UserLocalServiceUtil.getUserByEmailAddress(LoginController.companyId, email); return true; } catch (Exception e) { return false; } } private List<ConferenceUser> getConferenceUsers() throws IOException { HttpClient client = new HttpClient(); GetMethod method = new GetMethod("https://classic.regonline.com/activereports/smartLink.aspx?eventid=WThQT9uce5k=&crid=1056641"); client.executeMethod(method); Workbook wb = new HSSFWorkbook(method.getResponseBodyAsStream()); Sheet sheet = wb.getSheetAt(0); List<ConferenceUser> users = new LinkedList<>(); for (Row row : sheet) { if (row.getRowNum() == 0) continue; //skip header try { users.add(new ConferenceUser(row)); } catch (Exception e) { } } method.releaseConnection(); return users; } }
package com.opengamma.analytics.financial.interestrate.swap.provider; import static org.testng.AssertJUnit.assertEquals; import java.util.LinkedHashMap; import org.testng.annotations.Test; import org.threeten.bp.Period; import org.threeten.bp.ZonedDateTime; import com.opengamma.analytics.financial.instrument.index.GeneratorAttributeIR; import com.opengamma.analytics.financial.instrument.index.GeneratorLegIborMaster; import com.opengamma.analytics.financial.instrument.index.GeneratorLegOnAaMaster; import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedIbor; import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedIborMaster; import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedON; import com.opengamma.analytics.financial.instrument.index.GeneratorSwapFixedONMaster; import com.opengamma.analytics.financial.instrument.index.GeneratorSwapONAAIbor; import com.opengamma.analytics.financial.instrument.index.IborIndex; import com.opengamma.analytics.financial.instrument.swap.SwapDefinition; import com.opengamma.analytics.financial.instrument.swap.SwapFixedIborDefinition; import com.opengamma.analytics.financial.interestrate.datasets.StandardDataSetsMulticurveUSD; import com.opengamma.analytics.financial.interestrate.payments.derivative.Payment; import com.opengamma.analytics.financial.interestrate.swap.derivative.Swap; import com.opengamma.analytics.financial.provider.calculator.discounting.ParRateDiscountingCalculator; import com.opengamma.analytics.financial.provider.calculator.discounting.ParSpreadMarketQuoteDiscountingCalculator; import com.opengamma.analytics.financial.provider.calculator.discounting.PresentValueCurveSensitivityDiscountingCalculator; import com.opengamma.analytics.financial.provider.calculator.discounting.PresentValueDiscountingCalculator; import com.opengamma.analytics.financial.provider.calculator.generic.MarketQuoteSensitivityBlockCalculator; import com.opengamma.analytics.financial.provider.curve.CurveBuildingBlockBundle; import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderDiscount; import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderInterface; import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyParameterSensitivity; import com.opengamma.analytics.financial.provider.sensitivity.parameter.ParameterSensitivityParameterCalculator; import com.opengamma.analytics.financial.util.AssertSensitivityObjects; import com.opengamma.analytics.math.matrix.DoubleMatrix1D; import com.opengamma.financial.convention.calendar.Calendar; import com.opengamma.timeseries.precise.zdt.ImmutableZonedDateTimeDoubleTimeSeries; import com.opengamma.timeseries.precise.zdt.ZonedDateTimeDoubleTimeSeries; import com.opengamma.util.money.Currency; import com.opengamma.util.money.MultipleCurrencyAmount; import com.opengamma.util.test.TestGroup; import com.opengamma.util.time.DateUtils; import com.opengamma.util.tuple.ObjectsPair; import com.opengamma.util.tuple.Pair; /** * Tests the Swap discounting method with standard data. * Demo test - worked-out example on how to use OG-Analytics library for compute standard measure to simple instruments. * The data is hard-coded. It is also available in some integration unit test and in snapshots. */ @Test(groups = TestGroup.UNIT) public class SwapCalculatorE2ETest { private static final IborIndex[] INDEX_IBOR_LIST = StandardDataSetsMulticurveUSD.indexIborArrayUSDOisL1L3L6(); private static final IborIndex USDLIBOR1M = INDEX_IBOR_LIST[0]; private static final IborIndex USDLIBOR3M = INDEX_IBOR_LIST[1]; private static final Calendar NYC = StandardDataSetsMulticurveUSD.calendarArray()[0]; private static final Currency USD = USDLIBOR3M.getCurrency(); private static final PresentValueDiscountingCalculator PVDC = PresentValueDiscountingCalculator.getInstance(); private static final ParRateDiscountingCalculator PRDC = ParRateDiscountingCalculator.getInstance(); private static final ParSpreadMarketQuoteDiscountingCalculator PSMQDC = ParSpreadMarketQuoteDiscountingCalculator.getInstance(); private static final PresentValueCurveSensitivityDiscountingCalculator PVCSDC = PresentValueCurveSensitivityDiscountingCalculator.getInstance(); private static final ParameterSensitivityParameterCalculator<MulticurveProviderInterface> PSC = new ParameterSensitivityParameterCalculator<>(PVCSDC); private static final MarketQuoteSensitivityBlockCalculator<MulticurveProviderInterface> MQSBC = new MarketQuoteSensitivityBlockCalculator<>(PSC); // Curve Data private static final Pair<MulticurveProviderDiscount, CurveBuildingBlockBundle> MULTICURVE_PAIR = StandardDataSetsMulticurveUSD.getCurvesUSDOisL1L3L6(); private static final MulticurveProviderDiscount MULTICURVE = MULTICURVE_PAIR.getFirst(); private static final CurveBuildingBlockBundle BLOCK = MULTICURVE_PAIR.getSecond(); private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2014, 1, 22); // Standard conventions private static final GeneratorSwapFixedIborMaster GENERATOR_SWAP_FIXED_IBOR_MASTER = GeneratorSwapFixedIborMaster.getInstance(); private static final GeneratorSwapFixedONMaster GENERATOR_SWAP_FIXED_ONCMP_MASTER = GeneratorSwapFixedONMaster.getInstance(); private static final GeneratorSwapFixedIbor USD6MLIBOR1M = GENERATOR_SWAP_FIXED_IBOR_MASTER.getGenerator("USD6MLIBOR1M", NYC); private static final GeneratorSwapFixedIbor USD6MLIBOR3M = GENERATOR_SWAP_FIXED_IBOR_MASTER.getGenerator("USD6MLIBOR3M", NYC); private static final GeneratorSwapFixedON USD1YFEDFUND = GENERATOR_SWAP_FIXED_ONCMP_MASTER.getGenerator("USD1YFEDFUND", NYC); private static final GeneratorSwapONAAIbor USDFFAA3MLIBOR3M = new GeneratorSwapONAAIbor("USDFEDFUNDAA3MLIBOR3M", GeneratorLegOnAaMaster.getInstance().getGenerator("USDFEDFUNDAA3M", NYC), GeneratorLegIborMaster.getInstance().getGenerator("USDLIBOR3M", NYC)); private static final double NOTIONAL = 100000000; //100m // Instrument description: Swap Fixed vs ON Cmp private static final ZonedDateTime START_DATE_ON = DateUtils.getUTCDate(2014, 2, 3); private static final Period TENOR_SWAP_ON = Period.ofMonths(2); private static final double FIXED_RATE_ON = 0.00123; private static final GeneratorAttributeIR ATTRIBUTE_ON = new GeneratorAttributeIR(TENOR_SWAP_ON); private static final SwapDefinition SWAP_FIXED_ON_DEFINITION = USD1YFEDFUND.generateInstrument(START_DATE_ON, FIXED_RATE_ON, NOTIONAL, ATTRIBUTE_ON); private static final Swap<? extends Payment, ? extends Payment> SWAP_FIXED_ON = SWAP_FIXED_ON_DEFINITION.toDerivative(REFERENCE_DATE); // Instrument description: Swap ON AA vs Libor 3M private static final ZonedDateTime START_DATE_FF = DateUtils.getUTCDate(2014, 9, 10); private static final Period TENOR_SWAP_FF = Period.ofYears(6); private static final double SPREAD_FF = 0.0025; private static final GeneratorAttributeIR ATTRIBUTE_FF = new GeneratorAttributeIR(TENOR_SWAP_FF); private static final SwapDefinition SWAP_FF_3M_0_DEFINITION = USDFFAA3MLIBOR3M.generateInstrument(START_DATE_FF, 0.0, NOTIONAL, ATTRIBUTE_FF); private static final Swap<? extends Payment, ? extends Payment> SWAP_FF_3M_0 = SWAP_FF_3M_0_DEFINITION.toDerivative(REFERENCE_DATE); private static final SwapDefinition SWAP_FF_3M_DEFINITION = USDFFAA3MLIBOR3M.generateInstrument(START_DATE_FF, SPREAD_FF, NOTIONAL, ATTRIBUTE_FF); private static final Swap<? extends Payment, ? extends Payment> SWAP_FF_3M = SWAP_FF_3M_DEFINITION.toDerivative(REFERENCE_DATE); // Instrument description: Swap Fixed vs Libor3M private static final ZonedDateTime START_DATE_3M = DateUtils.getUTCDate(2014, 9, 10); private static final Period TENOR_SWAP_3M = Period.ofYears(7); private static final double FIXED_RATE_3M = 0.0150; private static final GeneratorAttributeIR ATTRIBUTE_3M = new GeneratorAttributeIR(TENOR_SWAP_3M); private static final SwapDefinition SWAP_FIXED_3M_DEFINITION = USD6MLIBOR3M.generateInstrument(START_DATE_3M, FIXED_RATE_3M, NOTIONAL, ATTRIBUTE_3M); private static final Swap<? extends Payment, ? extends Payment> SWAP_FIXED_3M = SWAP_FIXED_3M_DEFINITION.toDerivative(REFERENCE_DATE); // Instrument description: Swap Fixed vs Libor1M private static final ZonedDateTime START_DATE_1M = DateUtils.getUTCDate(2014, 9, 10); private static final Period TENOR_SWAP_1M = Period.ofYears(2); private static final double FIXED_RATE_1M = 0.0125; private static final GeneratorAttributeIR ATTRIBUTE_1M = new GeneratorAttributeIR(TENOR_SWAP_1M); private static final SwapDefinition SWAP_FIXED_1M_DEFINITION = USD6MLIBOR1M.generateInstrument(START_DATE_1M, FIXED_RATE_1M, NOTIONAL, ATTRIBUTE_1M); private static final Swap<? extends Payment, ? extends Payment> SWAP_FIXED_1M = SWAP_FIXED_1M_DEFINITION.toDerivative(REFERENCE_DATE); // Instrument description: Swap Fixed vs Libor3M Already started (with fixing) private static final ZonedDateTime START_DATE_3M_S = DateUtils.getUTCDate(2013, 9, 10); private static final Period TENOR_SWAP_3M_S = Period.ofYears(7); private static final double FIXED_RATE_3M_S = 0.0150; private static final GeneratorAttributeIR ATTRIBUTE_3M_S = new GeneratorAttributeIR(TENOR_SWAP_3M_S); private static final SwapFixedIborDefinition SWAP_FIXED_3M_S_DEFINITION = USD6MLIBOR3M.generateInstrument(START_DATE_3M_S, FIXED_RATE_3M_S, NOTIONAL, ATTRIBUTE_3M_S); private static final ZonedDateTimeDoubleTimeSeries TS_IBOR_USD3M = ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(new ZonedDateTime[] {DateUtils.getUTCDate(2013, 12, 10), DateUtils.getUTCDate(2013, 12, 12) }, new double[] {0.0024185, 0.0100 }); private static final ZonedDateTimeDoubleTimeSeries[] TS_FIXED_IBOR_USD3M = new ZonedDateTimeDoubleTimeSeries[] {TS_IBOR_USD3M }; private static final Swap<? extends Payment, ? extends Payment> SWAP_FIXED_3M_S = SWAP_FIXED_3M_S_DEFINITION.toDerivative(REFERENCE_DATE, TS_FIXED_IBOR_USD3M); // Instrument description: Swap Libor3M+S vs Libor6M private static final double TOLERANCE_PV = 1.0E-3; private static final double TOLERANCE_PV_DELTA = 1.0E-4; private static final double TOLERANCE_RATE = 1.0E-8; private static final double BP1 = 1.0E-4; /** FEDFUND products **/ @Test /** Tests present value for a swap fixed vs ON compounded. */ public void presentValueONCmp() { final MultipleCurrencyAmount pvComputed = SWAP_FIXED_ON.accept(PVDC, MULTICURVE); final MultipleCurrencyAmount pvExpected = MultipleCurrencyAmount.of(Currency.USD, -9723.264518929138); assertEquals("Swap Fixed v ON compounded: present value from standard curves", pvExpected.getAmount(USD), pvComputed.getAmount(USD), TOLERANCE_PV); } @Test /** Tests forward rate for a swap fixed vs Fed Fund compounded. */ public void parRateONCmp() { final double parRate = SWAP_FIXED_ON.accept(PRDC, MULTICURVE); final double parRateExpected = 6.560723881400023E-4; assertEquals("Swap Fixed v ON compounded: par rate from standard curves", parRateExpected, parRate, TOLERANCE_RATE); } @Test /** Tests present value of ON Arithmetic Average (+ spread) vs Libor3M swaps. */ public void parSpreadMarketQuoteONAA3M() { final double parSpread = SWAP_FF_3M_0.accept(PSMQDC, MULTICURVE); final double parSpreadExpected = 0.0027741318; assertEquals("Swap ON Arithmetic Average: par spread", parSpreadExpected, parSpread, TOLERANCE_RATE); } @Test /** Tests present value of ON Arithmetic Average (+ spread) vs Libor3M swaps. */ public void presentValueONAA3M() { final MultipleCurrencyAmount pv0Computed = SWAP_FF_3M_0.accept(PVDC, MULTICURVE); // Spread = 0 final MultipleCurrencyAmount pv0Expected = MultipleCurrencyAmount.of(Currency.USD, -1617070.5290); assertEquals("Swap ON Arithmetic Average: present value", pv0Expected.getAmount(USD), pv0Computed.getAmount(USD), TOLERANCE_PV); final MultipleCurrencyAmount pvComputed = SWAP_FF_3M.accept(PVDC, MULTICURVE); // Spread final MultipleCurrencyAmount pvExpected = MultipleCurrencyAmount.of(Currency.USD, -159794.3224); assertEquals("Swap ON Arithmetic Average: present value", pvExpected.getAmount(USD), pvComputed.getAmount(USD), TOLERANCE_PV); } @Test /** Tests Bucketed PV01 of ON Arithmetic Average (+ spread) vs Libor3M swaps. */ public void BucketedPV01ONAA3M() { final double[] deltaDsc = {-0.53657, -0.53657, 1.50563, -20.38650, 156.45965, -3141.24234, -3355.04638, -13.91364, 42.96362, 61.31768, 44.65782, -104.16588, 23501.58783, 40086.81647, 0.00000, 0.00000, 0.00000}; final double[] deltaFwd3 = {2605.09563, 2632.09625, 1176.12448, -27.11358, 33.63026, 6.79543, 7.46515, -11436.33187, -52207.12832, 0.00000, 0.00000, 0.00000, 0.00000, 0.00000, 0.00000 }; final LinkedHashMap<Pair<String, Currency>, DoubleMatrix1D> sensitivity = new LinkedHashMap<>(); sensitivity.put(ObjectsPair.of(MULTICURVE.getName(USD), USD), new DoubleMatrix1D(deltaDsc)); sensitivity.put(ObjectsPair.of(MULTICURVE.getName(USDLIBOR3M), USD), new DoubleMatrix1D(deltaFwd3)); final MultipleCurrencyParameterSensitivity pvpsExpected = new MultipleCurrencyParameterSensitivity(sensitivity); final MultipleCurrencyParameterSensitivity pvpsComputed = MQSBC.fromInstrument(SWAP_FF_3M, MULTICURVE, BLOCK).multipliedBy(BP1); AssertSensitivityObjects.assertEquals("Swap ON Arithmetic Average: bucketed delts from standard curves", pvpsExpected, pvpsComputed, TOLERANCE_PV_DELTA); } /** LIBOR3M products **/ @Test /** Test present value for a swap fixed vs LIBOR3M. */ public void presentValue3M() { final MultipleCurrencyAmount pvComputed = SWAP_FIXED_3M.accept(PVDC, MULTICURVE); final MultipleCurrencyAmount pvExpected = MultipleCurrencyAmount.of(Currency.USD, 7170391.798257509); assertEquals("ForwardRateAgreementDiscountingMethod: present value from standard curves", pvExpected.getAmount(USD), pvComputed.getAmount(USD), TOLERANCE_PV); } @Test /** Test present value for a swap fixed vs LIBOR3M. */ public void presentValue3MWithFixing() { final MultipleCurrencyAmount pvComputed = SWAP_FIXED_3M_S.accept(PVDC, MULTICURVE); final MultipleCurrencyAmount pvExpected = MultipleCurrencyAmount.of(Currency.USD, 3588376.471608199); assertEquals("ForwardRateAgreementDiscountingMethod: present value from standard curves", pvExpected.getAmount(USD), pvComputed.getAmount(USD), TOLERANCE_PV); } @Test /** Test forward rate for a swap fixed vs LIBOR1M. */ public void parRate3M() { final double parRate = SWAP_FIXED_3M.accept(PRDC, MULTICURVE); final double parRateExpected = 0.025894715668195054; assertEquals("ForwardRateAgreementDiscountingMethod: par rate from standard curves", parRateExpected, parRate, TOLERANCE_RATE); } @Test /** Test Bucketed PV01 for a swap fixed vs LIBOR3M. */ public void BucketedPV013M() { final double[] deltaDsc = {-2.0061282888005487, -2.0061296819291816, -8.67452075363044E-5, 0.0011745459201512494, 1.4847039752079148, -56.9491079838621, 1.1272953888594144, -86.07354102781184, -166.96224129263487, -242.22201138850485, -314.19406010048203, -385.9029177491706, -463.2762183477875, -979.7315575792289, -243.35533439972858, 243.5314114568193, 139.99052652789604 }; final double[] deltaFwd3 = {-2604.935862485693, -2632.099517240374, -1176.1264079094185, 27.132459446981603, -34.136228550265635, -8.299063015802915, -10.516911338517652, 0.5088197130590212, 56648.04062948109, 15520.134985155655, 0.00, 0.00, 0.00, 0.00, 0.00 }; final LinkedHashMap<Pair<String, Currency>, DoubleMatrix1D> sensitivity = new LinkedHashMap<>(); sensitivity.put(ObjectsPair.of(MULTICURVE.getName(USD), USD), new DoubleMatrix1D(deltaDsc)); sensitivity.put(ObjectsPair.of(MULTICURVE.getName(USDLIBOR3M), USD), new DoubleMatrix1D(deltaFwd3)); final MultipleCurrencyParameterSensitivity pvpsExpected = new MultipleCurrencyParameterSensitivity(sensitivity); final MultipleCurrencyParameterSensitivity pvpsComputed = MQSBC.fromInstrument(SWAP_FIXED_3M, MULTICURVE, BLOCK).multipliedBy(BP1); AssertSensitivityObjects.assertEquals("ForwardRateAgreementDiscountingMethod: bucketed delts from standard curves", pvpsExpected, pvpsComputed, TOLERANCE_PV_DELTA); } /** LIBOR1M products **/ @Test /**Test present value for a swap fixed vs LIBOR1M. */ public void presentValue1M() { final MultipleCurrencyAmount pvComputed = SWAP_FIXED_1M.accept(PVDC, MULTICURVE); final MultipleCurrencyAmount pvExpected = MultipleCurrencyAmount.of(Currency.USD, -1003685.179128858); assertEquals("ForwardRateAgreementDiscountingMethod: present value from standard curves", pvExpected.getAmount(USD), pvComputed.getAmount(USD), TOLERANCE_PV); } @Test /** Test forward rate for a swap fixed vs LIBOR1M. */ public void parRate1M() { final double parRate = SWAP_FIXED_1M.accept(PRDC, MULTICURVE); final double parRateExpected = 0.007452504182638092; assertEquals("ForwardRateAgreementDiscountingMethod: par rate from standard curves", parRateExpected, parRate, TOLERANCE_RATE); } @Test /** Test Bucketed PV01 for a swap fixed vs LIBOR1M. */ public void BucketedPV011M() { final double[] deltaDsc = {0.30079551275104416, 0.30079572164276736, -9.585961874740465E-6, 1.2979495579621574E-4, 1.5085871713580485, -13.566109046684943, 0.09026843918435334, 45.96990975622252, 99.74522348776304, 104.85108270307225, -9.33773534893459E-11, -4.285397912505579E-12, 0.00, 0.00, 0.00, 0.00, 0.00 }; final double[] deltaFwd1 = {-0.20863786628281816, 2887.648010427227, 3524.8181060609513, 54.75432367092116, -9894.416325570519, -16771.99913018682, -3.0220503938933227E-10, 3.729948495906336E-10, 1.6330782253589604E-10, -8.986191325519167E-11, 0.00, 0.00, 0.00, 0.00, 0.00 }; final double[] deltaFwd3 = {-2597.896012855518, -2626.224124335432, -1187.3995581915851, -53.9916796422252, 9752.524496704595, 16503.81428148996, 4.871798063348056E-10, -6.672030279745711E-10, -1.7934130597452707E-10, 1.7682040814394901E-10, 0.00, 0.00, 0.00, 0.00, 0.00 }; final LinkedHashMap<Pair<String, Currency>, DoubleMatrix1D> sensitivity = new LinkedHashMap<>(); sensitivity.put(ObjectsPair.of(MULTICURVE.getName(USD), USD), new DoubleMatrix1D(deltaDsc)); sensitivity.put(ObjectsPair.of(MULTICURVE.getName(USDLIBOR1M), USD), new DoubleMatrix1D(deltaFwd1)); sensitivity.put(ObjectsPair.of(MULTICURVE.getName(USDLIBOR3M), USD), new DoubleMatrix1D(deltaFwd3)); final MultipleCurrencyParameterSensitivity pvpsExpected = new MultipleCurrencyParameterSensitivity(sensitivity); final MultipleCurrencyParameterSensitivity pvpsComputed = MQSBC.fromInstrument(SWAP_FIXED_1M, MULTICURVE, BLOCK).multipliedBy(BP1); AssertSensitivityObjects.assertEquals("ForwardRateAgreementDiscountingMethod: bucketed delts from standard curves", pvpsExpected, pvpsComputed, TOLERANCE_PV_DELTA); } }
package org.jboss.as.test.integration.logging.operations; import org.jboss.arquillian.container.test.api.ContainerController; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLEncoder; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*; /** * @author <a href="mailto:pkremens@redhat.com">Petr Kremensky</a> */ @RunWith(Arquillian.class) public class SizeRotatingHandlerTestCase extends AbstractLoggingOperationsTestCase { private static String fileName = "size-rotating-reload.log"; private static final String SIZE_HANDLER_NAME = "sizeRotatingHandlerTestCase"; private static final ModelNode SIZE_HANDLER_ADDRESS = createAddress("size-rotating-file-handler", SIZE_HANDLER_NAME).toModelNode(); @ContainerResource private ManagementClient managementClient; @ArquillianResource ContainerController controller; @ArquillianResource(DefaultLoggingServlet.class) private URL url; private File logFile = null; @Deployment public static WebArchive createDeployment() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "default-logging.war"); archive.addClasses(DefaultLoggingServlet.class); return archive; } /* * Create basic logging configuration */ private void loggingSetup() throws Exception { logFile = getAbsoluteLogFilePath(managementClient, fileName); // Clear logs clearLogs(logFile); final ModelControllerClient client = managementClient.getControllerClient(); // Create the size rotating handler ModelNode op = Operations.createAddOperation(SIZE_HANDLER_ADDRESS); ModelNode file = new ModelNode(); file.get("path").set(logFile.getAbsolutePath()); op.get(FILE).set(file); validateResponse(op); // Add the handler to the root-logger op = Operations.createOperation("add-handler", createRootLoggerAddress().toModelNode()); op.get(ModelDescriptionConstants.NAME).set(SIZE_HANDLER_NAME); validateResponse(op); } @Test @RunAsClient public void testEnabled() throws Exception { final String disabledMsg = "SizeRotatingHandlerTestCase - This message should not appear in log file"; final String enabledMsg = "SizeRotatingHandlerTestCase - This message should appear in log file"; fileName = "size-rotating-reload-testEnabled.log"; loggingSetup(); // disable handler ModelNode op = Operations.createOperation(DISABLE, SIZE_HANDLER_ADDRESS); validateResponse(op); op = Operations.createReadAttributeOperation(SIZE_HANDLER_ADDRESS, ENABLED); Assert.assertFalse("Handler should be disabled.", validateResponse(op, true).asBoolean()); searchLog(disabledMsg, false); // enable handler op = Operations.createOperation(ENABLE, SIZE_HANDLER_ADDRESS); validateResponse(op); op = Operations.createReadAttributeOperation(SIZE_HANDLER_ADDRESS, ENABLED); Assert.assertTrue("Handler should be enabled.", validateResponse(op, true).asBoolean()); searchLog(enabledMsg, true); } @Test @RunAsClient public void rotationTest() throws Exception { final String message = "SizeRotatingHandlerTestCase - This is my dummy message which is gonna fill my log file"; final String newMessage = "SizeRotatingHandlerTestCase - This is new message"; final int maxBackupIndex = 3; fileName = "size-rotating-reload-rotationTest.log"; loggingSetup(); ModelNode op = Operations.createWriteAttributeOperation(SIZE_HANDLER_ADDRESS, "max-backup-index", maxBackupIndex); validateResponse(op); op = Operations.createWriteAttributeOperation(SIZE_HANDLER_ADDRESS, "rotate-size", "2k"); validateResponse(op); op = Operations.createReadResourceOperation(SIZE_HANDLER_ADDRESS); validateResponse(op); for (int i = 0; i < 100; i++) { makeLog(message); } checkLogs(message, true); // check that file size is not greater than 2k and it contains message int count = 0; for (File file : logFile.getParentFile().listFiles()) { if (file.getName().contains(logFile.getName())) { long length = file.length(); Assert.assertTrue(String.format("File %s is bigger than allowed rotate-size. File length = %d", file.getName(), length), length < 2500); checkLogs(message, true, file); count++; } } // verify max-backup-index Assert.assertEquals("Incorrect number of log files were found.", maxBackupIndex + 1, count); searchLog(newMessage, true); } @After public void cleanUp() throws Exception { // Remove the handler from the root-logger ModelNode op = Operations.createOperation("remove-handler", createRootLoggerAddress().toModelNode()); op.get(ModelDescriptionConstants.NAME).set(SIZE_HANDLER_NAME); validateResponse(op); // Remove the size rotating handler op = Operations.createRemoveOperation(SIZE_HANDLER_ADDRESS); validateResponse(op); // Clear logs clearLogs(logFile); } @Override protected ManagementClient getManagementClient() { return managementClient; } /* * Clear all log files for test (don't forget for rotated ones) */ private void clearLogs(File file) { for (File f : file.getParentFile().listFiles()) { if (f.getName().contains(logFile.getName())) { f.delete(); if (f.exists()) { Assert.fail("Unable to delete file: " + f.getName()); } } } } private ModelNode validateResponse(ModelNode operation) throws Exception { return validateResponse(operation, false); } private ModelNode validateResponse(ModelNode operation, boolean validateResult) throws Exception { final ModelNode response = executeOperation(operation); if (!Operations.isSuccessfulOutcome(response)) { Assert.fail(Operations.getFailureDescription(response).toString()); } if (validateResult) { Assert.assertTrue("result exists", response.hasDefined(RESULT)); } return response.get(RESULT); } /* * Make log of message, and search logFile */ private void searchLog(final String msg, final boolean expected) throws Exception { makeLog(msg); checkLogs(msg, expected); } private void checkLogs(final String msg, final boolean expected) throws Exception { checkLogs(msg, expected, logFile); } /* * Search file for message */ private void checkLogs(final String msg, final boolean expected, File file) throws Exception { BufferedReader reader = null; // check logs try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8")); String line; boolean logFound = false; while ((line = reader.readLine()) != null) { if (line.contains(msg)) { logFound = true; break; } } Assert.assertTrue("Message: \"" + msg + "\" was not found in file: " + file.getName(), logFound == expected); } finally { safeClose(reader); } } private void makeLog(String msg) throws Exception { int statusCode = getResponse(new URL(url, "logger?msg=" + URLEncoder.encode(msg, "utf-8"))); Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpServletResponse.SC_OK); } }
package org.jboss.as.test.clustering.single.jdbcstore; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import javax.naming.InitialContext; import javax.naming.NamingException; /** * Verify the integration between JdbcCacheStore and XADataSource. XADataSource's * connection should be properly enlisted with the ongoing transaction when * Infinispan internally calls its getConnection() method. * * These tests should be failing until ISPN-604 is resolved. * * @author Martin Gencur */ @RunWith(Arquillian.class) @Ignore("https://issues.jboss.org/browse/ISPN-604") public class TransactionalJdbcStoreTestCase { @Deployment public static Archive<?> deployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "test.war"); war.addClasses(TransactionalJdbcStoreTestCase.class, TransactionalInfinispanManagedBean.class); war.addAsManifestResource(new StringAsset("Manifest-Version: 1.0\nDependencies: org.infinispan export\n"), "MANIFEST.MF"); return war; } @Test public void testTxPutCommit() throws Exception { getIspnBeanFromJndi().testTxPutCommit(); } @Test public void testTxPutRollback() throws Exception { getIspnBeanFromJndi().testTxPutRollback(); } @Test public void testTxRemoveCommit() throws Exception { getIspnBeanFromJndi().testTxRemoveCommit(); } @Test public void testTxRemoveRollback() throws Exception { getIspnBeanFromJndi().testTxRemoveRollback(); } @Test public void testTxAlterCommit() throws Exception { getIspnBeanFromJndi().testTxAlterCommit(); } @Test public void testTxAlterRollback() throws Exception { getIspnBeanFromJndi().testTxAlterRollback(); } private TransactionalInfinispanManagedBean getIspnBeanFromJndi() { InitialContext context; Object result; try { context = new InitialContext(); result = context.lookup("java:module/infinispan"); } catch (NamingException e) { throw new RuntimeException(e); } Assert.assertTrue(result instanceof TransactionalInfinispanManagedBean); TransactionalInfinispanManagedBean bean = (TransactionalInfinispanManagedBean) result; return bean; } }
package org.curioswitch.gradle.plugins.ci; import static com.google.common.base.Preconditions.checkNotNull; import static org.curioswitch.common.testing.assertj.CurioAssertions.assertThat; import com.google.common.collect.ImmutableMap; import com.google.common.io.Resources; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.gradle.testkit.runner.GradleRunner; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; class CurioGenericCiPluginTest { @SuppressWarnings("ClassCanBeStatic") @Nested class MasterBranchNoDiffs { private File projectDir; @BeforeAll void copyProject(@TempDir Path projectDir) throws Exception { copyProjectFromResources("test-projects/gradle-curio-generic-ci-plugin/normal", projectDir); this.projectDir = projectDir.toFile(); } @Test void noCi() { var result = GradleRunner.create() .withProjectDir(projectDir) .withArguments("continuousBuild", "--stacktrace") .withEnvironment(ImmutableMap.of()) .withPluginClasspath() .buildAndFail(); assertThat(result.getOutput()).contains("Task 'continuousBuild' not found in root project"); } @Test void ciNotMaster() { var result = GradleRunner.create() .withProjectDir(projectDir) .withArguments("continuousBuild") .withEnvironment(ImmutableMap.of("CI", "true")) .withPluginClasspath() .build(); assertThat(result.task(":library1:build")).isNull(); assertThat(result.task(":server1:build")).isNull(); } @Test void ciIsMaster() { var result = GradleRunner.create() .withProjectDir(projectDir) .withArguments("continuousBuild") .withEnvironment(ImmutableMap.of("CI", "true", "CI_MASTER", "true")) .withPluginClasspath() .build(); assertThat(result.task(":library1:build")).isNull(); assertThat(result.task(":server1:build")).isNull(); } @SuppressWarnings("ClassCanBeStatic") @Nested class ReleaseBuild { @Test void implicitTag() { var result = GradleRunner.create() .withProjectDir(projectDir) .withArguments("releaseBuild") .withEnvironment(ImmutableMap.of("CI", "true", "TAG_NAME", "RELEASE_SERVER1")) .withPluginClasspath() .build(); assertThat(result.task(":library1:build")).isNull(); assertThat(result.task(":server1:build")).isNotNull(); assertThat(result.task(":server1:jib")).isNotNull(); } @Test void unknownTag() { var result = GradleRunner.create() .withProjectDir(projectDir) .withArguments("releaseBuild") .withEnvironment(ImmutableMap.of("CI", "true", "TAG_NAME", "RELEASE_UNKNOWN1")) .withPluginClasspath() .buildAndFail(); assertThat(result.getOutput()).contains("Task 'releaseBuild' not found in root project"); } } } private static void copyProjectFromResources(String resourcePath, Path projectDir) throws Exception { var resourceDir = Paths.get(Resources.getResource(resourcePath).toURI()); try (var stream = Files.walk(resourceDir)) { stream .filter(path -> !path.equals(resourceDir)) .forEach( path -> { var destPath = projectDir.resolve(resourceDir.relativize(path)); try { if (Files.isDirectory(path)) { Files.createDirectory(destPath); } else { Files.copy(path, destPath); } } catch (IOException e) { throw new UncheckedIOException("Could not copy test project file.", e); } }); } var projectFiles = projectDir.toFile().listFiles(); checkNotNull(projectFiles); for (var file : projectFiles) { if (file.getName().equals("dot-git")) { if (!file.renameTo(new File(file.getParent(), ".git"))) { throw new IllegalStateException("Could not rename dot-git to .git."); } break; } } } }
package org.eclipse.birt.report.designer.ui.views.attributes; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.util.mediator.IColleague; import org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest; import org.eclipse.birt.report.designer.internal.ui.editors.parts.event.IModelEventProcessor; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.DummyEditpart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportElementEditPart; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.internal.ui.views.actions.GlobalActionFactory; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.IReportGraphicConstants; import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages; import org.eclipse.birt.report.designer.ui.ReportPlugin; import org.eclipse.birt.report.designer.ui.views.IPageGenerator; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.GroupElementHandle; import org.eclipse.birt.report.model.api.activity.NotificationEvent; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.INullSelectionListener; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.part.Page; /** * Attribute view shows the attributes of the selected control. If no control is * selected, it will show no attributes and a sentence describing there is * nothing to show for the selected object. * </p> * Multi-selection of control of the same type will normally show the same UI as * if only one control was selected. Some of the values may be gray or blank if * the selected controls have different attributes. If the controls have * different type, nothing will be shown in the attributes view. * </P> */ public class AttributeViewPage extends Page implements INullSelectionListener, IColleague, IModelEventProcessor { /** * WorkbenchPart ID list that attribute view interests in selection changing * occupied in these WorkbenchParts. */ protected List PART_IDS = Arrays.asList( new String[]{ "org.eclipse.birt.report.designer.ui.editors.ReportEditor",//$NON-NLS-1$ "org.eclipse.birt.report.designer.ui.editors.LibraryReportEditor",//$NON-NLS-1$ "org.eclipse.birt.report.designer.ui.editors.TemplateEditor",//$NON-NLS-1$ IPageLayout.ID_OUTLINE, } ); /** * Keeps current selection When AttributeView is not on the top of window. */ private ISelection selection; /** * Attribute view UI builder */ private AttributesBuilder builder; // add restore library properties action private RestoreLibraryPropertiesAction restoreLibraryPropertiesAction; public class RestoreLibraryPropertiesAction extends Action { AttributeViewPage view; RestoreLibraryPropertiesAction( AttributeViewPage view ) { this.view = view; setImageDescriptor( ReportPlatformUIImages.getImageDescriptor( IReportGraphicConstants.ICON_ENABLE_RESTORE_PROPERTIES ) ); setEnabled( false ); setToolTipText( Messages.getString( "AttributeView.toolbar.tooltip.RestoreLibraryPropertiesAction.RestoreMsg" ) ); } public void run( ) { if ( view != null ) { MessageDialog prefDialog = new MessageDialog( UIUtil.getDefaultShell( ), Messages.getString( "AttributeView.dialg.Message.Warning" ),//$NON-NLS-1$ null, Messages.getString( "AttributeView.dialg.Message.PromptMsg" ),//$NON-NLS-1$ MessageDialog.INFORMATION, new String[]{ Messages.getString( "AttributeView.dialg.Message.Yes" ),//$NON-NLS-1$ Messages.getString( "AttributeView.dialg.Message.No" ),//$NON-NLS-1$ Messages.getString( "AttributeView.dialg.Message.Cancel" )}, 0 );//$NON-NLS-1$ int ret = prefDialog.open( ); if ( !( ret == 2 ) ) { if ( ret == Window.OK ) { resetLocalProperties( ret ); pageGenerator = builder.getPageGenerator( getModelList( selection ) ); pageGenerator.createControl( container, getModelList( selection ) ); setEnabled( false ); } } } } } /** * Clear all the local properties * * @param ret */ public void resetLocalProperties( int ret ) { try { DEUtil.getGroupElementHandle( getModelList( new StructuredSelection( SessionHandleAdapter.getInstance( ) .getMediator( ) .getCurrentState( ) .getSelectionObject( ) ) ) ) .clearLocalProperties( ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } return; } /** * Creates the SWT controls for this workbench part. * <p> * Clients should not call this method (the workbench calls this method when * it needs to, which may be never). * </p> * <p> * For implementors this is a multi-step process: * <ol> * <li>Create one or more controls within the parent.</li> * <li>Set the parent layout as needed.</li> * <li>Register any global actions with the <code>IActionService</code>. * </li> * <li>Register any popup menus with the <code>IActionService</code>. * </li> * <li>Register a selection provider with the * <code>ISelectionService</code> (optional).</li> * </ol> * </p> * * @param parent * the parent control */ private Composite container; public void createControl( Composite parent ) { addActions( ); container = new Composite( parent, SWT.NONE ); GridLayout layout = new GridLayout( ); layout.marginWidth = layout.marginHeight = 0; container.setLayout( layout ); builder = new AttributesBuilder( ); IWorkbenchPage page = getSite( ).getPage( ); selection = page.getSelection( ); page.addSelectionListener( this ); SessionHandleAdapter.getInstance( ) .getMediator( ) .addGlobalColleague( this ); } private void addActions( ) { if ( restoreLibraryPropertiesAction == null ) { restoreLibraryPropertiesAction = new RestoreLibraryPropertiesAction( this ); } getSite( ).getActionBars( ) .getToolBarManager( ) .add( restoreLibraryPropertiesAction ); } /** * Asks this part to take focus within the workbench. * <p> * Clients should not call this method (the workbench calls this method at * appropriate times). To have the workbench activate a part, use * <code>IWorkbenchPage.activate(IWorkbenchPart) instead</code>. * </p> */ public void setFocus( ) { handleSelectionChanged( selection ); } private void setPartName( ) { String typeInfo = builder.getTypeInfo( ); IViewPart view = UIUtil.getView( "org.eclipse.birt.report.designer.ui.attributes.AttributeView" ); if ( view != null && typeInfo != null ) ( (AttributeView) view ).setPartName( typeInfo ); } private boolean hasLocalProperties( ISelection selection ) { GroupElementHandle groupHandle = DEUtil.getGroupElementHandle( getModelList( selection ) ); return groupHandle.hasLocalPropertiesForExtendedElements( ); } private boolean hasLocalProperties( List modelList ) { GroupElementHandle groupHandle = DEUtil.getGroupElementHandle( modelList ); return groupHandle.hasLocalPropertiesForExtendedElements( ); } public void resetRestorePropertiesAction( List modelList ) { restoreLibraryPropertiesAction.setEnabled( hasLocalProperties( modelList ) ); } /** * Parse out the DE models for all kinds of input source. * * @param selection * the current selection. * @return */ private List getModelList( ISelection selection ) { List list = new ArrayList( ); if ( selection == null ) return list; if ( !( selection instanceof StructuredSelection ) ) return list; StructuredSelection structured = (StructuredSelection) selection; if ( structured.getFirstElement( ) instanceof ReportElementEditPart ) { boolean bool = false; for ( Iterator it = structured.iterator( ); it.hasNext( ); ) { ReportElementEditPart object = (ReportElementEditPart) it.next( ); if ( object instanceof DummyEditpart ) { list.add( object.getModel( ) ); bool = true; } if ( !bool ) { list.add( object.getModel( ) ); } } } else { list = structured.toList( ); } return list; } /** * Notifies this listener that the selection has changed. * <p> * This method is called when the selection changes from one to a * <code>non-null</code> value, but not when the selection changes to * <code>null</code>. If there is a requirement to be notified in the * latter scenario, implement <code>INullSelectionListener</code>. The * event will be posted through this method. * </p> * * @param part * the workbench part containing the selection * @param selection * the current selection. This may be <code>null</code> if * <code>INullSelectionListener</code> is implemented. */ public void selectionChanged( IWorkbenchPart part, ISelection selection ) { // if ( part != null && !PART_IDS.contains( part.getSite( ).getId( ) ) // && !ID.equals( part.getSite( ).getId( ) ) // && !PaletteView.ID.equals( part.getSite( ).getId( ) ) ) if ( SessionHandleAdapter.getInstance( ).getReportDesignHandle( ) != null ) { if ( part != null && !ReportPlugin.getDefault( ) .containIgnoreViewID( part.getSite( ).getId( ) ) ) { selection = new StructuredSelection( ); handleSelectionChanged( selection ); } } } /** * Disposes of this workbench part. * <p> * This is the last method called on the <code>IWorkbenchPart</code>. At * this point the part controls (if they were ever created) have been * disposed as part of an SWT composite. There is no guarantee that * createPartControl() has been called, so the part controls may never have * been created. * </p> * <p> * Within this method a part may release any resources, fonts, images, * etc.&nbsp; held by this part. It is also very important to deregister all * listeners from the workbench. * </p> * <p> * Clients should not call this method (the workbench calls this method at * appropriate times). * </p> */ public void dispose( ) { deRegisterEventManager( ); IWorkbenchPage page = getSite( ).getPage( ); page.removeSelectionListener( this ); // page.removePartListener( partListener ); // remove the mediator listener SessionHandleAdapter.getInstance( ) .getMediator( ) .removeGlobalColleague( this ); super.dispose( ); } /** * Handles all global actions */ private void handleGlobalAction( ) { for ( int i = 0; i < GlobalActionFactory.GLOBAL_STACK_ACTIONS.length; i++ ) { String id = GlobalActionFactory.GLOBAL_STACK_ACTIONS[i]; getSite( ).getActionBars( ).setGlobalActionHandler( id, GlobalActionFactory.createStackAction( id, SessionHandleAdapter.getInstance( ) .getCommandStack( ) ) ); } getSite( ).getActionBars( ) .setGlobalActionHandler( ActionFactory.SELECT_ALL.getId( ), new SelectAllAction( ) ); } private static class SelectAllAction extends Action { private SelectAllAction( ) { setId( ActionFactory.SELECT_ALL.getId( ) ); } public void runWithEvent( Event event ) { try { execute( ); } catch ( ExecutionException e ) { ExceptionHandler.handle( e ); } } /** * The parameters to pass to the method this handler invokes. This * handler always passes no parameters. */ protected static final Class[] NO_PARAMETERS = new Class[0]; private static final String methodName = "selectAll";//$NON-NLS-1$ public final Object execute( ) throws ExecutionException { final Method methodToExecute = getMethodToExecute( ); if ( methodToExecute != null ) { try { final Control focusControl = Display.getCurrent( ) .getFocusControl( ); // if it's an embedded swing component, fail gracefully for // now. if ( ( focusControl instanceof Composite ) && ( ( ( (Composite) focusControl ).getStyle( ) & SWT.EMBEDDED ) != 0 ) ) { return null; } final int numParams = methodToExecute.getParameterTypes( ).length; if ( numParams == 0 ) { // This is a no-argument selectAll method. methodToExecute.invoke( focusControl, null ); focusControl.notifyListeners( SWT.Selection, null ); } else if ( numParams == 1 ) { // This is a single-point selection method. final Method textLimitAccessor = focusControl.getClass( ) .getMethod( "getTextLimit", NO_PARAMETERS ); //$NON-NLS-1$ final Integer textLimit = (Integer) textLimitAccessor.invoke( focusControl, null ); final Object[] parameters = { new Point( 0, textLimit.intValue( ) ) }; methodToExecute.invoke( focusControl, parameters ); focusControl.notifyListeners( SWT.Selection, null ); } else { /* * This means that getMethodToExecute() has been * changed, while this method hasn't. */ throw new ExecutionException( "Too many parameters on select all", new Exception( ) ); //$NON-NLS-1$ } } catch ( IllegalAccessException e ) { // The method is protected, so do nothing. } catch ( InvocationTargetException e ) { throw new ExecutionException( "An exception occurred while executing " //$NON-NLS-1$ + getMethodToExecute( ), e.getTargetException( ) ); } catch ( NoSuchMethodException e ) { // I can't get the text limit. Do nothing. } } return null; } /** * Looks up the select all method on the given focus control. * * @return The method on the focus control; <code>null</code> if none. */ protected Method getMethodToExecute( ) { final Control focusControl = Display.getCurrent( ) .getFocusControl( ); Method method = null; if ( focusControl != null ) { final Class clazz = focusControl.getClass( ); try { method = clazz.getMethod( methodName, NO_PARAMETERS ); } catch ( NoSuchMethodException e ) { // Fall through... } } if ( ( method == null ) && ( focusControl instanceof Composite ) && ( ( ( (Composite) focusControl ).getStyle( ) & SWT.EMBEDDED ) != 0 ) ) { /* * We couldn't find the appropriate method on the current focus * control. It is possible that the current focus control is an * embedded SWT composite, which could be containing some Swing * components. If this is the case, then we should try to pass * through to the underlying Swing component hierarchy. * Insha'allah, this will work. */ try { final Class focusManagerClass = Class.forName( "javax.swing.FocusManager" ); //$NON-NLS-1$ final Method focusManagerGetCurrentManagerMethod = focusManagerClass.getMethod( "getCurrentManager", null ); //$NON-NLS-1$ final Object focusManager = focusManagerGetCurrentManagerMethod.invoke( focusManagerClass, null ); final Method focusManagerGetFocusOwner = focusManagerClass.getMethod( "getFocusOwner", null ); //$NON-NLS-1$ final Object focusComponent = focusManagerGetFocusOwner.invoke( focusManager, null ); final Class clazz = focusComponent.getClass( ); try { method = clazz.getMethod( methodName, NO_PARAMETERS ); } catch ( NoSuchMethodException e ) { // Do nothing. } } catch ( final ClassNotFoundException e ) { // There is no Swing support, so do nothing. } catch ( final NoSuchMethodException e ) { // The API has changed, which seems amazingly unlikely. throw new Error( "Something is seriously wrong here" ); //$NON-NLS-1$ } catch ( IllegalAccessException e ) { // The API has changed, which seems amazingly unlikely. throw new Error( "Something is seriously wrong here" ); //$NON-NLS-1$ } catch ( InvocationTargetException e ) { // The API has changed, which seems amazingly unlikely. throw new Error( "Something is seriously wrong here" ); //$NON-NLS-1$ } } return method; } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.core.util.mediator.IColleague#performRequest(org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest) */ List requesList = Collections.EMPTY_LIST; private IPageGenerator pageGenerator; public void performRequest( ReportRequest request ) { if ( ReportRequest.SELECTION.equals( request.getType( ) ) ) { if ( !requesList.equals( request.getSelectionModelList( ) ) ) { deRegisterEventManager( ); requesList = request.getSelectionModelList( ); handleSelectionChanged( new StructuredSelection( requesList ) ); registerEventManager( ); } } } /** * Removes model change listener. */ protected void deRegisterEventManager( ) { if ( UIUtil.getModelEventManager( ) != null ) UIUtil.getModelEventManager( ).removeModelEventProcessor( this ); } /** * Registers model change listener to DE elements. */ protected void registerEventManager( ) { if ( UIUtil.getModelEventManager( ) != null ) UIUtil.getModelEventManager( ).addModelEventProcessor( this ); } /** * Notifies this listener that the selection has changed. * <p> * This method is called when the selection changes from one to a * <code>non-null</code> value, but not when the selection changes to * <code>null</code>. If there is a requirement to be notified in the * latter scenario, implement <code>INullSelectionListener</code>. The * event will be posted through this method. * </p> * * @param part * the workbench part containing the selection * @param selection * the current selection. This may be <code>null</code> if * <code>INullSelectionListener</code> is implemented. */ public void handleSelectionChanged( ISelection selection ) { List modelList = getModelList( selection ); if ( modelList == null || modelList.size( ) == 0 ) return; pageGenerator = builder.getPageGenerator( modelList ); if ( container != null && !container.isDisposed( ) ) pageGenerator.createControl( container, modelList ); if ( SessionHandleAdapter.getInstance( ).getReportDesignHandle( ) != null ) { restoreLibraryPropertiesAction.setEnabled( hasLocalProperties( selection ) ); handleGlobalAction( ); setPartName( ); } this.selection = selection; } static class MessagePageGenerator extends TabPageGenerator { public void createTabItems( List input ) { super.createTabItems( input ); Composite pane = new Composite( tabFolder, SWT.NONE ); pane.setLayout( new FillLayout( ) ); new MessageAttributePage( pane, SWT.NONE, input ); CTabItem tabItem = new CTabItem( tabFolder, SWT.NONE ); if ( input.get( 0 ) instanceof ModelClassWrapper ) { tabItem.setText( ( (ModelClassWrapper) input.get( 0 ) ).getTypeMessage( ) ); } tabItem.setControl( pane ); } } static class MessageAttributePage extends Composite { private List model; public MessageAttributePage( Composite parent, int style, List input ) { super( parent, style ); model = input; buildUI( ); } private void buildUI( ) { FillLayout layout = new FillLayout( ); setLayout( layout ); Label label = new Label( this, SWT.LEFT | SWT.TOP | SWT.WRAP ); String extendsString = "";//$NON-NLS-1$ if ( model.get( 0 ) instanceof ModelClassWrapper ) { extendsString = ( (ModelClassWrapper) model.get( 0 ) ).getExtendsString( ); } label.setText( extendsString ); } } static class ModelClassWrapper { private GroupElementHandle groupElementHandle; public ModelClassWrapper( List modelList ) { groupElementHandle = DEUtil.getMultiSelectionHandle( modelList ); } public String getTypeMessage( ) { if ( groupElementHandle.getElements( ).get( 0 ) instanceof DesignElementHandle ) { return DEUtil.getDisplayLabel( ( (DesignElementHandle) groupElementHandle.getElements( ) .get( 0 ) ) ); } return "";//$NON-NLS-1$ } public String getExtendsString( ) { DesignElementHandle handle = (DesignElementHandle) groupElementHandle.getElements( ) .get( 0 ); String name = DEUtil.getDisplayLabel( handle ); String extendsFrom = handle.getExtends( ).getDisplayLabel( ); String libName = handle.getExtends( ).getRoot( ).getDisplayLabel( ); return Messages.getFormattedString( "AttributeView.view.message.Emptypage", new Object[]{name,//$NON-NLS-1$ extendsFrom, libName, name } ); } public Object getElement( ) { if ( groupElementHandle != null ) { return groupElementHandle.getElements( ).get( 0 ); } return new Object( ); } } public Control getControl( ) { return container; } public void addElementEvent( DesignElementHandle focus, NotificationEvent ev ) { } public void clear( ) { } public void postElementEvent( ) { restoreLibraryPropertiesAction.setEnabled( hasLocalProperties( selection ) ); if ( pageGenerator != null && pageGenerator.getControl( ) != null && !pageGenerator.getControl( ).isDisposed( ) ) pageGenerator.refresh( ); } public Object getAdapter( Class adapter ) { return null; } }
package org.ovirt.engine.core.searchbackend; import java.util.Date; import java.util.UUID; import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType; import org.ovirt.engine.core.common.businessentities.ImageStatus; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.compat.StringFormat; import org.ovirt.engine.core.compat.StringHelper; public class DiskConditionFieldAutoCompleter extends BaseConditionFieldAutoCompleter { public DiskConditionFieldAutoCompleter() { // Building the basic verbs set. mVerbs.add("ALIAS"); mVerbs.add("DESCRIPTION"); mVerbs.add("PROVISIONED_SIZE"); mVerbs.add("SIZE"); mVerbs.add("ACTUAL_SIZE"); mVerbs.add("CREATION_DATE"); mVerbs.add("BOOTABLE"); mVerbs.add("SHAREABLE"); mVerbs.add("STATUS"); mVerbs.add("DISK_TYPE"); mVerbs.add("NUMBER_OF_VMS"); mVerbs.add("VM_NAMES"); mVerbs.add("QUOTA"); mVerbs.add("ID"); // Building the autoCompletion dict. buildCompletions(); // Building the types dict. getTypeDictionary().put("ALIAS", String.class); getTypeDictionary().put("DESCRIPTION", String.class); getTypeDictionary().put("PROVISIONED_SIZE", Long.class); getTypeDictionary().put("SIZE", Long.class); getTypeDictionary().put("ACTUAL_SIZE", Long.class); getTypeDictionary().put("CREATION_DATE", Date.class); getTypeDictionary().put("BOOTABLE", Boolean.class); getTypeDictionary().put("SHAREABLE", Boolean.class); getTypeDictionary().put("STATUS", ImageStatus.class); getTypeDictionary().put("DISK_TYPE", DiskStorageType.class); getTypeDictionary().put("NUMBER_OF_VMS", Integer.class); getTypeDictionary().put("VM_NAMES", String.class); getTypeDictionary().put("QUOTA", String.class); getTypeDictionary().put("ID", UUID.class); // building the ColumnName dict. - the name of the column in db columnNameDict.put("ALIAS", "disk_alias"); columnNameDict.put("DESCRIPTION", "disk_description"); columnNameDict.put("PROVISIONED_SIZE", "size"); columnNameDict.put("SIZE", "size"); columnNameDict.put("ACTUAL_SIZE", "actual_size"); columnNameDict.put("CREATION_DATE", "creation_date"); columnNameDict.put("BOOTABLE", "boot"); columnNameDict.put("SHAREABLE", "shareable"); columnNameDict.put("STATUS", "imageStatus"); columnNameDict.put("DISK_TYPE", "disk_storage_type"); columnNameDict.put("NUMBER_OF_VMS", "number_of_vms"); columnNameDict.put("VM_NAMES", "vm_names"); columnNameDict.put("QUOTA", "quota_name"); columnNameDict.put("ID", "disk_id"); // Building the validation dict. buildBasicValidationTable(); } @Override public IAutoCompleter getFieldRelationshipAutoCompleter(String fieldName) { if ("CREATION_DATE".equals(fieldName) || "SIZE".equals(fieldName) || "ACTUAL_SIZE".equals(fieldName) || "PROVISIONED_SIZE".equals(fieldName)) { return BiggerOrSmallerRelationAutoCompleter.INSTANCE; } else if ("NUMBER_OF_VMS".equals(fieldName)) { return NumericConditionRelationAutoCompleter.INSTANCE; } else { return StringConditionRelationAutoCompleter.INSTANCE; } } @Override public IConditionValueAutoCompleter getFieldValueAutoCompleter(String fieldName) { if ("STATUS".equals(fieldName)) { return new EnumValueAutoCompleter(ImageStatus.class); } else if ("DISK_TYPE".equals(fieldName)) { return new EnumValueAutoCompleter(DiskStorageType.class); } else if ("BOOTABLE".equals(fieldName) || "SHAREABLE".equals(fieldName)) { return new BitValueAutoCompleter(); } return null; } @Override public void formatValue(String fieldName, Pair<String, String> pair, boolean caseSensitive) { if ("CREATION_DATE".equals(fieldName)) { Date tmp = new Date(Date.parse(StringHelper.trim(pair.getSecond(), '\''))); pair.setSecond(StringFormat.format("'%1$s'", tmp)); } else { super.formatValue(fieldName, pair, caseSensitive); } } }
package org.eclipse.smarthome.io.voice.internal; import java.io.InputStream; import java.io.IOException; import java.util.Arrays; import ee.ioc.phon.netspeechapi.duplex.RecognitionEvent; import ee.ioc.phon.netspeechapi.duplex.RecognitionEventListener; import ee.ioc.phon.netspeechapi.duplex.WsDuplexRecognitionSession; import org.eclipse.smarthome.io.audio.AudioFormat; import org.eclipse.smarthome.io.audio.AudioSource; import org.eclipse.smarthome.io.audio.AudioException; import org.eclipse.smarthome.io.voice.RecognitionStartEvent; import org.eclipse.smarthome.io.voice.SpeechRecognitionErrorEvent; import org.eclipse.smarthome.io.voice.STTListener; /** * A Runnable that sends AudioSource data in a WsDuplexRecognitionSession * * @author Kelly Davis - Initial contribution and API * */ public class STTServiceKaldiRunnable implements Runnable, RecognitionEventListener { /** * Boolean indicating if the thread is aborting */ private volatile boolean isAborting; /** * The source of audio data */ private final AudioSource audioSource; /** * The STTListener notified of STTEvents */ private final STTListener sttListener; /** * The WsDuplexRecognitionSession communication is over */ private final WsDuplexRecognitionSession recognitionSession; /** * Constructs an instance targeting the passed WsDuplexRecognitionSession * * @param recognitionSession The WsDuplexRecognitionSession sesion * @param sttListener The STTListener targeted for STTEvents * @param audioSource The AudioSource data */ public STTServiceKaldiRunnable(WsDuplexRecognitionSession recognitionSession, STTListener sttListener, AudioSource audioSource) { this.isAborting = false; this.audioSource = audioSource; this.sttListener = sttListener; this.recognitionSession = recognitionSession; this.recognitionSession.addRecognitionEventListener(this); } /** * This method sends AudioSource data in the WsDuplexRecognitionSession */ public void run() { try { this.recognitionSession.connect(); InputStream inputStream = this.audioSource.getInputStream(); AudioFormat audioFormat = this.audioSource.getFormat(); int bitRate = audioFormat.getBitRate().intValue(); int byteRate = (bitRate / 8); int chunkRate = 4; byte buffer[] = new byte[byteRate / chunkRate]; sttListener.sttEventReceived(new RecognitionStartEvent()); boolean sentLastChunk = false; while (!this.isAborting) { long millisWithinChunkSecond = System.currentTimeMillis() % (1000 / chunkRate); int size = inputStream.read(buffer); if (size < 0) { sentLastChunk = true; byte buffer2[] = new byte[0]; this.recognitionSession.sendChunk(buffer2, true); break; } if (size == (byteRate / chunkRate)) { this.recognitionSession.sendChunk(buffer, false); } else { sentLastChunk = true; byte buffer2[] = Arrays.copyOf(buffer, size); this.recognitionSession.sendChunk(buffer2, true); break; } Thread.sleep(1000/chunkRate - millisWithinChunkSecond); } if (this.isAborting && !sentLastChunk) { byte buffer2[] = new byte[0]; this.recognitionSession.sendChunk(buffer2, true); } } catch(AudioException e) { sttListener.sttEventReceived(new SpeechRecognitionErrorEvent("Unable to obtain the audio input stream")); } catch(IOException e) { sttListener.sttEventReceived(new SpeechRecognitionErrorEvent("Unable to send audio data to the server")); } catch(InterruptedException e) { sttListener.sttEventReceived(new SpeechRecognitionErrorEvent("Unable to send data to the server at the proper rate")); } } /** * This method initiates the process of aborting this thread */ public void abort() { this.isAborting = true; } /** * {@inheritDoc} */ public void onRecognitionEvent(RecognitionEvent recognitionEvent) { // RecognitionEvent are ignored } /** * {@inheritDoc} */ public void onClose() { this.abort(); } }
package com.codenvy.ide.ext.datasource.client.sqllauncher; import java.util.Collection; import java.util.List; import com.codenvy.ide.api.editor.EditorPartPresenter; import com.codenvy.ide.api.notification.Notification; import com.codenvy.ide.api.notification.Notification.Type; import com.codenvy.ide.api.notification.NotificationManager; import com.codenvy.ide.api.preferences.PreferencesManager; import com.codenvy.ide.api.ui.workspace.AbstractPartPresenter; import com.codenvy.ide.dto.DtoFactory; import com.codenvy.ide.ext.datasource.client.DatasourceClientService; import com.codenvy.ide.ext.datasource.client.DatasourceManager; import com.codenvy.ide.ext.datasource.client.events.DatasourceCreatedEvent; import com.codenvy.ide.ext.datasource.client.events.DatasourceCreatedHandler; import com.codenvy.ide.ext.datasource.client.sqleditor.SqlEditorProvider; import com.codenvy.ide.ext.datasource.shared.DatabaseConfigurationDTO; import com.codenvy.ide.ext.datasource.shared.request.RequestResultDTO; import com.codenvy.ide.ext.datasource.shared.request.RequestResultGroupDTO; import com.codenvy.ide.ext.datasource.shared.request.SelectResultDTO; import com.codenvy.ide.ext.datasource.shared.request.UpdateResultDTO; import com.codenvy.ide.resources.marshal.StringUnmarshaller; import com.codenvy.ide.rest.AsyncRequestCallback; import com.codenvy.ide.util.loging.Log; import com.google.gwt.http.client.RequestException; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.gwt.user.client.ui.TextArea; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; public class SqlRequestLauncherPresenter extends AbstractPartPresenter implements SqlRequestLauncherView.ActionDelegate, DatasourceCreatedHandler { /** Preference property name for default result limit. */ private static final String PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT = "SqlEditor_default_request_limit"; /** Default value for request limit (when no pref is set). */ private static final int DEFAULT_REQUEST_LIMIT = 20; /** The matching view. */ private final SqlRequestLauncherView view; /** The i18n-able constants. */ private final SqlRequestLauncherConstants constants; /** The DTO factory. */ private final DtoFactory dtoFactory; private String selectedDatasourceId = null; private int resultLimit = DEFAULT_REQUEST_LIMIT; private EditorPartPresenter editor; private DatasourceClientService datasourceClientService; private NotificationManager notificationManager; private DatasourceManager datasourceManager; private TextArea editorArea; private TextArea resultArea; @Inject public SqlRequestLauncherPresenter(final SqlRequestLauncherView view, final SqlRequestLauncherConstants constants, final PreferencesManager preferencesManager, final SqlEditorProvider sqlEditorProvider, final DatasourceClientService service, final NotificationManager notificationManager, final DatasourceManager datasourceManager, final EventBus eventBus, final DtoFactory dtoFactory) { this.view = view; this.view.setDelegate(this); this.constants = constants; this.dtoFactory = dtoFactory; this.editor = sqlEditorProvider.getEditor(); this.datasourceClientService = service; this.notificationManager = notificationManager; this.datasourceManager = datasourceManager; final String prefRequestLimit = preferencesManager.getValue(PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT); if (prefRequestLimit != null) { try { int prefValue = Integer.valueOf(prefRequestLimit); if (prefValue > 0) { this.resultLimit = prefValue; } else { Log.warn(SqlRequestLauncherPresenter.class, "negative value stored in preference " + PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT); } } catch (final NumberFormatException e) { StringBuilder sb = new StringBuilder("Preference stored in ") .append(PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT) .append(" is not an integer (") .append(resultLimit) .append(")."); Log.warn(SqlRequestLauncherPresenter.class, sb.toString()); } } // push the request limit value to the view this.view.setResultLimit(this.resultLimit); // register for datasource creation events eventBus.addHandler(DatasourceCreatedEvent.getType(), this); // temporary editorArea = new SqlLauncherTextArea(false); resultArea = new SqlLauncherTextArea(true); } private void setupDatasourceComponent() { Collection<String> datasourceIds = this.datasourceManager.getNames(); this.view.setDatasourceList(datasourceIds); } @Override public String getTitle() { return this.constants.sqlEditorWindowTitle(); } @Override public ImageResource getTitleImage() { return null; } @Override public String getTitleToolTip() { return null; } @Override public void go(final AcceptsOneWidget container) { container.setWidget(view); // editor.go(this.view.getEditorZone()); this.view.getEditorZone().setWidget(editorArea); this.view.getResultZone().setWidget(resultArea); setupDatasourceComponent(); } @Override public boolean onClose() { return this.editor.onClose(); } @Override public void onOpen() { this.editor.onOpen(); } @Override public void datasourceChanged(final String newDataSourceId) { Log.info(SqlRequestLauncherPresenter.class, "Datasource changed to " + newDataSourceId); this.selectedDatasourceId = newDataSourceId; } @Override public void resultLimitChanged(final String newResultLimitString) { Log.info(SqlRequestLauncherPresenter.class, "Attempt to change result limit to " + newResultLimitString); int resultLimitValue; try { resultLimitValue = Integer.parseInt(newResultLimitString); if (resultLimit < 0) { Log.debug(SqlRequestLauncherPresenter.class, " new value for result limit is negative - abort change"); this.view.setResultLimit(this.resultLimit); } else { Log.debug(SqlRequestLauncherPresenter.class, " valid value for result limit - changed"); this.resultLimit = resultLimitValue; } } catch (NumberFormatException e) { Log.debug(SqlRequestLauncherPresenter.class, " new value for result limit is not a number - abort change"); this.view.setResultLimit(this.resultLimit); } } private String getSqlRequestInput() { final String selectedText = this.editorArea.getSelectedText(); if ("".equals(selectedText)) { return this.editorArea.getText(); } else { return selectedText; } } @Override public void executeRequested(final String request) { Log.info(SqlRequestLauncherPresenter.class, "Execution requested."); if (this.selectedDatasourceId == null) { Window.alert("No datasource selected"); return; } DatabaseConfigurationDTO databaseConf = this.datasourceManager.getByName(this.selectedDatasourceId); String rawSql = getSqlRequestInput(); if (rawSql != null) { rawSql = rawSql.trim(); if (!"".equals(rawSql)) { try { final Notification requestNotification = new Notification("Executing SQL request...", Notification.Status.PROGRESS); AsyncRequestCallback<String> callback = new AsyncRequestCallback<String>(new StringUnmarshaller()) { @Override protected void onSuccess(final String result) { Log.info(SqlRequestLauncherPresenter.class, "SQL request result received."); requestNotification.setMessage("SQL request execution completed"); requestNotification.setStatus(Notification.Status.FINISHED); final RequestResultGroupDTO resultDto = dtoFactory.createDtoFromJson(result, RequestResultGroupDTO.class); Log.info(SqlRequestLauncherPresenter.class, "JSON->dto conversion OK - result :" + resultDto); updateResultDisplay(resultDto); } @Override protected void onFailure(final Throwable exception) { Log.info(SqlRequestLauncherPresenter.class, "SQL request failure."); requestNotification.setStatus(Notification.Status.FINISHED); notificationManager.showNotification(new Notification("SQL request failed", Type.ERROR)); updateResultDisplay(exception.getMessage()); } }; notificationManager.showNotification(requestNotification); datasourceClientService.executeSqlRequest(databaseConf, this.resultLimit, rawSql, callback); } catch (final RequestException e) { Log.error(SqlRequestLauncherPresenter.class, "Exception on SQL request execution : " + e.getMessage()); notificationManager.showNotification(new Notification("Failed execution of SQL request", Type.ERROR)); } } } else { Window.alert("No SQL request"); } } protected void updateResultDisplay(String message) { Log.info(SqlRequestLauncherPresenter.class, "Printing request error message."); this.resultArea.setText(message); } protected void updateResultDisplay(final RequestResultGroupDTO resultDto) { Log.info(SqlRequestLauncherPresenter.class, "Printing request results. (" + resultDto.getResults().size() + " individual results)."); this.resultArea.setText(""); // TODO should probably use a cellwidget at some point StringBuilder sb = new StringBuilder(); for (final RequestResultDTO result : resultDto.getResults()) { switch (result.getResultType()) { case UpdateResultDTO.TYPE: Log.info(SqlRequestLauncherPresenter.class, "Found one result of type 'update'."); appendUpdateResult(sb, result); break; case SelectResultDTO.TYPE: Log.info(SqlRequestLauncherPresenter.class, "Found one result of type 'select'."); appendSelectResult(sb, result); break; default: Log.error(SqlRequestLauncherPresenter.class, "unknown result type : " + result.getResultType()); sb.append("Result can't be displayed"); } sb.append("\n\n"); } Log.info(SqlRequestLauncherPresenter.class, "All individual results are processed."); this.resultArea.setText(sb.toString()); } private void appendSelectResult(final StringBuilder sb, final RequestResultDTO result) { // append header StringBuilder headerBuilder = new StringBuilder(); for (String cell : result.getHeaderLine()) { headerBuilder.append(formatCell(cell)); headerBuilder.append(" "); } String header = headerBuilder.toString(); sb.append(header) .append("\n"); // separator for (int i = 0; i < header.length(); i++) { sb.append("-"); } sb.append("\n"); // actual data for (List<String> line : result.getResultLines()) { for (String cell : line) { sb.append(formatCell(cell)) .append(" "); } sb.append("\n"); } } private void appendUpdateResult(final StringBuilder sb, final RequestResultDTO result) { sb.append(this.constants.updateCountMessage(result.getUpdateCount())); } private String formatCell(final String cell) { if (cell.length() > 12) { String cut = cell.substring(0, 10); return cut + ".."; } else { String padding = ""; switch (cell.length()) { case 0: padding = " "; break; case 1: padding = " "; break; case 2: padding = " "; break; case 3: padding = " "; break; case 4: padding = " "; break; case 5: padding = " "; break; case 6: padding = " "; break; case 7: padding = " "; break; case 8: padding = " "; break; case 9: padding = " "; break; case 10: padding = " "; break; case 11: padding = " "; break; default: break; } return cell + padding; } } @Override public void onDatasourceCreated(DatasourceCreatedEvent event) { this.setupDatasourceComponent(); } @Override public void minimize() { // nothing to do } }
package org.jtalks.jcommune.web.validation.validators; import javax.validation.ConstraintValidatorContext; import org.jtalks.jcommune.model.entity.JCUser; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * * @author Anuar_Nurmakanov * */ public class PageSizeValidatorTest { @Mock private ConstraintValidatorContext validatorContext; private PageSizeValidator pageSizeValidator; @BeforeTest public void init() { MockitoAnnotations.initMocks(this); this.pageSizeValidator = new PageSizeValidator(); } @Test(dataProvider = "validPageSizes") public void testIsValidWithAvailablePageSize(int availablePageSize) { boolean isValid = pageSizeValidator.isValid(availablePageSize, validatorContext); Assert.assertTrue(isValid, "Value from the list of available sizes must be valid."); } @DataProvider(name = "validPageSizes") public Object[][] getValidPageSizes() { int rowSize = 1; Object[][] validPageSizes = new Object[JCUser.PAGE_SIZES_AVAILABLE.length][rowSize]; for (int i = 0; i < JCUser.PAGE_SIZES_AVAILABLE.length; i++) { validPageSizes[i][rowSize - 1] = JCUser.PAGE_SIZES_AVAILABLE[i]; } return validPageSizes; } @Test public void testIsValidWithPageSizeAsNull() { boolean isValid = pageSizeValidator.isValid(null, validatorContext); Assert.assertFalse(isValid, "Null must be invalid value."); } @Test(dataProvider = "boundaryValues") public void testIsValidWithBoundaryValue(int boundaryValue) { boolean isValid = pageSizeValidator.isValid(null, validatorContext); Assert.assertFalse(isValid, "Max possible integer and min possible integer must be invalid values."); } @DataProvider(name = "boundaryValues") public Object[][] getBoundaryValues() { return new Object[][] { {Integer.MAX_VALUE}, {Integer.MIN_VALUE} }; } @Test public void testIsValidWithNotAvailablePageSize() { int notAvailablePageSize = 379; boolean isValid = pageSizeValidator.isValid(notAvailablePageSize, validatorContext); Assert.assertFalse(isValid, "This value isn't available, so it must be invalid. Passed value - " + notAvailablePageSize); } }
package org.safehaus.subutai.core.peer.impl; import java.io.File; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.SQLException; import java.util.Enumeration; import java.util.List; import java.util.Set; import java.util.UUID; import javax.persistence.EntityManagerFactory; import org.safehaus.subutai.common.dao.DaoManager; import org.safehaus.subutai.common.peer.Peer; import org.safehaus.subutai.common.peer.PeerException; import org.safehaus.subutai.common.peer.PeerInfo; import org.safehaus.subutai.common.peer.PeerPolicy; import org.safehaus.subutai.common.settings.Common; import org.safehaus.subutai.core.executor.api.CommandExecutor; import org.safehaus.subutai.core.hostregistry.api.HostRegistry; import org.safehaus.subutai.core.identity.api.IdentityManager; import org.safehaus.subutai.core.key.api.KeyInfo; import org.safehaus.subutai.core.key.api.KeyManager; import org.safehaus.subutai.core.key.api.KeyManagerException; import org.safehaus.subutai.core.lxc.quota.api.QuotaManager; import org.safehaus.subutai.core.messenger.api.Messenger; import org.safehaus.subutai.core.metric.api.Monitor; import org.safehaus.subutai.core.peer.api.EnvironmentContext; import org.safehaus.subutai.core.peer.api.HostNotFoundException; import org.safehaus.subutai.core.peer.api.LocalPeer; import org.safehaus.subutai.core.peer.api.ManagementHost; import org.safehaus.subutai.core.peer.api.PeerManager; import org.safehaus.subutai.core.peer.api.RequestListener; import org.safehaus.subutai.core.peer.impl.command.CommandRequestListener; import org.safehaus.subutai.core.peer.impl.command.CommandResponseListener; import org.safehaus.subutai.core.peer.impl.container.CreateContainerGroupRequestListener; import org.safehaus.subutai.core.peer.impl.container.DestroyEnvironmentContainersRequestListener; import org.safehaus.subutai.core.peer.impl.dao.PeerDAO; import org.safehaus.subutai.core.peer.impl.entity.ManagementHostEntity; import org.safehaus.subutai.core.peer.impl.request.MessageRequestListener; import org.safehaus.subutai.core.peer.impl.request.MessageResponseListener; import org.safehaus.subutai.core.registry.api.TemplateRegistry; import org.safehaus.subutai.core.ssl.manager.api.CustomSslContextFactory; import org.safehaus.subutai.core.strategy.api.StrategyManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.io.FileUtils; import com.google.common.collect.Lists; import com.google.common.collect.Sets; /** * PeerManager implementation */ public class PeerManagerImpl implements PeerManager { private static final Logger LOG = LoggerFactory.getLogger( PeerManagerImpl.class.getName() ); private static final String SOURCE_REMOTE_PEER = "PEER_REMOTE"; private static final String SOURCE_LOCAL_PEER = "PEER_LOCAL"; private static final String PEER_ID_PATH = "/var/lib/subutai/id"; private static final String PEER_ID_FILE = "peer_id"; private PeerDAO peerDAO; private QuotaManager quotaManager; private Monitor monitor; private TemplateRegistry templateRegistry; private CommandExecutor commandExecutor; private LocalPeerImpl localPeer; private StrategyManager strategyManager; private PeerInfo peerInfo; private Messenger messenger; private CommandResponseListener commandResponseListener; private Set<RequestListener> requestListeners = Sets.newHashSet(); private MessageResponseListener messageResponseListener; private HostRegistry hostRegistry; private DaoManager daoManager; private KeyManager keyManager; private IdentityManager identityManager; private CustomSslContextFactory sslContextFactory; public void setSslContextFactory( final CustomSslContextFactory sslContextFactory ) { this.sslContextFactory = sslContextFactory; } public PeerManagerImpl( final Messenger messenger ) { this.messenger = messenger; } public void setHostRegistry( final HostRegistry hostRegistry ) { this.hostRegistry = hostRegistry; } public DaoManager getDaoManager() { return daoManager; } public void setDaoManager( final DaoManager daoManager ) { this.daoManager = daoManager; } public void setKeyManager( final KeyManager keyManager ) { this.keyManager = keyManager; } public void setIdentityManager( final IdentityManager identityManager ) { this.identityManager = identityManager; } @Override public EnvironmentContext prepareEnvironment( final UUID environmentId, String email ) { EnvironmentContext environmentContext = new EnvironmentContext(); try { ManagementHost managementHost = localPeer.getManagementHost(); KeyInfo keyInfo = keyManager.generateKey( managementHost, environmentId.toString(), email ); keyInfo.getPublicKeyId(); String gpgPublicKey = keyManager.readKey( managementHost, keyInfo.getPublicKeyId() ); } catch ( KeyManagerException | HostNotFoundException e ) { LOG.error( e.toString(), e ); } return null; } @Override public EntityManagerFactory getEntityManagerFactory() { return daoManager.getEntityManagerFactory(); } public void init() { try { this.peerDAO = new PeerDAO( daoManager ); } catch ( SQLException e ) { LOG.error( e.getMessage(), e ); } List<PeerInfo> result = peerDAO.getInfo( SOURCE_LOCAL_PEER, PeerInfo.class ); if ( result.isEmpty() ) { //obtain id from fs File scriptsDirectory = new File( PEER_ID_PATH ); scriptsDirectory.mkdirs(); Path peerIdFilePath = Paths.get( PEER_ID_PATH, PEER_ID_FILE ); File peerIdFile = peerIdFilePath.toFile(); UUID peerId; try { if ( !peerIdFile.exists() ) { //generate new id and save to fs peerId = UUID.randomUUID(); FileUtils.writeStringToFile( peerIdFile, peerId.toString() ); } else { //read id from file peerId = UUID.fromString( FileUtils.readFileToString( peerIdFile ) ); } } catch ( Exception e ) { throw new PeerInitializationError( "Failed to obtain peer id file", e ); } peerInfo = new PeerInfo(); peerInfo.setId( peerId ); peerInfo.setName( "Local Subutai server" ); //TODO get ownerId from persistent storage peerInfo.setOwnerId( UUID.randomUUID() ); try { Enumeration<InetAddress> addressEnumeration = NetworkInterface.getByName( Common.MANAGEMENT_HOST_EXTERNAL_IP_INTERFACE ).getInetAddresses(); while ( addressEnumeration.hasMoreElements() ) { InetAddress address = addressEnumeration.nextElement(); if ( ( address instanceof Inet4Address ) ) { peerInfo.setIp( address.getHostAddress() ); } } } catch ( SocketException e ) { LOG.error( "Error getting network interfaces", e ); } peerInfo.setName( String.format( "Peer on %s", peerInfo.getIp() ) ); peerDAO.saveInfo( SOURCE_LOCAL_PEER, peerInfo.getId().toString(), peerInfo ); } else { peerInfo = result.get( 0 ); } localPeer = new LocalPeerImpl( this, templateRegistry, quotaManager, strategyManager, requestListeners, commandExecutor, hostRegistry, monitor, identityManager ); localPeer.setSslContextFactory( sslContextFactory ); localPeer.init(); //add command request listener addRequestListener( new CommandRequestListener( localPeer, this ) ); //add command response listener commandResponseListener = new CommandResponseListener(); addRequestListener( commandResponseListener ); //subscribe to peer message requests messenger.addMessageListener( new MessageRequestListener( this, messenger, requestListeners ) ); //subscribe to peer message responses messageResponseListener = new MessageResponseListener( messenger ); messenger.addMessageListener( messageResponseListener ); //add create container requests listener addRequestListener( new CreateContainerGroupRequestListener( localPeer ) ); //add destroy environment containers requests listener addRequestListener( new DestroyEnvironmentContainersRequestListener( localPeer ) ); //add echo listener addRequestListener( new EchoRequestListener() ); } public void destroy() { localPeer.shutdown(); } public void setCommandExecutor( final CommandExecutor commandExecutor ) { this.commandExecutor = commandExecutor; } public void setStrategyManager( final StrategyManager strategyManager ) { this.strategyManager = strategyManager; } public void setTemplateRegistry( final TemplateRegistry templateRegistry ) { this.templateRegistry = templateRegistry; } public void setQuotaManager( final QuotaManager quotaManager ) { this.quotaManager = quotaManager; } public void setMonitor( final Monitor monitor ) { this.monitor = monitor; } @Override public boolean trustRequest( final UUID peerId, final String root_server_px1 ) throws PeerException { return false; } @Override public boolean trustResponse( final UUID peerId, final String root_server_px1, final short status ) throws PeerException { return false; } @Override public boolean register( final PeerInfo peerInfo ) throws PeerException { ManagementHost managementHost = getLocalPeer().getManagementHost(); managementHost.addAptSource( peerInfo.getId().toString(), peerInfo.getIp() ); return peerDAO.saveInfo( SOURCE_REMOTE_PEER, peerInfo.getId().toString(), peerInfo ); } @Override public boolean unregister( final String uuid ) throws PeerException { ManagementHost mgmHost = getLocalPeer().getManagementHost(); if ( !( mgmHost instanceof ManagementHostEntity ) ) { return false; } ManagementHostEntity managementHost = ( ManagementHostEntity ) mgmHost; UUID remotePeerId = UUID.fromString( uuid ); PeerInfo p = getPeerInfo( remotePeerId ); managementHost.removeAptSource( p.getId().toString(), p.getIp() ); managementHost.removeTunnel( p.getIp() ); PeerPolicy peerPolicy = localPeer.getPeerInfo().getPeerPolicy( remotePeerId ); // Remove peer policy of the target remote peer from the local peer if ( peerPolicy != null ) { localPeer.getPeerInfo().getPeerPolicies().remove( peerPolicy ); peerDAO.saveInfo( SOURCE_LOCAL_PEER, localPeer.getId().toString(), localPeer ); } return peerDAO.deleteInfo( SOURCE_REMOTE_PEER, uuid ); } @Override public boolean update( final PeerInfo peerInfo ) { String source; if ( peerInfo.getId().compareTo( localPeer.getId() ) == 0 ) { source = SOURCE_LOCAL_PEER; } else { source = SOURCE_REMOTE_PEER; } return peerDAO.saveInfo( source, peerInfo.getId().toString(), peerInfo ); } @Override public List<PeerInfo> peers() { return peerDAO.getInfo( SOURCE_REMOTE_PEER, PeerInfo.class ); } @Override public List<Peer> getPeers() { List<PeerInfo> peerInfoList = peerDAO.getInfo( SOURCE_REMOTE_PEER, PeerInfo.class ); List<Peer> result = Lists.newArrayList(); result.add( getLocalPeer() ); for ( PeerInfo info : peerInfoList ) { result.add( getPeer( info.getId() ) ); } return result; } @Override public PeerInfo getPeerInfo( UUID uuid ) { String source; if ( uuid.compareTo( localPeer.getId() ) == 0 ) { source = SOURCE_LOCAL_PEER; } else { source = SOURCE_REMOTE_PEER; } return peerDAO.getInfo( source, uuid.toString(), PeerInfo.class ); } @Override public Peer getPeer( final UUID peerId ) { if ( peerInfo.getId().equals( peerId ) ) { return localPeer; } PeerInfo pi = getPeerInfo( peerId ); if ( pi != null ) { return new RemotePeerImpl( localPeer, pi, messenger, commandResponseListener, messageResponseListener ); } return null; } @Override public Peer getPeer( final String peerId ) { return getPeer( UUID.fromString( peerId ) ); } @Override public LocalPeer getLocalPeer() { return localPeer; } @Override public PeerInfo getLocalPeerInfo() { return peerInfo; } @Override public void addRequestListener( RequestListener listener ) { if ( listener != null ) { requestListeners.add( listener ); } } @Override public void removeRequestListener( RequestListener listener ) { if ( listener != null ) { requestListeners.add( listener ); } } }
package net.beaconcontroller.routing.apsp; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.beaconcontroller.core.IBeaconProvider; import net.beaconcontroller.core.IOFSwitch; import net.beaconcontroller.routing.IRoutingEngine; import net.beaconcontroller.routing.Link; import net.beaconcontroller.routing.Route; import net.beaconcontroller.routing.RouteId; import net.beaconcontroller.topology.TopologyAware; /** * Implementation of the APSP algorithm by Demetrescu and Italiano. * * @author David Erickson (derickso@stanford.edu) */ public class AllPairsShortestPathRoutingEngineImpl implements IRoutingEngine, TopologyAware { protected static Logger log = LoggerFactory.getLogger(AllPairsShortestPathRoutingEngineImpl.class); public IBeaconProvider beaconProvider; protected Map<RouteId, Route> shortest; protected Map<RouteId, List<Route>> localRoutes; protected Map<Route, List<Route>> leftLocal; protected Map<Route, List<Route>> leftShortest; protected Map<Route, List<Route>> rightLocal; protected Map<Route, List<Route>> rightShortest; protected ReentrantReadWriteLock lock; public AllPairsShortestPathRoutingEngineImpl() { shortest = new HashMap<RouteId, Route>(); localRoutes = new HashMap<RouteId, List<Route>>(); leftLocal = new HashMap<Route, List<Route>>(); leftShortest = new HashMap<Route, List<Route>>(); rightLocal = new HashMap<Route, List<Route>>(); rightShortest = new HashMap<Route, List<Route>>(); lock = new ReentrantReadWriteLock(); } public void startUp() { } public void shutDown() { } @Override public void linkAdded(IOFSwitch srcSwitch, short srcPort, IOFSwitch dstSwitch, short dstPort) { update(srcSwitch.getId(), srcPort, dstSwitch.getId(), dstPort, true); } @Override public void linkRemoved(IOFSwitch srcSwitch, short srcPort, IOFSwitch dstSwitch, short dstPort) { update(srcSwitch.getId(), srcPort, dstSwitch.getId(), dstPort, false); } @Override public Route getRoute(IOFSwitch src, IOFSwitch dst) { lock.readLock().lock(); Route result = shortest.get(new RouteId(src.getId(), dst.getId())); lock.readLock().unlock(); return result; } @Override public Route getRoute(Long srcDpid, Long dstDpid) { lock.readLock().lock(); Route result = shortest.get(new RouteId(srcDpid, dstDpid)); lock.readLock().unlock(); return result; } @Override public void update(Long srcId, Short srcPort, Long dstId, Short dstPort, boolean added) { Route route = new Route(srcId, dstId); route.getPath().add(new Link(srcPort, dstPort, dstId)); lock.writeLock().lock(); cleanup(route, added); fixup(route, added); lock.writeLock().unlock(); log.debug("Route {} added: {}", route, added); } @Override public void update(Long srcId, Integer srcPort, Long dstId, Integer dstPort, boolean added) { update(srcId, srcPort.shortValue(), dstId, dstPort.shortValue(), added); } protected void cleanup(Route route, boolean added) { Queue<Route> toClean = new LinkedList<Route>(); toClean.add(route); while (toClean.size() > 0) { Route r = toClean.remove(); Route leftsubPath = subPath(r, true); Route rightsubPath = subPath(r, false); removeFromLocal(r); remove(leftLocal, r, rightsubPath); remove(rightLocal, r, leftsubPath); if (r.equals(shortest.get(r.getId()))) { shortest.remove(r.getId()); remove(leftShortest, r, rightsubPath); remove(rightShortest, r, leftsubPath); } if (leftLocal.containsKey(r)) toClean.addAll(leftLocal.get(r)); if (rightLocal.containsKey(r)) toClean.addAll(rightLocal.get(r)); } } protected void fixup(Route route, boolean added) { // Phase 1 if (added) { addLocal(route); add(leftLocal, route, subPath(route, false)); add(rightLocal, route, subPath(route, true)); } // Phase 2 Queue<Route> h = new PriorityQueue<Route>(10, new Comparator<Route>() { @Override public int compare(Route r1, Route r2) { return ((Integer)r1.getPath().size()).compareTo(r2.getPath().size()); } }); for (Map.Entry<RouteId, List<Route>> entry : localRoutes.entrySet()) { h.add(entry.getValue().get(0)); } // Phase 3 while (!h.isEmpty()) { Route r = h.remove(); if (shortest.containsKey(r.getId())) { if (r.compareTo(shortest.get(r.getId())) >= 0) continue; } else if (r.getId().getSrc().equals(r.getId().getDst())) { continue; } Route leftSubPath = subPath(r, true); Route rightSubPath = subPath(r, false); addShortest(r); add(leftShortest, r, rightSubPath); add(rightShortest, r, leftSubPath); addNewLocalRoutes(r, leftSubPath, rightSubPath, h); } } protected void addNewLocalRoutes(Route route, Route leftSubPath, Route rightSubPath, Queue<Route> h) { if (leftShortest.containsKey(leftSubPath)) for (Route r : leftShortest.get(leftSubPath)) { Route newLocal = null; try { newLocal = (Route) route.clone(); } catch (CloneNotSupportedException e) { } newLocal.getPath().add(0, r.getPath().get(0)); newLocal.getId().setSrc(r.getId().getSrc()); addLocal(newLocal); add(leftLocal, newLocal, route); add(rightLocal, newLocal, r); h.add(newLocal); } if (rightShortest.containsKey(rightSubPath)) for (Route r : rightShortest.get(rightSubPath)) { Route newLocal = null; try { newLocal = (Route) route.clone(); } catch (CloneNotSupportedException e) { } newLocal.getPath().add(r.getPath().get(r.getPath().size()-1)); newLocal.getId().setDst(r.getId().getDst()); addLocal(newLocal); add(leftLocal, newLocal, r); add(rightLocal, newLocal, route); h.add(newLocal); } } protected void addLocal(Route route) { if (!localRoutes.containsKey(route.getId())) { localRoutes.put(route.getId(), new ArrayList<Route>()); localRoutes.get(route.getId()).add(route); } else { List<Route> routes = localRoutes.get(route.getId()); for (int i = 0; i < routes.size(); ++i) { if (route.compareTo(routes.get(i)) < 0) { routes.add(i, route); return; } } } } protected void addShortest(Route route) { shortest.put(route.getId(), route); } protected void add(Map<Route, List<Route>> routeMap, Route route, Route subPath) { if (!routeMap.containsKey(subPath)) routeMap.put(subPath, new ArrayList<Route>()); routeMap.get(subPath).add(route); } protected boolean removeFromLocal(Route route) { List<Route> routes = this.localRoutes.get(route.getId()); if (routes != null) { if (routes.remove(route)) { if (routes.isEmpty()) { this.localRoutes.remove(route.getId()); } return true; } } return false; } protected boolean removeFromShortest(Route route) { if (this.shortest.containsKey(route.getId()) && this.shortest.get(route.getId()).equals(route)) { this.shortest.remove(route.getId()); return true; } return false; } /** * Removes the given route from the list in routeMap indexed by subPath, * if it exists. Returns true if it was removed, false otherwise. * @param routeMap * @param route * @param subPath * @return */ protected boolean remove(Map<Route, List<Route>> routeMap, Route route, Route subPath) { List<Route> routes = routeMap.get(subPath); if (routes != null) { if (routes.remove(route)) { if (routes.isEmpty()) routeMap.remove(subPath); return true; } } return false; } /** * Returns the subPath of the given route, namely l(route) or r(route) as * given in the algorithm. The returned Route is a clone of the supplied * Route and safe for modification. * @param route * @param isLeft * @return */ protected Route subPath(Route route, boolean isLeft) { Route clone = null; try { clone = (Route) route.clone(); } catch (CloneNotSupportedException e) { // this will never happen } List<Link> path = clone.getPath(); if (isLeft) { if (path.size() > 0) path.remove(path.size()-1); if (path.isEmpty()) clone.getId().setDst(clone.getId().getSrc()); } else { if (path.size() > 0) path.remove(0); if (path.isEmpty()) clone.getId().setSrc(clone.getId().getDst()); } return clone; } /** * @param beaconProvider the beaconProvider to set */ public void setBeaconProvider(IBeaconProvider beaconProvider) { this.beaconProvider = beaconProvider; } }
package com.camunda.fox.platform.tasklist.identity.impl; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import org.activiti.engine.IdentityService; import org.activiti.engine.identity.Group; import com.camunda.fox.platform.tasklist.identity.FoxIdentityService; import com.camunda.fox.platform.tasklist.identity.User; @Named @ApplicationScoped public class ActivitiIdentityServiceImpl implements FoxIdentityService, Serializable { private static final long serialVersionUID = 1L; @Inject private IdentityService identityService; @Override public void authenticateUser(String userId, String password) { // always authenticate } @Override public List<String> getGroupsByUserId(String userId) { List<String> groupIds = new ArrayList<String>(); List<Group> groups = identityService.createGroupQuery().groupMember(userId).list(); for (Group group : groups) { groupIds.add(group.getId()); } return groupIds; } @Override public List<User> getColleaguesByUserId(String userId) { User kermit = new User("kermit", "Kermit", "The Frog"); User gonzo = new User("gonzo", "Gonzo", "The Great"); User fozzie = new User("fozzie", "Fozzie", "Bear"); if (userId.equals("kermit")) { return Arrays.asList(new User[] { gonzo, fozzie }); } else if (userId.equals("gonzo")) { return Arrays.asList(new User[] { kermit, fozzie }); } else if (userId.equals("fozzie")) { return Arrays.asList(new User[] { gonzo, kermit }); } else { return new ArrayList<User>(); } } }
package org.bitrepository.integrityservice.workflow.step; import org.bitrepository.common.utils.SettingsUtils; import org.bitrepository.integrityservice.cache.IntegrityModel; import org.bitrepository.integrityservice.cache.PillarCollectionMetric; import org.bitrepository.integrityservice.statistics.StatisticsCollector; import org.bitrepository.service.workflow.AbstractWorkFlowStep; import java.util.List; import java.util.Map; /** * A workflow step for creating pillar statistics. */ public class CreateStatisticsEntryStep extends AbstractWorkFlowStep { private final IntegrityModel store; private final String collectionID; private final StatisticsCollector sc; public CreateStatisticsEntryStep(IntegrityModel store, String collectionID, StatisticsCollector statisticsCollector) { this.store = store; this.collectionID = collectionID; this.sc = statisticsCollector; } @Override public String getName() { return "Create statistics"; } /** * Collects pillar metrics for the given collection and creates from them a statistics entry in the store. */ @Override public synchronized void performStep() { List<String> pillars = SettingsUtils.getPillarIDsForCollection(collectionID); Map<String, PillarCollectionMetric> pillarMetrics = store.getPillarCollectionMetrics(collectionID); for (String pillar : pillars) { PillarCollectionMetric metric = pillarMetrics.get(pillar); if (metric == null) { sc.getPillarCollectionStat(pillar).setFileCount(0L); sc.getPillarCollectionStat(pillar).setDataSize(0L); sc.getPillarCollectionStat(pillar).setOldestChecksumTimestamp(null); } else { sc.getPillarCollectionStat(pillar).setFileCount(metric.getPillarFileCount()); sc.getPillarCollectionStat(pillar).setDataSize(metric.getPillarCollectionSize()); sc.getPillarCollectionStat(pillar).setOldestChecksumTimestamp(metric.getOldestChecksumTimestamp()); } } sc.getCollectionStat().setFileCount(store.getNumberOfFilesInCollection(collectionID)); sc.getCollectionStat().setDataSize(store.getCollectionFileSize(collectionID)); sc.getCollectionStat().setLatestFileTime(store.getDateForNewestFileEntryForCollection(collectionID)); store.createStatistics(collectionID, sc); } public static String getDescription() { return "Creates a new statistics entry in the database."; } }
package org.wso2.carbon.identity.recovery.store; import org.apache.commons.lang.StringUtils; import org.wso2.carbon.identity.application.common.model.User; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.recovery.IdentityRecoveryConstants; import org.wso2.carbon.identity.recovery.IdentityRecoveryException; import org.wso2.carbon.identity.recovery.RecoveryScenarios; import org.wso2.carbon.identity.recovery.RecoverySteps; import org.wso2.carbon.identity.recovery.model.UserRecoveryData; import org.wso2.carbon.identity.recovery.util.Utils; import java.sql.*; import java.util.Date; public class JDBCRecoveryDataStore implements UserRecoveryDataStore { private static UserRecoveryDataStore jdbcRecoveryDataStore = new JDBCRecoveryDataStore(); private JDBCRecoveryDataStore() { } public static UserRecoveryDataStore getInstance() { return jdbcRecoveryDataStore; } @Override public void store(UserRecoveryData recoveryDataDO) throws IdentityRecoveryException { Connection connection = IdentityDatabaseUtil.getDBConnection(); PreparedStatement prepStmt = null; try { prepStmt = connection.prepareStatement(IdentityRecoveryConstants.SQLQueries.STORE_RECOVERY_DATA); prepStmt.setString(1, recoveryDataDO.getUser().getUserName()); prepStmt.setString(2, recoveryDataDO.getUser().getUserStoreDomain().toUpperCase()); prepStmt.setInt(3, IdentityTenantUtil.getTenantId(recoveryDataDO.getUser().getTenantDomain())); prepStmt.setString(4, recoveryDataDO.getSecret()); prepStmt.setString(5, String.valueOf(recoveryDataDO.getRecoveryScenario())); prepStmt.setString(6, String.valueOf(recoveryDataDO.getRecoveryStep())); prepStmt.setTimestamp(7, new Timestamp(new Date().getTime())); prepStmt.setString(8, recoveryDataDO.getRemainingSetIds()); prepStmt.execute(); connection.setAutoCommit(false); connection.commit(); } catch (SQLException e) { throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_STORING_RECOVERY_DATA, null, e); } finally { IdentityDatabaseUtil.closeStatement(prepStmt); IdentityDatabaseUtil.closeConnection(connection); } } @Override public UserRecoveryData load(User user, Enum recoveryScenario, Enum recoveryStep, String code) throws IdentityRecoveryException { PreparedStatement prepStmt = null; ResultSet resultSet = null; Connection connection = IdentityDatabaseUtil.getDBConnection(); String sql; try { if (IdentityUtil.isUserStoreCaseSensitive(user.getUserStoreDomain(), IdentityTenantUtil.getTenantId(user.getTenantDomain()))) { sql = IdentityRecoveryConstants.SQLQueries.LOAD_RECOVERY_DATA; } else { sql = IdentityRecoveryConstants.SQLQueries.LOAD_RECOVERY_DATA_CASE_INSENSITIVE; } prepStmt = connection.prepareStatement(sql); prepStmt.setString(1, user.getUserName()); prepStmt.setString(2, user.getUserStoreDomain().toUpperCase()); prepStmt.setInt(3, IdentityTenantUtil.getTenantId(user.getTenantDomain())); prepStmt.setString(4, code); prepStmt.setString(5, String.valueOf(recoveryScenario)); prepStmt.setString(6, String.valueOf(recoveryStep)); resultSet = prepStmt.executeQuery(); if (resultSet.next()) { UserRecoveryData userRecoveryData = new UserRecoveryData(user, code, recoveryScenario, recoveryStep); if (StringUtils.isNotBlank(resultSet.getString("REMAINING_SETS"))) { userRecoveryData.setRemainingSetIds(resultSet.getString("REMAINING_SETS")); } Timestamp timeCreated = resultSet.getTimestamp("TIME_CREATED"); long createdTimeStamp = timeCreated.getTime(); int notificationExpiryTimeInMinutes = Integer.parseInt(Utils.getRecoveryConfigs(IdentityRecoveryConstants .ConnectorConfig.EXPIRY_TIME, user.getTenantDomain())); //Notification expiry time in minutes long expiryTime = createdTimeStamp + notificationExpiryTimeInMinutes * 60 * 1000L; if (System.currentTimeMillis() > expiryTime) { throw Utils.handleClientException(IdentityRecoveryConstants.ErrorMessages .ERROR_CODE_EXPIRED_CODE, code); } return userRecoveryData; } } catch (SQLException e) { throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, null, e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt); } throw Utils.handleClientException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_INVALID_CODE, code); } @Override public UserRecoveryData load(String code) throws IdentityRecoveryException { PreparedStatement prepStmt = null; ResultSet resultSet = null; Connection connection = IdentityDatabaseUtil.getDBConnection(); try { String sql = IdentityRecoveryConstants.SQLQueries.LOAD_RECOVERY_DATA_FROM_CODE; prepStmt = connection.prepareStatement(sql); prepStmt.setString(1, code); resultSet = prepStmt.executeQuery(); if (resultSet.next()) { User user = new User(); user.setUserName(resultSet.getString("USER_NAME")); user.setTenantDomain(IdentityTenantUtil.getTenantDomain(resultSet.getInt("TENANT_ID"))); user.setUserStoreDomain(resultSet.getString("USER_DOMAIN")); String recoveryScenario = resultSet.getString("SCENARIO"); String recoveryStep = resultSet.getString("STEP"); UserRecoveryData userRecoveryData = new UserRecoveryData(user, code, RecoveryScenarios.valueOf (recoveryScenario), RecoverySteps.valueOf(recoveryStep)); if (StringUtils.isNotBlank(resultSet.getString("REMAINING_SETS"))) { userRecoveryData.setRemainingSetIds(resultSet.getString("REMAINING_SETS")); } Timestamp timeCreated = resultSet.getTimestamp("TIME_CREATED"); long createdTimeStamp = timeCreated.getTime(); int notificationExpiryTimeInMinutes = Integer.parseInt(Utils.getRecoveryConfigs(IdentityRecoveryConstants .ConnectorConfig.EXPIRY_TIME, user.getTenantDomain())); //Notification expiry time in minutes long expiryTime = createdTimeStamp + notificationExpiryTimeInMinutes * 60 * 1000L; if (System.currentTimeMillis() > expiryTime) { throw Utils.handleClientException(IdentityRecoveryConstants.ErrorMessages .ERROR_CODE_EXPIRED_CODE, code); } return userRecoveryData; } } catch (SQLException e) { throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, null, e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt); } throw Utils.handleClientException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_INVALID_CODE, code); } @Override public void invalidate(String code) throws IdentityRecoveryException { PreparedStatement prepStmt = null; Connection connection = IdentityDatabaseUtil.getDBConnection(); try { String sql = IdentityRecoveryConstants.SQLQueries.INVALIDATE_CODE; prepStmt = connection.prepareStatement(sql); prepStmt.setString(1, code); prepStmt.execute(); connection.commit(); } catch (SQLException e) { throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, null, e); } finally { IdentityDatabaseUtil.closeStatement(prepStmt); IdentityDatabaseUtil.closeConnection(connection); } } @Override public UserRecoveryData load(User user) throws IdentityRecoveryException { PreparedStatement prepStmt = null; ResultSet resultSet = null; Connection connection = IdentityDatabaseUtil.getDBConnection(); try { String sql; if (IdentityUtil.isUserStoreCaseSensitive(user.getUserStoreDomain(), IdentityTenantUtil.getTenantId(user.getTenantDomain()))) { sql = IdentityRecoveryConstants.SQLQueries.LOAD_RECOVERY_DATA_OF_USER; } else { sql = IdentityRecoveryConstants.SQLQueries.LOAD_RECOVERY_DATA_OF_USER_CASE_INSENSITIVE; } prepStmt = connection.prepareStatement(sql); prepStmt.setString(1, user.getUserName()); prepStmt.setString(2, user.getUserStoreDomain().toUpperCase()); prepStmt.setInt(3, IdentityTenantUtil.getTenantId(user.getTenantDomain())); resultSet = prepStmt.executeQuery(); if (resultSet.next()) { UserRecoveryData userRecoveryData = new UserRecoveryData(user, resultSet.getString("CODE"), RecoveryScenarios.valueOf(resultSet.getString("SCENARIO")), RecoverySteps.valueOf(resultSet .getString("STEP"))); if (StringUtils.isNotBlank(resultSet.getString("REMAINING_SETS"))) { userRecoveryData.setRemainingSetIds(resultSet.getString("REMAINING_SETS")); } return userRecoveryData; } } catch (SQLException e) { throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, null, e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt); } return null; } @Override public void invalidate(User user) throws IdentityRecoveryException { PreparedStatement prepStmt = null; Connection connection = IdentityDatabaseUtil.getDBConnection(); try { String sql; if (IdentityUtil.isUserStoreCaseSensitive(user.getUserStoreDomain(), IdentityTenantUtil.getTenantId(user.getTenantDomain()))) { sql = IdentityRecoveryConstants.SQLQueries.INVALIDATE_USER_CODES; } else { sql = IdentityRecoveryConstants.SQLQueries.INVALIDATE_USER_CODES_CASE_INSENSITIVE; } prepStmt = connection.prepareStatement(sql); prepStmt.setString(1, user.getUserName()); prepStmt.setString(2, user.getUserStoreDomain()); prepStmt.setInt(3, IdentityTenantUtil.getTenantId(user.getTenantDomain())); prepStmt.execute(); connection.commit(); } catch (SQLException e) { throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, null, e); } finally { IdentityDatabaseUtil.closeStatement(prepStmt); IdentityDatabaseUtil.closeConnection(connection); } } }
package com.sequenceiq.environment.environment.flow.deletion.handler.sdx; import static com.sequenceiq.environment.environment.flow.deletion.event.EnvClustersDeleteStateSelectors.FINISH_ENV_CLUSTERS_DELETE_EVENT; import static com.sequenceiq.environment.environment.flow.deletion.event.EnvDeleteHandlerSelectors.DELETE_DATALAKE_CLUSTERS_EVENT; import java.util.concurrent.TimeUnit; import javax.ws.rs.ClientErrorException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.sequenceiq.cloudbreak.common.exception.BadRequestException; import com.sequenceiq.cloudbreak.common.exception.ExceptionResponse; import com.sequenceiq.environment.environment.dto.EnvironmentDeletionDto; import com.sequenceiq.environment.environment.dto.EnvironmentDto; import com.sequenceiq.environment.environment.flow.deletion.event.EnvClusterDeleteFailedEvent; import com.sequenceiq.environment.environment.flow.deletion.event.EnvDeleteEvent; import com.sequenceiq.environment.environment.service.EnvironmentService; import com.sequenceiq.environment.util.PollingConfig; import com.sequenceiq.flow.reactor.api.event.EventSender; import com.sequenceiq.flow.reactor.api.handler.EventSenderAwareHandler; import reactor.bus.Event; @Component public class DataLakeClustersDeleteHandler extends EventSenderAwareHandler<EnvironmentDeletionDto> { private static final Logger LOGGER = LoggerFactory.getLogger(DataLakeClustersDeleteHandler.class); private static final int SLEEP_TIME = 10; private static final int TIMEOUT = 1; private final EnvironmentService environmentService; private final SdxDeleteService sdxDeleteService; protected DataLakeClustersDeleteHandler(EventSender eventSender, EnvironmentService environmentService, SdxDeleteService sdxDeleteService) { super(eventSender); this.sdxDeleteService = sdxDeleteService; this.environmentService = environmentService; } @Override public void accept(Event<EnvironmentDeletionDto> environmentDtoEvent) { LOGGER.debug("Accepting DataLakeClustersDelete event"); EnvironmentDeletionDto environmentDeletionDto = environmentDtoEvent.getData(); EnvironmentDto environmentDto = environmentDeletionDto.getEnvironmentDto(); EnvDeleteEvent envDeleteEvent = getEnvDeleteEvent(environmentDeletionDto); try { PollingConfig pollingConfig = getPollingConfig(); environmentService.findEnvironmentById(environmentDto.getId()) .ifPresent(environment -> sdxDeleteService.deleteSdxClustersForEnvironment( pollingConfig, environment, environmentDeletionDto.isForceDelete())); eventSender().sendEvent(envDeleteEvent, environmentDtoEvent.getHeaders()); } catch (ClientErrorException e) { String message; try { message = e.getResponse().readEntity(ExceptionResponse.class).getMessage(); } catch (Exception exception) { message = null; } EnvClusterDeleteFailedEvent failedEvent = EnvClusterDeleteFailedEvent.builder() .withEnvironmentID(environmentDto.getId()) .withException(new BadRequestException(message)) .withResourceCrn(environmentDto.getResourceCrn()) .withResourceName(environmentDto.getName()) .withMessage(message) .build(); eventSender().sendEvent(failedEvent, environmentDtoEvent.getHeaders()); } catch (Exception e) { EnvClusterDeleteFailedEvent failedEvent = EnvClusterDeleteFailedEvent.builder() .withEnvironmentID(environmentDto.getId()) .withException(e) .withResourceCrn(environmentDto.getResourceCrn()) .withResourceName(environmentDto.getName()) .build(); eventSender().sendEvent(failedEvent, environmentDtoEvent.getHeaders()); } } @Override public String selector() { return DELETE_DATALAKE_CLUSTERS_EVENT.selector(); } private PollingConfig getPollingConfig() { return PollingConfig.builder() .withStopPollingIfExceptionOccured(true) .withSleepTime(SLEEP_TIME) .withSleepTimeUnit(TimeUnit.SECONDS) .withTimeout(TIMEOUT) .withTimeoutTimeUnit(TimeUnit.HOURS) .build(); } private EnvDeleteEvent getEnvDeleteEvent(EnvironmentDeletionDto environmentDeletionDto) { EnvironmentDto environmentDto = environmentDeletionDto.getEnvironmentDto(); return EnvDeleteEvent.builder() .withResourceId(environmentDto.getResourceId()) .withResourceName(environmentDto.getName()) .withResourceCrn(environmentDto.getResourceCrn()) .withForceDelete(environmentDeletionDto.isForceDelete()) .withSelector(FINISH_ENV_CLUSTERS_DELETE_EVENT.selector()) .build(); } }
package org.opendaylight.controller.sal.rest.doc.impl; import static org.opendaylight.controller.sal.rest.doc.util.RestDocgenUtil.resolvePathArgumentsName; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule; import com.google.common.base.Preconditions; import java.io.IOException; import java.net.URI; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.ws.rs.core.UriInfo; import org.json.JSONException; import org.json.JSONObject; import org.opendaylight.controller.sal.rest.doc.model.builder.OperationBuilder; import org.opendaylight.controller.sal.rest.doc.swagger.Api; import org.opendaylight.controller.sal.rest.doc.swagger.ApiDeclaration; import org.opendaylight.controller.sal.rest.doc.swagger.Operation; import org.opendaylight.controller.sal.rest.doc.swagger.Parameter; import org.opendaylight.controller.sal.rest.doc.swagger.Resource; import org.opendaylight.controller.sal.rest.doc.swagger.ResourceList; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BaseYangSwaggerGenerator { private static final Logger LOG = LoggerFactory.getLogger(BaseYangSwaggerGenerator.class); protected static final String API_VERSION = "1.0.0"; protected static final String SWAGGER_VERSION = "1.2"; protected static final String RESTCONF_CONTEXT_ROOT = "restconf"; static final String MODULE_NAME_SUFFIX = "_module"; protected final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private final ModelGenerator jsonConverter = new ModelGenerator(); // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>() private final ObjectMapper mapper = new ObjectMapper(); protected BaseYangSwaggerGenerator() { mapper.registerModule(new JsonOrgModule()); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); } /** * * @param uriInfo * @param operType * @return list of modules converted to swagger compliant resource list. */ public ResourceList getResourceListing(UriInfo uriInfo, SchemaContext schemaContext, String context) { ResourceList resourceList = createResourceList(); Set<Module> modules = getSortedModules(schemaContext); List<Resource> resources = new ArrayList<>(modules.size()); LOG.info("Modules found [{}]", modules.size()); for (Module module : modules) { String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision()); Resource resource = new Resource(); LOG.debug("Working on [{},{}]...", module.getName(), revisionString); ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context); if (doc != null) { resource.setPath(generatePath(uriInfo, module.getName(), revisionString)); resources.add(resource); } else { LOG.debug("Could not generate doc for {},{}", module.getName(), revisionString); } } resourceList.setApis(resources); return resourceList; } protected ResourceList createResourceList() { ResourceList resourceList = new ResourceList(); resourceList.setApiVersion(API_VERSION); resourceList.setSwaggerVersion(SWAGGER_VERSION); return resourceList; } protected String generatePath(UriInfo uriInfo, String name, String revision) { URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build(); return uri.toASCIIString(); } public ApiDeclaration getApiDeclaration(String module, String revision, UriInfo uriInfo, SchemaContext schemaContext, String context) { Date rev = null; try { rev = SIMPLE_DATE_FORMAT.parse(revision); } catch (ParseException e) { throw new IllegalArgumentException(e); } Module m = schemaContext.findModuleByName(module, rev); Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module + "," + revision); return getApiDeclaration(m, rev, uriInfo, context, schemaContext); } public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo, String context, SchemaContext schemaContext) { String basePath = createBasePathFromUriInfo(uriInfo); ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext); if (doc != null) { return doc; } return null; } protected String createBasePathFromUriInfo(UriInfo uriInfo) { String portPart = ""; int port = uriInfo.getBaseUri().getPort(); if (port != -1) { portPart = ":" + port; } String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append(": .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT) .toString(); return basePath; } public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context, SchemaContext schemaContext) { ApiDeclaration doc = createApiDeclaration(basePath); List<Api> apis = new ArrayList<Api>(); Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes(); LOG.debug("child nodes size [{}]", dataSchemaNodes.size()); for (DataSchemaNode node : dataSchemaNodes) { if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) { LOG.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName()); List<Parameter> pathParams = new ArrayList<Parameter>(); String resourcePath = getDataStorePath("/config/", context); addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, apis); addApis(node, apis, resourcePath, pathParams, schemaContext, true); pathParams = new ArrayList<Parameter>(); resourcePath = getDataStorePath("/operational/", context); addApis(node, apis, resourcePath, pathParams, schemaContext, false); } } Set<RpcDefinition> rpcs = m.getRpcs(); for (RpcDefinition rpcDefinition : rpcs) { String resourcePath = getDataStorePath("/operations/", context); addRpcs(rpcDefinition, apis, resourcePath, schemaContext); } LOG.debug("Number of APIs found [{}]", apis.size()); if (!apis.isEmpty()) { doc.setApis(apis); JSONObject models = null; try { models = jsonConverter.convertToJsonSchema(m, schemaContext); doc.setModels(models); if (LOG.isDebugEnabled()) { LOG.debug(mapper.writeValueAsString(doc)); } } catch (IOException | JSONException e) { e.printStackTrace(); } return doc; } return null; } private void addRootPostLink(final Module m, final DataNodeContainer node, final List<Parameter> pathParams, final String resourcePath, final List<Api> apis) { if (containsListOrContainer(m.getChildNodes())) { final Api apiForRootPostUri = new Api(); apiForRootPostUri.setPath(resourcePath); apiForRootPostUri.setOperations(operationPost(m.getName()+MODULE_NAME_SUFFIX, m.getDescription(), m, pathParams, true)); apis.add(apiForRootPostUri); } } protected ApiDeclaration createApiDeclaration(String basePath) { ApiDeclaration doc = new ApiDeclaration(); doc.setApiVersion(API_VERSION); doc.setSwaggerVersion(SWAGGER_VERSION); doc.setBasePath(basePath); doc.setProduces(Arrays.asList("application/json", "application/xml")); return doc; } protected String getDataStorePath(String dataStore, String context) { return dataStore + context; } private String generateCacheKey(Module m) { return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision())); } private String generateCacheKey(String module, String revision) { return module + "(" + revision + ")"; } private void addApis(DataSchemaNode node, List<Api> apis, String parentPath, List<Parameter> parentPathParams, SchemaContext schemaContext, boolean addConfigApi) { Api api = new Api(); List<Parameter> pathParams = new ArrayList<Parameter>(parentPathParams); String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/"; LOG.debug("Adding path: [{}]", resourcePath); api.setPath(resourcePath); Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode> emptySet(); if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) { DataNodeContainer dataNodeContainer = (DataNodeContainer) node; childSchemaNodes = dataNodeContainer.getChildNodes(); } api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes)); apis.add(api); for (DataSchemaNode childNode : childSchemaNodes) { if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) { // keep config and operation attributes separate. if (childNode.isConfiguration() == addConfigApi) { addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi); } } } } private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) { for (DataSchemaNode child : nodes) { if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) { return true; } } return false; } /** * @param node * @param pathParams * @return */ private List<Operation> operation(DataSchemaNode node, List<Parameter> pathParams, boolean isConfig, Iterable<DataSchemaNode> childSchemaNodes) { List<Operation> operations = new ArrayList<>(); OperationBuilder.Get getBuilder = new OperationBuilder.Get(node, isConfig); operations.add(getBuilder.pathParams(pathParams).build()); if (isConfig) { OperationBuilder.Put putBuilder = new OperationBuilder.Put(node.getQName().getLocalName(), node.getDescription()); operations.add(putBuilder.pathParams(pathParams).build()); OperationBuilder.Delete deleteBuilder = new OperationBuilder.Delete(node); operations.add(deleteBuilder.pathParams(pathParams).build()); if (containsListOrContainer(childSchemaNodes)) { operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(), (DataNodeContainer) node, pathParams, isConfig)); } } return operations; } /** * @param node * @param pathParams * @return */ private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer, List<Parameter> pathParams, boolean isConfig) { List<Operation> operations = new ArrayList<>(); if (isConfig) { OperationBuilder.Post postBuilder = new OperationBuilder.Post(name, description, dataNodeContainer); operations.add(postBuilder.pathParams(pathParams).build()); } return operations; } private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams, SchemaContext schemaContext) { ArrayList<LeafSchemaNode> pathListParams = new ArrayList<LeafSchemaNode>(); StringBuilder path = new StringBuilder(); String localName = resolvePathArgumentsName(schemaNode, schemaContext); path.append(localName); if ((schemaNode instanceof ListSchemaNode)) { final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition(); for (final QName listKey : listKeys) { DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey); pathListParams.add(((LeafSchemaNode) _dataChildByName)); String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}") .toString(); path.append(pathParamIdentifier); Parameter pathParam = new Parameter(); pathParam.setName(listKey.getLocalName()); pathParam.setDescription(_dataChildByName.getDescription()); pathParam.setType("string"); pathParam.setParamType("path"); pathParams.add(pathParam); } } return path.toString(); } protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath, SchemaContext schemaContext) { Api rpc = new Api(); String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext); rpc.setPath(resourcePath); Operation operationSpec = new Operation(); operationSpec.setMethod("POST"); operationSpec.setNotes(rpcDefn.getDescription()); operationSpec.setNickname(rpcDefn.getQName().getLocalName()); if (rpcDefn.getOutput() != null) { operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output"); } if (rpcDefn.getInput() != null) { Parameter payload = new Parameter(); payload.setParamType("body"); payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input"); operationSpec.setParameters(Collections.singletonList(payload)); } rpc.setOperations(Arrays.asList(operationSpec)); apis.add(rpc); } protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) { if (schemaContext == null) { return new TreeSet<>(); } Set<Module> modules = schemaContext.getModules(); SortedSet<Module> sortedModules = new TreeSet<>(new Comparator<Module>() { @Override public int compare(Module o1, Module o2) { int result = o1.getName().compareTo(o2.getName()); if (result == 0) { result = o1.getRevision().compareTo(o2.getRevision()); } if (result == 0) { result = o1.getNamespace().compareTo(o2.getNamespace()); } return result; } }); for (Module m : modules) { if (m != null) { sortedModules.add(m); } } return sortedModules; } }
package org.opendaylight.controller.switchmanager.internal; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.EnumSet; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.felix.dm.Component; import org.eclipse.osgi.framework.console.CommandInterpreter; import org.eclipse.osgi.framework.console.CommandProvider; import org.opendaylight.controller.clustering.services.CacheConfigException; import org.opendaylight.controller.clustering.services.CacheExistException; import org.opendaylight.controller.clustering.services.IClusterContainerServices; import org.opendaylight.controller.clustering.services.IClusterServices; import org.opendaylight.controller.configuration.ConfigurationObject; import org.opendaylight.controller.configuration.IConfigurationContainerAware; import org.opendaylight.controller.configuration.IConfigurationContainerService; import org.opendaylight.controller.sal.core.Bandwidth; import org.opendaylight.controller.sal.core.Config; import org.opendaylight.controller.sal.core.ConstructionException; import org.opendaylight.controller.sal.core.Description; import org.opendaylight.controller.sal.core.ForwardingMode; import org.opendaylight.controller.sal.core.MacAddress; import org.opendaylight.controller.sal.core.Name; import org.opendaylight.controller.sal.core.Node; import org.opendaylight.controller.sal.core.NodeConnector; import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; import org.opendaylight.controller.sal.core.Property; import org.opendaylight.controller.sal.core.State; import org.opendaylight.controller.sal.core.Tier; import org.opendaylight.controller.sal.core.UpdateType; import org.opendaylight.controller.sal.inventory.IInventoryService; import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; import org.opendaylight.controller.sal.reader.NodeDescription; import org.opendaylight.controller.sal.utils.GlobalConstants; import org.opendaylight.controller.sal.utils.HexEncode; import org.opendaylight.controller.sal.utils.IObjectReader; import org.opendaylight.controller.sal.utils.Status; import org.opendaylight.controller.sal.utils.StatusCode; import org.opendaylight.controller.statisticsmanager.IStatisticsManager; import org.opendaylight.controller.switchmanager.IInventoryListener; import org.opendaylight.controller.switchmanager.ISpanAware; import org.opendaylight.controller.switchmanager.ISwitchManager; import org.opendaylight.controller.switchmanager.ISwitchManagerAware; import org.opendaylight.controller.switchmanager.SpanConfig; import org.opendaylight.controller.switchmanager.Subnet; import org.opendaylight.controller.switchmanager.SubnetConfig; import org.opendaylight.controller.switchmanager.Switch; import org.opendaylight.controller.switchmanager.SwitchConfig; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class describes SwitchManager which is the central repository of all the * inventory data including nodes, node connectors, properties attached, Layer3 * configurations, Span configurations, node configurations, network device * representations viewed by Controller Web applications. One SwitchManager * instance per container of the network. All the node/nodeConnector properties * are maintained in the default container only. */ public class SwitchManager implements ISwitchManager, IConfigurationContainerAware, IObjectReader, IListenInventoryUpdates, CommandProvider { private static Logger log = LoggerFactory.getLogger(SwitchManager.class); private static final String SUBNETS_FILE_NAME = "subnets.conf"; private static final String SPAN_FILE_NAME = "spanPorts.conf"; private static final String SWITCH_CONFIG_FILE_NAME = "switchConfig.conf"; private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>(); // Collection of Subnets keyed by the InetAddress private ConcurrentMap<InetAddress, Subnet> subnets; private ConcurrentMap<String, SubnetConfig> subnetsConfigList; private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList; // manually configured parameters for the node such as name, tier, mode private ConcurrentMap<String, SwitchConfig> nodeConfigList; private ConcurrentMap<Node, Map<String, Property>> nodeProps; private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps; private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames; private ConcurrentMap<String, Property> controllerProps; private IInventoryService inventoryService; private IStatisticsManager statisticsManager; private IConfigurationContainerService configurationService; private final Set<ISwitchManagerAware> switchManagerAware = Collections .synchronizedSet(new HashSet<ISwitchManagerAware>()); private final Set<IInventoryListener> inventoryListeners = Collections .synchronizedSet(new HashSet<IInventoryListener>()); private final Set<ISpanAware> spanAware = Collections.synchronizedSet(new HashSet<ISpanAware>()); private IClusterContainerServices clusterContainerService = null; private String containerName = null; private boolean isDefaultContainer = true; private static final int REPLACE_RETRY = 1; /* Information about the default subnet. If there have been no configured subnets, i.e., * subnets.size() == 0 or subnetsConfigList.size() == 0, then this subnet will be the * only subnet returned. As soon as a user-configured subnet is created this one will * vanish. */ protected static final SubnetConfig DEFAULT_SUBNETCONFIG; protected static final Subnet DEFAULT_SUBNET; protected static final String DEFAULT_SUBNET_NAME = "default (cannot be modifed)"; static{ DEFAULT_SUBNETCONFIG = new SubnetConfig(DEFAULT_SUBNET_NAME, "0.0.0.0/0", new ArrayList<String>()); DEFAULT_SUBNET = new Subnet(DEFAULT_SUBNETCONFIG); } public void notifySubnetChange(Subnet sub, boolean add) { synchronized (switchManagerAware) { for (Object subAware : switchManagerAware) { try { ((ISwitchManagerAware) subAware).subnetNotify(sub, add); } catch (Exception e) { log.error("Failed to notify Subnet change {}", e.getMessage()); } } } } public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) { synchronized (spanAware) { for (Object sa : spanAware) { try { ((ISpanAware) sa).spanUpdate(node, ports, add); } catch (Exception e) { log.error("Failed to notify Span Interface change {}", e.getMessage()); } } } } private void notifyModeChange(Node node, boolean proactive) { synchronized (switchManagerAware) { for (ISwitchManagerAware service : switchManagerAware) { try { service.modeChangeNotify(node, proactive); } catch (Exception e) { log.error("Failed to notify Subnet change {}", e.getMessage()); } } } } public void startUp() { // Instantiate cluster synced variables allocateCaches(); retrieveCaches(); // Add controller MAC, if first node in the cluster if (!controllerProps.containsKey(MacAddress.name)) { byte controllerMac[] = getHardwareMAC(); if (controllerMac != null) { Property existing = controllerProps.putIfAbsent(MacAddress.name, new MacAddress(controllerMac)); if (existing == null && log.isTraceEnabled()) { log.trace("Container {}: Setting controller MAC address in the cluster: {}", getContainerName(), HexEncode.bytesToHexStringFormat(controllerMac)); } } } } public void shutDown() { } private void allocateCaches() { if (this.clusterContainerService == null) { this.nonClusterObjectCreate(); log.warn("un-initialized clusterContainerService, can't create cache"); return; } try { clusterContainerService.createCache( "switchmanager.subnetsConfigList", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.spanConfigList", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.nodeConfigList", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.subnets", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.nodeProps", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache( "switchmanager.nodeConnectorProps", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache( "switchmanager.nodeConnectorNames", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache( "switchmanager.controllerProps", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); } catch (CacheConfigException cce) { log.error("\nCache configuration invalid - check cache mode"); } catch (CacheExistException ce) { log.error("\nCache already exits - destroy and recreate if needed"); } } @SuppressWarnings({ "unchecked" }) private void retrieveCaches() { if (this.clusterContainerService == null) { log.warn("un-initialized clusterContainerService, can't create cache"); return; } subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService .getCache("switchmanager.subnetsConfigList"); if (subnetsConfigList == null) { log.error("\nFailed to get cache for subnetsConfigList"); } spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService .getCache("switchmanager.spanConfigList"); if (spanConfigList == null) { log.error("\nFailed to get cache for spanConfigList"); } nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService .getCache("switchmanager.nodeConfigList"); if (nodeConfigList == null) { log.error("\nFailed to get cache for nodeConfigList"); } subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService .getCache("switchmanager.subnets"); if (subnets == null) { log.error("\nFailed to get cache for subnets"); } nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService .getCache("switchmanager.nodeProps"); if (nodeProps == null) { log.error("\nFailed to get cache for nodeProps"); } nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService .getCache("switchmanager.nodeConnectorProps"); if (nodeConnectorProps == null) { log.error("\nFailed to get cache for nodeConnectorProps"); } nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService .getCache("switchmanager.nodeConnectorNames"); if (nodeConnectorNames == null) { log.error("\nFailed to get cache for nodeConnectorNames"); } controllerProps = (ConcurrentMap<String, Property>) clusterContainerService .getCache("switchmanager.controllerProps"); if (controllerProps == null) { log.error("\nFailed to get cache for controllerProps"); } } private void nonClusterObjectCreate() { subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>(); spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>(); nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>(); subnets = new ConcurrentHashMap<InetAddress, Subnet>(); nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>(); nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>(); nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>(); controllerProps = new ConcurrentHashMap<String, Property>(); } @Override public List<SubnetConfig> getSubnetsConfigList() { // if there are no subnets, return the default subnet if(subnetsConfigList.size() == 0){ return Collections.singletonList(DEFAULT_SUBNETCONFIG); }else{ return new ArrayList<SubnetConfig>(subnetsConfigList.values()); } } @Override public SubnetConfig getSubnetConfig(String subnet) { // if there are no subnets, return the default subnet if(subnetsConfigList.isEmpty() && subnet.equalsIgnoreCase(DEFAULT_SUBNET_NAME)){ return DEFAULT_SUBNETCONFIG; }else{ return subnetsConfigList.get(subnet); } } private List<SpanConfig> getSpanConfigList(Node node) { List<SpanConfig> confList = new ArrayList<SpanConfig>(); String nodeId = node.toString(); for (SpanConfig conf : spanConfigList.values()) { if (conf.matchNode(nodeId)) { confList.add(conf); } } return confList; } public List<SwitchConfig> getNodeConfigList() { return new ArrayList<SwitchConfig>(nodeConfigList.values()); } @Override public SwitchConfig getSwitchConfig(String switchId) { return nodeConfigList.get(switchId); } public Switch getSwitchByNode(Node node) { Switch sw = new Switch(node); sw.setNode(node); MacAddress mac = (MacAddress) this.getNodeProp(node, MacAddress.name); if (mac != null) { sw.setDataLayerAddress(mac.getMacAddress()); } Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node); sw.setNodeConnectors(ncSet); List<NodeConnector> ncList = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : ncSet) { if (spanNodeConnectors.contains(nodeConnector)) { ncList.add(nodeConnector); } } sw.addSpanPorts(ncList); return sw; } @Override public List<Switch> getNetworkDevices() { List<Switch> swList = new ArrayList<Switch>(); for (Node node : getNodes()) { swList.add(getSwitchByNode(node)); } return swList; } private Status updateConfig(SubnetConfig conf, boolean add) { if (add) { if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) { String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists."; return new Status(StatusCode.CONFLICT, msg); } } else { subnetsConfigList.remove(conf.getName()); } return new Status(StatusCode.SUCCESS); } private Status updateDatabase(SubnetConfig conf, boolean add) { if (add) { Subnet subnetCurr = subnets.get(conf.getIPAddress()); Subnet subnet; if (subnetCurr == null) { subnet = new Subnet(conf); } else { subnet = subnetCurr.clone(); } // In case of API3 call we may receive the ports along with the // subnet creation if (!conf.isGlobal()) { subnet.addNodeConnectors(conf.getNodeConnectors()); } boolean putNewSubnet = false; if(subnetCurr == null) { if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) { putNewSubnet = true; } } else { putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet); } if(!putNewSubnet) { String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress(); return new Status(StatusCode.CONFLICT, msg); } // Subnet removal case } else { subnets.remove(conf.getIPAddress()); } return new Status(StatusCode.SUCCESS); } private Status semanticCheck(SubnetConfig conf) { Set<InetAddress> IPs = subnets.keySet(); if (IPs == null) { return new Status(StatusCode.SUCCESS); } Subnet newSubnet = new Subnet(conf); for (InetAddress i : IPs) { Subnet existingSubnet = subnets.get(i); if ((existingSubnet != null) && !existingSubnet.isMutualExclusive(newSubnet)) { return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one."); } } return new Status(StatusCode.SUCCESS); } private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) { // Valid configuration check Status status = conf.validate(); if (!status.isSuccess()) { log.warn(status.getDescription()); return status; } if (isAdding) { // Presence check if (subnetsConfigList.containsKey(conf.getName())) { return new Status(StatusCode.CONFLICT, "Subnet with the specified name already exists."); } // Semantic check status = semanticCheck(conf); if (!status.isSuccess()) { return status; } } else { if (conf.getName().equalsIgnoreCase(DEFAULT_SUBNET_NAME)) { return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed"); } } // Update Database status = updateDatabase(conf, isAdding); if (status.isSuccess()) { // Update Configuration status = updateConfig(conf, isAdding); if(!status.isSuccess()) { updateDatabase(conf, (!isAdding)); } else { // update the listeners Subnet subnetCurr = subnets.get(conf.getIPAddress()); Subnet subnet; if (subnetCurr == null) { subnet = new Subnet(conf); } else { subnet = subnetCurr.clone(); } notifySubnetChange(subnet, isAdding); } } return status; } /** * Adds Subnet configured in GUI or API3 */ @Override public Status addSubnet(SubnetConfig conf) { return this.addRemoveSubnet(conf, true); } @Override public Status removeSubnet(SubnetConfig conf) { return this.addRemoveSubnet(conf, false); } @Override public Status removeSubnet(String name) { if (name.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) { return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed"); } SubnetConfig conf = subnetsConfigList.get(name); if (conf == null) { return new Status(StatusCode.SUCCESS, "Subnet not present"); } return this.addRemoveSubnet(conf, false); } @Override public Status modifySubnet(SubnetConfig conf) { // Sanity check if (conf == null) { return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null"); } // Valid configuration check Status status = conf.validate(); if (!status.isSuccess()) { log.warn(status.getDescription()); return status; } // If a subnet configuration with this name does not exist, consider this is a creation SubnetConfig target = subnetsConfigList.get(conf.getName()); if (target == null) { return this.addSubnet(conf); } // No change if (target.equals(conf)) { return new Status(StatusCode.SUCCESS); } // Check not allowed modifications if (!target.getSubnet().equals(conf.getSubnet())) { return new Status(StatusCode.BADREQUEST, "IP address change is not allowed"); } // Derive the set of node connectors that are being removed Set<NodeConnector> toRemove = target.getNodeConnectors(); toRemove.removeAll(conf.getNodeConnectors()); List<String> nodeConnectorStrings = null; if (!toRemove.isEmpty()) { nodeConnectorStrings = new ArrayList<String>(); for (NodeConnector nc : toRemove) { nodeConnectorStrings.add(nc.toString()); } status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings); if (!status.isSuccess()) { return status; } } // Derive the set of node connectors that are being added Set<NodeConnector> toAdd = conf.getNodeConnectors(); toAdd.removeAll(target.getNodeConnectors()); if (!toAdd.isEmpty()) { List<String> nodeConnectorStringRemoved = nodeConnectorStrings; nodeConnectorStrings = new ArrayList<String>(); for (NodeConnector nc : toAdd) { nodeConnectorStrings.add(nc.toString()); } status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings); if (!status.isSuccess()) { // If any port was removed, add it back as a best recovery effort if (!toRemove.isEmpty()) { this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved); } return status; } } // Update Configuration subnetsConfigList.put(conf.getName(), conf); return new Status(StatusCode.SUCCESS); } @Override public Status addPortsToSubnet(String name, List<String> switchPorts) { if (name == null) { return new Status(StatusCode.BADREQUEST, "Null subnet name"); } SubnetConfig confCurr = subnetsConfigList.get(name); if (confCurr == null) { return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } if (switchPorts == null || switchPorts.isEmpty()) { return new Status(StatusCode.BADREQUEST, "Null or empty port set"); } Subnet subCurr = subnets.get(confCurr.getIPAddress()); if (subCurr == null) { log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress()); return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } // Update Database Subnet sub = subCurr.clone(); Set<NodeConnector> sp = NodeConnector.fromString(switchPorts); sub.addNodeConnectors(sp); boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub); if (!subnetsReplaced) { String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name; return new Status(StatusCode.CONFLICT, msg); } // Update Configuration SubnetConfig conf = confCurr.clone(); conf.addNodeConnectors(switchPorts); boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf); if (!configReplaced) { // TODO: recovery using Transactionality String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name; return new Status(StatusCode.CONFLICT, msg); } return new Status(StatusCode.SUCCESS); } @Override public Status removePortsFromSubnet(String name, List<String> switchPorts) { if (name == null) { return new Status(StatusCode.BADREQUEST, "Null subnet name"); } SubnetConfig confCurr = subnetsConfigList.get(name); if (confCurr == null) { return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } if (switchPorts == null || switchPorts.isEmpty()) { return new Status(StatusCode.BADREQUEST, "Null or empty port set"); } Subnet subCurr = subnets.get(confCurr.getIPAddress()); if (subCurr == null) { log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress()); return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } // Validation check Status status = SubnetConfig.validatePorts(switchPorts); if (!status.isSuccess()) { return status; } // Update Database Subnet sub = subCurr.clone(); Set<NodeConnector> sp = NodeConnector.fromString(switchPorts); sub.deleteNodeConnectors(sp); boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub); if (!subnetsReplace) { String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name; return new Status(StatusCode.CONFLICT, msg); } // Update Configuration SubnetConfig conf = confCurr.clone(); conf.removeNodeConnectors(switchPorts); boolean result = subnetsConfigList.replace(name, confCurr, conf); if (!result) { // TODO: recovery using Transactionality String msg = "Cluster conflict: Conflict while removing ports from " + conf; return new Status(StatusCode.CONFLICT, msg); } return new Status(StatusCode.SUCCESS); } public String getContainerName() { if (containerName == null) { return GlobalConstants.DEFAULT.toString(); } return containerName; } @Override public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) { // if there are no subnets, return the default subnet if (subnets.size() == 0) { return DEFAULT_SUBNET; } for(Map.Entry<InetAddress,Subnet> subnetEntry : subnets.entrySet()) { if(subnetEntry.getValue().isSubnetOf(networkAddress)) { return subnetEntry.getValue(); } } return null; } @Override public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException { // Perform the class deserialization locally, from inside the package // where the class is defined return ois.readObject(); } private void loadSubnetConfiguration() { for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SUBNETS_FILE_NAME)) { addSubnet((SubnetConfig) conf); } } private void loadSpanConfiguration() { for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SPAN_FILE_NAME)) { addSpanConfig((SpanConfig) conf); } } private void loadSwitchConfiguration() { for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SWITCH_CONFIG_FILE_NAME)) { updateNodeConfig((SwitchConfig) conf); } } @SuppressWarnings("deprecation") @Override public void updateSwitchConfig(SwitchConfig cfgObject) { // update default container only if (!isDefaultContainer) { return; } SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId()); if (sc == null) { if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) { return; } } else { if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) { return; } } boolean modeChange = false; if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) { modeChange = true; } String nodeId = cfgObject.getNodeId(); Node node = Node.fromString(nodeId); Map<String, Property> propMapCurr = nodeProps.get(node); if (propMapCurr == null) { return; } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); Property desc = new Description(cfgObject.getNodeDescription()); propMap.put(desc.getName(), desc); Property tier = new Tier(Integer.parseInt(cfgObject.getTier())); propMap.put(tier.getName(), tier); if (!nodeProps.replace(node, propMapCurr, propMap)) { // TODO rollback using Transactionality return; } log.trace("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode()); if (modeChange) { notifyModeChange(node, cfgObject.isProactive()); } } @Override public Status updateNodeConfig(SwitchConfig switchConfig) { Status status = switchConfig.validate(); if (!status.isSuccess()) { return status; } Map<String, Property> updateProperties = switchConfig.getNodeProperties(); ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name); if (mode != null) { if (isDefaultContainer) { if (!mode.isValid()) { return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value"); } } else { return new Status(StatusCode.NOTACCEPTABLE, "Forwarding Mode modification is allowed only in default container"); } } Description description = (Description) switchConfig.getProperty(Description.propertyName); String nodeId = switchConfig.getNodeId(); Node node = Node.fromString(nodeId); NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager .getNodeDescription(node); String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription(); if (description != null && description.getValue() != null) { if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) { updateProperties.remove(Description.propertyName); switchConfig = new SwitchConfig(nodeId, updateProperties); } else { // check if description is configured or was published by any other node for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) { Node n = entry.getKey(); Description desc = (Description) getNodeProp(n, Description.propertyName); NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager .getNodeDescription(n); String advDesc = (nDesc == null) ? "" : nDesc.getDescription(); if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) { return new Status(StatusCode.CONFLICT, "Node name already in use"); } } } } boolean modeChange = false; SwitchConfig sc = nodeConfigList.get(nodeId); Map<String, Property> prevNodeProperties = new HashMap<String, Property>(); if (sc == null) { if ((mode != null) && mode.isProactive()) { modeChange = true; } if (!updateProperties.isEmpty()) { if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) { return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); } } } else { prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties()); ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name); if (mode == null) { if ((prevMode != null) && (prevMode.isProactive())) { modeChange = true; } } else { if (((prevMode != null) && (prevMode.getValue() != mode.getValue())) || (prevMode == null && mode.isProactive())) { modeChange = true; } } if (updateProperties.isEmpty()) { nodeConfigList.remove(nodeId); } else { if (!nodeConfigList.replace(nodeId, sc, switchConfig)) { return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); } } } Map<String, Property> propMapCurr = nodeProps.get(node); if (propMapCurr == null) { return new Status(StatusCode.SUCCESS); } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) { String prop = entry.getKey(); if (!updateProperties.containsKey(prop)) { if (prop.equals(Description.propertyName)) { if (!advertisedDesc.isEmpty()) { Property desc = new Description(advertisedDesc); propMap.put(Description.propertyName, desc); } continue; } else if (prop.equals(ForwardingMode.name)) { Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING); propMap.put(ForwardingMode.name, defaultMode); continue; } propMap.remove(prop); } } propMap.putAll(updateProperties); if (!nodeProps.replace(node, propMapCurr, propMap)) { // TODO rollback using Transactionality return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); } if (modeChange) { notifyModeChange(node, (mode == null) ? false : mode.isProactive()); } return new Status(StatusCode.SUCCESS); } @Override public Status removeNodeConfig(String nodeId) { if ((nodeId == null) || (nodeId.isEmpty())) { return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty."); } Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties(); Node node = Node.fromString(nodeId); Map<String, Property> propMapCurr = nodeProps.get(node); if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) { Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) { String prop = entry.getKey(); if (prop.equals(Description.propertyName)) { Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps(); if (nodeProp.get(node) != null) { propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName)); continue; } } propMap.remove(prop); } if (!nodeProps.replace(node, propMapCurr, propMap)) { return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration."); } } if (nodeConfigList != null) { nodeConfigList.remove(nodeId); } return new Status(StatusCode.SUCCESS); } @Override public Status saveSwitchConfig() { return saveSwitchConfigInternal(); } public Status saveSwitchConfigInternal() { Status status; short number = 0; status = configurationService.persistConfiguration( new ArrayList<ConfigurationObject>(subnetsConfigList.values()), SUBNETS_FILE_NAME); if (status.isSuccess()) { number++; } else { log.warn("Failed to save subnet gateway configurations: " + status.getDescription()); } status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(spanConfigList.values()), SPAN_FILE_NAME); if (status.isSuccess()) { number++; } else { log.warn("Failed to save span port configurations: " + status.getDescription()); } status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(nodeConfigList.values()), SWITCH_CONFIG_FILE_NAME); if (status.isSuccess()) { number++; } else { log.warn("Failed to save node configurations: " + status.getDescription()); } if (number == 0) { return new Status(StatusCode.INTERNALERROR, "Save failed"); } if (number < 3) { return new Status(StatusCode.INTERNALERROR, "Partial save failure"); } return status; } @Override public List<SpanConfig> getSpanConfigList() { return new ArrayList<SpanConfig>(spanConfigList.values()); } @Override public Status addSpanConfig(SpanConfig conf) { // Valid config check if (!conf.isValidConfig()) { String msg = "Invalid Span configuration"; log.warn(msg); return new Status(StatusCode.BADREQUEST, msg); } // Presence check if (spanConfigList.containsKey(conf)) { return new Status(StatusCode.CONFLICT, "Same span config exists"); } // Update configuration if (spanConfigList.putIfAbsent(conf, conf) == null) { // Update database and notify clients addSpanPorts(conf.getNode(), conf.getPortArrayList()); } return new Status(StatusCode.SUCCESS); } @Override public Status removeSpanConfig(SpanConfig conf) { removeSpanPorts(conf.getNode(), conf.getPortArrayList()); // Update configuration spanConfigList.remove(conf); return new Status(StatusCode.SUCCESS); } @Override public List<NodeConnector> getSpanPorts(Node node) { List<NodeConnector> ncList = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : spanNodeConnectors) { if (nodeConnector.getNode().equals(node)) { ncList.add(nodeConnector); } } return ncList; } private void addNode(Node node, Set<Property> props) { log.trace("{} added, props: {}", node, props); if (nodeProps == null) { return; } Map<String, Property> propMapCurr = nodeProps.get(node); Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>() : new HashMap<String, Property>(propMapCurr); // copy node properties from plugin if (props != null) { for (Property prop : props) { propMap.put(prop.getName(), prop); } } boolean proactiveForwarding = false; // copy node properties from config if (nodeConfigList != null) { String nodeId = node.toString(); SwitchConfig conf = nodeConfigList.get(nodeId); if (conf != null && (conf.getNodeProperties() != null)) { Map<String, Property> nodeProperties = conf.getNodeProperties(); propMap.putAll(nodeProperties); if (nodeProperties.get(ForwardingMode.name) != null) { ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name); proactiveForwarding = mode.isProactive(); } } } if (!propMap.containsKey(ForwardingMode.name)) { Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING); propMap.put(ForwardingMode.name, defaultMode); } boolean result = false; if (propMapCurr == null) { if (nodeProps.putIfAbsent(node, propMap) == null) { result = true; } } else { result = nodeProps.replace(node, propMapCurr, propMap); } if (!result) { log.debug("Cluster conflict: Conflict while adding the node properties. Node: {} Properties: {}", node.getID(), props); addNodeProps(node, propMap); } // check if span ports are configed addSpanPorts(node); // notify node listeners notifyNode(node, UpdateType.ADDED, propMap); // notify proactive mode forwarding if (proactiveForwarding) { notifyModeChange(node, true); } } private void removeNode(Node node) { log.trace("{} removed", node); if (nodeProps == null) { return; } nodeProps.remove(node); nodeConnectorNames.remove(node); Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (nodeConnector.getNode().equals(node)) { removeNodeConnectorSet.add(nodeConnector); } } for (NodeConnector nc : removeNodeConnectorSet) { nodeConnectorProps.remove(nc); } // check if span ports need to be cleaned up removeSpanPorts(node); /* notify node listeners */ notifyNode(node, UpdateType.REMOVED, null); } private void updateNode(Node node, Set<Property> props) { log.trace("{} updated, props: {}", node, props); if (nodeProps == null || props == null) { return; } Map<String, Property> propMapCurr = nodeProps.get(node); Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>() : new HashMap<String, Property>(propMapCurr); // copy node properties from plugin String nodeId = node.toString(); for (Property prop : props) { if (nodeConfigList != null) { SwitchConfig conf = nodeConfigList.get(nodeId); if (conf != null && (conf.getNodeProperties() != null) && conf.getNodeProperties().containsKey(prop.getName())) { continue; } } propMap.put(prop.getName(), prop); } if (propMapCurr == null) { if (nodeProps.putIfAbsent(node, propMap) != null) { log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}", node.getID(), props); addNodeProps(node, propMap); } } else { if (!nodeProps.replace(node, propMapCurr, propMap)) { log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}", node.getID(), props); addNodeProps(node, propMap); } } /* notify node listeners */ notifyNode(node, UpdateType.CHANGED, propMap); } @Override public void updateNode(Node node, UpdateType type, Set<Property> props) { log.debug("updateNode: {} type {} props {} for container {}", new Object[] { node, type, props, containerName }); switch (type) { case ADDED: addNode(node, props); break; case CHANGED: updateNode(node, props); break; case REMOVED: removeNode(node); break; default: break; } } @Override public void updateNodeConnector(NodeConnector nodeConnector, UpdateType type, Set<Property> props) { Map<String, Property> propMap = new HashMap<String, Property>(); boolean update = true; log.debug("updateNodeConnector: {} type {} props {} for container {}", new Object[] { nodeConnector, type, props, containerName }); if (nodeConnectorProps == null) { return; } switch (type) { case ADDED: if (props != null) { for (Property prop : props) { addNodeConnectorProp(nodeConnector, prop); propMap.put(prop.getName(), prop); } } else { addNodeConnectorProp(nodeConnector, null); } addSpanPort(nodeConnector); break; case CHANGED: if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) { update = false; } else { for (Property prop : props) { addNodeConnectorProp(nodeConnector, prop); propMap.put(prop.getName(), prop); } } break; case REMOVED: if (!nodeConnectorProps.containsKey(nodeConnector)) { update = false; } removeNodeConnectorAllProps(nodeConnector); // clean up span config removeSpanPort(nodeConnector); break; default: update = false; break; } if (update) { notifyNodeConnector(nodeConnector, type, propMap); } } @Override public Set<Node> getNodes() { return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>(); } @Override public Map<String, Property> getControllerProperties() { return new HashMap<String, Property>(this.controllerProps); } @Override public Property getControllerProperty(String propertyName) { if (propertyName != null) { HashMap<String, Property> propertyMap = new HashMap<String, Property>(this.controllerProps); return propertyMap.get(propertyName); } return null; } @Override public Status setControllerProperty(Property property) { if (property != null) { this.controllerProps.put(property.getName(), property); return new Status(StatusCode.SUCCESS); } return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property"); } @Override public Status removeControllerProperty(String propertyName) { if (propertyName != null) { if (this.controllerProps.containsKey(propertyName)) { this.controllerProps.remove(propertyName); if (!this.controllerProps.containsKey(propertyName)) { return new Status(StatusCode.SUCCESS); } } String msg = "Unable to remove property " + propertyName + " from Controller"; return new Status(StatusCode.BADREQUEST, msg); } String msg = "Invalid property provided when removing property from Controller"; return new Status(StatusCode.BADREQUEST, msg); } /* * Returns a copy of a list of properties for a given node * * (non-Javadoc) * * @see * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps * (org.opendaylight.controller.sal.core.Node) */ @Override public Map<String, Property> getNodeProps(Node node) { Map<String, Property> rv = new HashMap<String, Property>(); if (this.nodeProps != null) { rv = this.nodeProps.get(node); if (rv != null) { /* make a copy of it */ rv = new HashMap<String, Property>(rv); } } return rv; } @Override public Property getNodeProp(Node node, String propName) { Map<String, Property> propMap = getNodeProps(node); return (propMap != null) ? propMap.get(propName) : null; } @Override public void setNodeProp(Node node, Property prop) { for (int i = 0; i <= REPLACE_RETRY; i++) { /* Get a copy of the property map */ Map<String, Property> propMapCurr = getNodeProps(node); if (propMapCurr == null) { return; } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); propMap.put(prop.getName(), prop); if (nodeProps.replace(node, propMapCurr, propMap)) { return; } } log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID()); } @Override public Status removeNodeProp(Node node, String propName) { for (int i = 0; i <= REPLACE_RETRY; i++) { Map<String, Property> propMapCurr = getNodeProps(node); if (propMapCurr != null) { if (!propMapCurr.containsKey(propName)) { return new Status(StatusCode.SUCCESS); } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); propMap.remove(propName); if (nodeProps.replace(node, propMapCurr, propMap)) { return new Status(StatusCode.SUCCESS); } } else { return new Status(StatusCode.SUCCESS); } } String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID(); return new Status(StatusCode.CONFLICT, msg); } @Override public Status removeNodeAllProps(Node node) { this.nodeProps.remove(node); return new Status(StatusCode.SUCCESS); } @Override public Set<NodeConnector> getUpNodeConnectors(Node node) { if (nodeConnectorProps == null) { return null; } Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (!nodeConnector.getNode().equals(node)) { continue; } if (isNodeConnectorEnabled(nodeConnector)) { nodeConnectorSet.add(nodeConnector); } } return nodeConnectorSet; } @Override public Set<NodeConnector> getNodeConnectors(Node node) { if (nodeConnectorProps == null) { return null; } Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (!nodeConnector.getNode().equals(node)) { continue; } nodeConnectorSet.add(nodeConnector); } return nodeConnectorSet; } @Override public Set<NodeConnector> getPhysicalNodeConnectors(Node node) { if (nodeConnectorProps == null) { return null; } Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (!nodeConnector.getNode().equals(node) || isSpecial(nodeConnector)) { continue; } nodeConnectorSet.add(nodeConnector); } return nodeConnectorSet; } @Override public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) { Map<String, Property> rv = new HashMap<String, Property>(); if (this.nodeConnectorProps != null) { rv = this.nodeConnectorProps.get(nodeConnector); if (rv != null) { rv = new HashMap<String, Property>(rv); } } return rv; } @Override public Property getNodeConnectorProp(NodeConnector nodeConnector, String propName) { Map<String, Property> propMap = getNodeConnectorProps(nodeConnector); return (propMap != null) ? propMap.get(propName) : null; } private byte[] getHardwareMAC() { Enumeration<NetworkInterface> nis; byte[] macAddress = null; try { nis = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { log.error("Failed to acquire controller MAC: ", e); return macAddress; } while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); try { macAddress = ni.getHardwareAddress(); } catch (SocketException e) { log.error("Failed to acquire controller MAC: ", e); } if (macAddress != null && macAddress.length != 0) { break; } } if (macAddress == null) { log.warn("Failed to acquire controller MAC: No physical interface found"); // This happens when running controller on windows VM, for example // Try parsing the OS command output } return macAddress; } @Override public byte[] getControllerMAC() { MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name); return (macProperty == null) ? null : macProperty.getMacAddress(); } @Override public NodeConnector getNodeConnector(Node node, String nodeConnectorName) { if (nodeConnectorNames == null) { return null; } Map<String, NodeConnector> map = nodeConnectorNames.get(node); if (map == null) { return null; } return map.get(nodeConnectorName); } /** * Adds a node connector and its property if any * * @param nodeConnector * {@link org.opendaylight.controller.sal.core.NodeConnector} * @param propName * name of {@link org.opendaylight.controller.sal.core.Property} * @return success or failed reason */ @Override public Status addNodeConnectorProp(NodeConnector nodeConnector, Property prop) { Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector); Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>() : new HashMap<String, Property>(propMapCurr); String msg = "Cluster conflict: Unable to add NodeConnector Property."; // Just add the nodeConnector if prop is not available (in a non-default // container) if (prop == null) { if (propMapCurr == null) { if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) { return new Status(StatusCode.CONFLICT, msg); } } else { if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) { return new Status(StatusCode.CONFLICT, msg); } } return new Status(StatusCode.SUCCESS); } propMap.put(prop.getName(), prop); if (propMapCurr == null) { if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) { return new Status(StatusCode.CONFLICT, msg); } } else { if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) { return new Status(StatusCode.CONFLICT, msg); } } if (prop.getName().equals(Name.NamePropName)) { if (nodeConnectorNames != null) { Node node = nodeConnector.getNode(); Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node); Map<String, NodeConnector> map = new HashMap<String, NodeConnector>(); if (mapCurr != null) { for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) { String s = entry.getKey(); try { map.put(s, new NodeConnector(entry.getValue())); } catch (ConstructionException e) { log.error("An error occured",e); } } } map.put(((Name) prop).getValue(), nodeConnector); if (mapCurr == null) { if (nodeConnectorNames.putIfAbsent(node, map) != null) { // TODO: recovery using Transactionality return new Status(StatusCode.CONFLICT, msg); } } else { if (!nodeConnectorNames.replace(node, mapCurr, map)) { // TODO: recovery using Transactionality return new Status(StatusCode.CONFLICT, msg); } } } } return new Status(StatusCode.SUCCESS); } /** * Removes one property of a node connector * * @param nodeConnector * {@link org.opendaylight.controller.sal.core.NodeConnector} * @param propName * name of {@link org.opendaylight.controller.sal.core.Property} * @return success or failed reason */ @Override public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) { Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector); if (propMapCurr == null) { /* Nothing to remove */ return new Status(StatusCode.SUCCESS); } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); propMap.remove(propName); boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap); String msg = "Cluster conflict: Unable to remove NodeConnector property."; if (!result) { return new Status(StatusCode.CONFLICT, msg); } if (propName.equals(Name.NamePropName)) { if (nodeConnectorNames != null) { Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName)); if (name != null) { Node node = nodeConnector.getNode(); Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node); if (mapCurr != null) { Map<String, NodeConnector> map = new HashMap<String, NodeConnector>(); for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) { String s = entry.getKey(); try { map.put(s, new NodeConnector(entry.getValue())); } catch (ConstructionException e) { log.error("An error occured",e); } } map.remove(name.getValue()); if (!nodeConnectorNames.replace(node, mapCurr, map)) { // TODO: recovery using Transactionality return new Status(StatusCode.CONFLICT, msg); } } } } } return new Status(StatusCode.SUCCESS); } /** * Removes all the properties of a node connector * * @param nodeConnector * {@link org.opendaylight.controller.sal.core.NodeConnector} * @return success or failed reason */ @Override public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) { if (nodeConnectorNames != null) { Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName)); if (name != null) { Node node = nodeConnector.getNode(); Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node); if (mapCurr != null) { Map<String, NodeConnector> map = new HashMap<String, NodeConnector>(); for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) { String s = entry.getKey(); try { map.put(s, new NodeConnector(entry.getValue())); } catch (ConstructionException e) { log.error("An error occured",e); } } map.remove(name.getValue()); if (map.isEmpty()) { nodeConnectorNames.remove(node); } else { if (!nodeConnectorNames.replace(node, mapCurr, map)) { log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.", nodeConnector.getID()); } } } } } nodeConnectorProps.remove(nodeConnector); return new Status(StatusCode.SUCCESS); } /** * Function called by the dependency manager when all the required * dependencies are satisfied * */ void init(Component c) { Dictionary<?, ?> props = c.getServiceProperties(); if (props != null) { this.containerName = (String) props.get("containerName"); log.trace("Running containerName: {}", this.containerName); } else { // In the Global instance case the containerName is empty this.containerName = ""; } isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT .toString()); } /** * Function called by the dependency manager when at least one dependency * become unsatisfied or when the component is shutting down because for * example bundle is being stopped. * */ void destroy() { shutDown(); } /** * Function called by dependency manager after "init ()" is called and after * the services provided by the class are registered in the service registry * */ void start() { startUp(); /* * Read startup and build database if we are the coordinator */ loadSubnetConfiguration(); loadSpanConfiguration(); loadSwitchConfiguration(); // OSGI console registerWithOSGIConsole(); } /** * Function called after registered the service in OSGi service registry. */ void started() { // solicit for existing inventories getInventories(); } /** * Function called by the dependency manager before the services exported by * the component are unregistered, this will be followed by a "destroy ()" * calls * */ void stop() { } public void setConfigurationContainerService(IConfigurationContainerService service) { log.trace("Got configuration service set request {}", service); this.configurationService = service; } public void unsetConfigurationContainerService(IConfigurationContainerService service) { log.trace("Got configuration service UNset request"); this.configurationService = null; } public void setInventoryService(IInventoryService service) { log.trace("Got inventory service set request {}", service); this.inventoryService = service; // solicit for existing inventories getInventories(); } public void unsetInventoryService(IInventoryService service) { log.trace("Got a service UNset request"); this.inventoryService = null; // clear existing inventories clearInventories(); } public void setStatisticsManager(IStatisticsManager statisticsManager) { log.trace("Got statistics manager set request {}", statisticsManager); this.statisticsManager = statisticsManager; } public void unsetStatisticsManager(IStatisticsManager statisticsManager) { log.trace("Got statistics manager UNset request"); this.statisticsManager = null; } public void setSwitchManagerAware(ISwitchManagerAware service) { log.trace("Got inventory service set request {}", service); if (this.switchManagerAware != null) { this.switchManagerAware.add(service); } // bulk update for newly joined switchManagerAwareNotify(service); } public void unsetSwitchManagerAware(ISwitchManagerAware service) { log.trace("Got a service UNset request"); if (this.switchManagerAware != null) { this.switchManagerAware.remove(service); } } public void setInventoryListener(IInventoryListener service) { log.trace("Got inventory listener set request {}", service); if (this.inventoryListeners != null) { this.inventoryListeners.add(service); } // bulk update for newly joined bulkUpdateService(service); } public void unsetInventoryListener(IInventoryListener service) { log.trace("Got a service UNset request"); if (this.inventoryListeners != null) { this.inventoryListeners.remove(service); } } public void setSpanAware(ISpanAware service) { log.trace("Got SpanAware set request {}", service); if (this.spanAware != null) { this.spanAware.add(service); } // bulk update for newly joined spanAwareNotify(service); } public void unsetSpanAware(ISpanAware service) { log.trace("Got a service UNset request"); if (this.spanAware != null) { this.spanAware.remove(service); } } void setClusterContainerService(IClusterContainerServices s) { log.trace("Cluster Service set"); this.clusterContainerService = s; } void unsetClusterContainerService(IClusterContainerServices s) { if (this.clusterContainerService == s) { log.trace("Cluster Service removed!"); this.clusterContainerService = null; } } private void getInventories() { if (inventoryService == null) { log.trace("inventory service not avaiable"); return; } Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps(); for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) { Node node = entry.getKey(); log.debug("getInventories: {} added for container {}", new Object[] { node, containerName }); Map<String, Property> propMap = entry.getValue(); Set<Property> props = new HashSet<Property>(); for (Property property : propMap.values()) { props.add(property); } addNode(node, props); } Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) { Map<String, Property> propMap = entry.getValue(); for (Property property : propMap.values()) { addNodeConnectorProp(entry.getKey(), property); } } } private void clearInventories() { nodeProps.clear(); nodeConnectorProps.clear(); nodeConnectorNames.clear(); spanNodeConnectors.clear(); } private void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) { synchronized (inventoryListeners) { for (IInventoryListener service : inventoryListeners) { service.notifyNode(node, type, propMap); } } } private void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) { synchronized (inventoryListeners) { for (IInventoryListener service : inventoryListeners) { service.notifyNodeConnector(nodeConnector, type, propMap); } } } /* * For those joined late, bring them up-to-date. */ private void switchManagerAwareNotify(ISwitchManagerAware service) { for (Subnet sub : subnets.values()) { service.subnetNotify(sub, true); } for (Node node : getNodes()) { SwitchConfig sc = getSwitchConfig(node.toString()); if ((sc != null) && isDefaultContainer) { ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name); service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive()); } } } private void bulkUpdateService(IInventoryListener service) { Map<String, Property> propMap; UpdateType type = UpdateType.ADDED; for (Node node : getNodes()) { propMap = nodeProps.get(node); service.notifyNode(node, type, propMap); } for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); propMap = nodeConnectorProps.get(nodeConnector); service.notifyNodeConnector(nodeConnector, type, propMap); } } private void spanAwareNotify(ISpanAware service) { for (Node node : getNodes()) { for (SpanConfig conf : getSpanConfigList(node)) { service.spanUpdate(node, conf.getPortArrayList(), true); } } } private void registerWithOSGIConsole() { BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) .getBundleContext(); bundleContext.registerService(CommandProvider.class.getName(), this, null); } @Override public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) { if (nodeConnector == null) { return false; } Config config = (Config) getNodeConnectorProp(nodeConnector, Config.ConfigPropName); State state = (State) getNodeConnectorProp(nodeConnector, State.StatePropName); return ((config != null) && (config.getValue() == Config.ADMIN_UP) && (state != null) && (state.getValue() == State.EDGE_UP)); } @Override public boolean doesNodeConnectorExist(NodeConnector nc) { return (nc != null && nodeConnectorProps != null && nodeConnectorProps.containsKey(nc)); } @Override public String getHelp() { StringBuffer help = new StringBuffer(); help.append(" help.append("\t pencs <node id> - Print enabled node connectors for a given node\n"); help.append("\t pdm <node id> - Print switch ports in device map\n"); return help.toString(); } public void _pencs(CommandInterpreter ci) { String st = ci.nextArgument(); if (st == null) { ci.println("Please enter node id"); return; } Node node = Node.fromString(st); if (node == null) { ci.println("Please enter node id"); return; } Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node); if (nodeConnectorSet == null) { return; } for (NodeConnector nodeConnector : nodeConnectorSet) { if (nodeConnector == null) { continue; } ci.println(nodeConnector); } ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size()); } public void _pdm(CommandInterpreter ci) { String st = ci.nextArgument(); if (st == null) { ci.println("Please enter node id"); return; } Node node = Node.fromString(st); if (node == null) { ci.println("Please enter node id"); return; } Switch sw = getSwitchByNode(node); ci.println(" NodeConnector Name"); Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors(); String nodeConnectorName; if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) { for (NodeConnector nodeConnector : nodeConnectorSet) { Map<String, Property> propMap = getNodeConnectorProps(nodeConnector); nodeConnectorName = (propMap == null) ? null : ((Name) propMap .get(Name.NamePropName)).getValue(); if (nodeConnectorName != null) { Node nd = nodeConnector.getNode(); if (!nd.equals(node)) { log.debug("node not match {} {}", nd, node); } Map<String, NodeConnector> map = nodeConnectorNames .get(node); if (map != null) { NodeConnector nc = map.get(nodeConnectorName); if (nc == null) { log.debug("no nodeConnector named {}", nodeConnectorName); } else if (!nc.equals(nodeConnector)) { log.debug("nodeConnector not match {} {}", nc, nodeConnector); } } } ci.println(nodeConnector + " " + ((nodeConnectorName == null) ? "" : nodeConnectorName) + "(" + nodeConnector.getID() + ")"); } ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size()); } } @Override public byte[] getNodeMAC(Node node) { MacAddress mac = (MacAddress) this.getNodeProp(node, MacAddress.name); return (mac != null) ? mac.getMacAddress() : null; } @Override public boolean isSpecial(NodeConnector p) { if (p.getType().equals(NodeConnectorIDType.CONTROLLER) || p.getType().equals(NodeConnectorIDType.ALL) || p.getType().equals(NodeConnectorIDType.SWSTACK) || p.getType().equals(NodeConnectorIDType.HWPATH)) { return true; } return false; } /* * Add span configuration to local cache and notify clients */ private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) { List<NodeConnector> ncLists = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : nodeConnectors) { if (!spanNodeConnectors.contains(nodeConnector)) { ncLists.add(nodeConnector); } } if (ncLists.size() > 0) { spanNodeConnectors.addAll(ncLists); notifySpanPortChange(node, ncLists, true); } } private void addSpanPorts(Node node) { for (SpanConfig conf : getSpanConfigList(node)) { addSpanPorts(node, conf.getPortArrayList()); } } private void addSpanPort(NodeConnector nodeConnector) { // only add if span is configured on this nodeConnector for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) { if (conf.getPortArrayList().contains(nodeConnector)) { List<NodeConnector> ncLists = new ArrayList<NodeConnector>(); ncLists.add(nodeConnector); addSpanPorts(nodeConnector.getNode(), ncLists); return; } } } /* * Remove span configuration to local cache and notify clients */ private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) { List<NodeConnector> ncLists = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : nodeConnectors) { if (spanNodeConnectors.contains(nodeConnector)) { ncLists.add(nodeConnector); } } if (ncLists.size() > 0) { spanNodeConnectors.removeAll(ncLists); notifySpanPortChange(node, ncLists, false); } } private void removeSpanPorts(Node node) { for (SpanConfig conf : getSpanConfigList(node)) { addSpanPorts(node, conf.getPortArrayList()); } } private void removeSpanPort(NodeConnector nodeConnector) { if (spanNodeConnectors.contains(nodeConnector)) { List<NodeConnector> ncLists = new ArrayList<NodeConnector>(); ncLists.add(nodeConnector); removeSpanPorts(nodeConnector.getNode(), ncLists); } } private void addNodeProps(Node node, Map<String, Property> propMap) { if (propMap == null) { propMap = new HashMap<String, Property>(); } nodeProps.put(node, propMap); } @Override public Status saveConfiguration() { return saveSwitchConfig(); } /** * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property * object based on given property name and value. Other property types are * not supported yet. * * @param propName * Name of the Property * @param propValue * Value of the Property * @return {@link org.opendaylight.controller.sal.core.Property} */ @Override public Property createProperty(String propName, String propValue) { if (propName == null) { log.debug("propName is null"); return null; } if (propValue == null) { log.debug("propValue is null"); return null; } try { if (propName.equalsIgnoreCase(Description.propertyName)) { return new Description(propValue); } else if (propName.equalsIgnoreCase(Tier.TierPropName)) { int tier = Integer.parseInt(propValue); return new Tier(tier); } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) { long bw = Long.parseLong(propValue); return new Bandwidth(bw); } else if (propName.equalsIgnoreCase(ForwardingMode.name)) { int mode = Integer.parseInt(propValue); return new ForwardingMode(mode); } else if (propName.equalsIgnoreCase(MacAddress.name)){ return new MacAddress(propValue); } else { log.debug("Not able to create {} property", propName); } } catch (Exception e) { log.debug("createProperty caught exception {}", e.getMessage()); } return null; } @SuppressWarnings("deprecation") @Override public String getNodeDescription(Node node) { // Check first if user configured a name SwitchConfig config = getSwitchConfig(node.toString()); if (config != null) { String configuredDesc = config.getNodeDescription(); if (configuredDesc != null && !configuredDesc.isEmpty()) { return configuredDesc; } } // No name configured by user, get the node advertised name Description desc = (Description) getNodeProp(node, Description.propertyName); return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? "" : desc.getValue(); } @Override public Set<Switch> getConfiguredNotConnectedSwitches() { Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>(); if (this.inventoryService == null) { log.trace("inventory service not avaiable"); return configuredNotConnectedSwitches; } Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes(); if (configuredNotConnectedNodes != null) { for (Node node : configuredNotConnectedNodes) { Switch sw = getSwitchByNode(node); configuredNotConnectedSwitches.add(sw); } } return configuredNotConnectedSwitches; } }
package org.opendaylight.controller.switchmanager.internal; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.felix.dm.Component; import org.eclipse.osgi.framework.console.CommandInterpreter; import org.eclipse.osgi.framework.console.CommandProvider; import org.opendaylight.controller.clustering.services.CacheConfigException; import org.opendaylight.controller.clustering.services.CacheExistException; import org.opendaylight.controller.clustering.services.IClusterContainerServices; import org.opendaylight.controller.clustering.services.IClusterServices; import org.opendaylight.controller.configuration.ConfigurationObject; import org.opendaylight.controller.configuration.IConfigurationContainerAware; import org.opendaylight.controller.configuration.IConfigurationContainerService; import org.opendaylight.controller.sal.core.Bandwidth; import org.opendaylight.controller.sal.core.Config; import org.opendaylight.controller.sal.core.ConstructionException; import org.opendaylight.controller.sal.core.Description; import org.opendaylight.controller.sal.core.ForwardingMode; import org.opendaylight.controller.sal.core.MacAddress; import org.opendaylight.controller.sal.core.Name; import org.opendaylight.controller.sal.core.Node; import org.opendaylight.controller.sal.core.NodeConnector; import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; import org.opendaylight.controller.sal.core.Property; import org.opendaylight.controller.sal.core.State; import org.opendaylight.controller.sal.core.Tier; import org.opendaylight.controller.sal.core.UpdateType; import org.opendaylight.controller.sal.inventory.IInventoryService; import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; import org.opendaylight.controller.sal.reader.NodeDescription; import org.opendaylight.controller.sal.utils.GlobalConstants; import org.opendaylight.controller.sal.utils.IObjectReader; import org.opendaylight.controller.sal.utils.ServiceHelper; import org.opendaylight.controller.sal.utils.Status; import org.opendaylight.controller.sal.utils.StatusCode; import org.opendaylight.controller.statisticsmanager.IStatisticsManager; import org.opendaylight.controller.switchmanager.IInventoryListener; import org.opendaylight.controller.switchmanager.ISpanAware; import org.opendaylight.controller.switchmanager.ISwitchManager; import org.opendaylight.controller.switchmanager.ISwitchManagerAware; import org.opendaylight.controller.switchmanager.SpanConfig; import org.opendaylight.controller.switchmanager.Subnet; import org.opendaylight.controller.switchmanager.SubnetConfig; import org.opendaylight.controller.switchmanager.Switch; import org.opendaylight.controller.switchmanager.SwitchConfig; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class describes SwitchManager which is the central repository of all the * inventory data including nodes, node connectors, properties attached, Layer3 * configurations, Span configurations, node configurations, network device * representations viewed by Controller Web applications. One SwitchManager * instance per container of the network. All the node/nodeConnector properties * are maintained in the default container only. */ public class SwitchManager implements ISwitchManager, IConfigurationContainerAware, IObjectReader, IListenInventoryUpdates, CommandProvider { private static Logger log = LoggerFactory.getLogger(SwitchManager.class); private static final String SUBNETS_FILE_NAME = "subnets.conf"; private static final String SPAN_FILE_NAME = "spanPorts.conf"; private static final String SWITCH_CONFIG_FILE_NAME = "switchConfig.conf"; private final List<NodeConnector> spanNodeConnectors = new CopyOnWriteArrayList<NodeConnector>(); // Collection of Subnets keyed by the InetAddress private ConcurrentMap<InetAddress, Subnet> subnets; private ConcurrentMap<String, SubnetConfig> subnetsConfigList; private ConcurrentMap<SpanConfig, SpanConfig> spanConfigList; // manually configured parameters for the node such as name, tier, mode private ConcurrentMap<String, SwitchConfig> nodeConfigList; private ConcurrentMap<Node, Map<String, Property>> nodeProps; private ConcurrentMap<NodeConnector, Map<String, Property>> nodeConnectorProps; private ConcurrentMap<Node, Map<String, NodeConnector>> nodeConnectorNames; private ConcurrentMap<String, Property> controllerProps; private IInventoryService inventoryService; private IStatisticsManager statisticsManager; private IControllerProperties controllerProperties; private IConfigurationContainerService configurationService; private final Set<ISwitchManagerAware> switchManagerAware = Collections .synchronizedSet(new HashSet<ISwitchManagerAware>()); private final Set<IInventoryListener> inventoryListeners = Collections .synchronizedSet(new HashSet<IInventoryListener>()); private final Set<ISpanAware> spanAware = Collections.synchronizedSet(new HashSet<ISpanAware>()); private IClusterContainerServices clusterContainerService = null; private String containerName = null; private boolean isDefaultContainer = true; private static final int REPLACE_RETRY = 1; /* Information about the default subnet. If there have been no configured subnets, i.e., * subnets.size() == 0 or subnetsConfigList.size() == 0, then this subnet will be the * only subnet returned. As soon as a user-configured subnet is created this one will * vanish. */ private static final String DISABLE_DEFAULT_SUBNET_PROP = "switchmanager.disableDefaultSubnetGateway"; private static final String DISABLE_DEFAULT_SUBNET_PROP_VAL = System.getProperty(DISABLE_DEFAULT_SUBNET_PROP); private static final boolean USE_DEFAULT_SUBNET_GW = !Boolean.valueOf(DISABLE_DEFAULT_SUBNET_PROP_VAL); protected static final SubnetConfig DEFAULT_SUBNETCONFIG; protected static final Subnet DEFAULT_SUBNET; protected static final String DEFAULT_SUBNET_NAME = "default (cannot be modifed)"; static{ DEFAULT_SUBNETCONFIG = new SubnetConfig(DEFAULT_SUBNET_NAME, "0.0.0.0/0", new ArrayList<String>()); DEFAULT_SUBNET = new Subnet(DEFAULT_SUBNETCONFIG); } public void notifySubnetChange(Subnet sub, boolean add) { synchronized (switchManagerAware) { for (Object subAware : switchManagerAware) { try { ((ISwitchManagerAware) subAware).subnetNotify(sub, add); } catch (Exception e) { log.error("Failed to notify Subnet change {}", e.getMessage()); } } } } public void notifySpanPortChange(Node node, List<NodeConnector> ports, boolean add) { synchronized (spanAware) { for (Object sa : spanAware) { try { ((ISpanAware) sa).spanUpdate(node, ports, add); } catch (Exception e) { log.error("Failed to notify Span Interface change {}", e.getMessage()); } } } } private void notifyModeChange(Node node, boolean proactive) { synchronized (switchManagerAware) { for (ISwitchManagerAware service : switchManagerAware) { try { service.modeChangeNotify(node, proactive); } catch (Exception e) { log.error("Failed to notify Subnet change {}", e.getMessage()); } } } } public void startUp() { // Instantiate cluster synced variables allocateCaches(); retrieveCaches(); // Add controller MAC, if first node in the cluster if ((!controllerProps.containsKey(MacAddress.name)) && (controllerProperties != null)) { Property controllerMac = controllerProperties.getControllerProperty(MacAddress.name); if (controllerMac != null) { Property existing = controllerProps.putIfAbsent(MacAddress.name, controllerMac); if (existing == null && log.isTraceEnabled()) { log.trace("Container {}: Setting controller MAC address in the cluster: {}", getContainerName(), controllerMac); } } } } public void shutDown() { } private void allocateCaches() { if (this.clusterContainerService == null) { this.nonClusterObjectCreate(); log.warn("un-initialized clusterContainerService, can't create cache"); return; } try { clusterContainerService.createCache( "switchmanager.subnetsConfigList", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.spanConfigList", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.nodeConfigList", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.subnets", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache("switchmanager.nodeProps", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache( "switchmanager.nodeConnectorProps", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache( "switchmanager.nodeConnectorNames", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); clusterContainerService.createCache( "switchmanager.controllerProps", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); } catch (CacheConfigException cce) { log.error("\nCache configuration invalid - check cache mode"); } catch (CacheExistException ce) { log.error("\nCache already exits - destroy and recreate if needed"); } } @SuppressWarnings({ "unchecked" }) private void retrieveCaches() { if (this.clusterContainerService == null) { log.warn("un-initialized clusterContainerService, can't create cache"); return; } subnetsConfigList = (ConcurrentMap<String, SubnetConfig>) clusterContainerService .getCache("switchmanager.subnetsConfigList"); if (subnetsConfigList == null) { log.error("\nFailed to get cache for subnetsConfigList"); } spanConfigList = (ConcurrentMap<SpanConfig, SpanConfig>) clusterContainerService .getCache("switchmanager.spanConfigList"); if (spanConfigList == null) { log.error("\nFailed to get cache for spanConfigList"); } nodeConfigList = (ConcurrentMap<String, SwitchConfig>) clusterContainerService .getCache("switchmanager.nodeConfigList"); if (nodeConfigList == null) { log.error("\nFailed to get cache for nodeConfigList"); } subnets = (ConcurrentMap<InetAddress, Subnet>) clusterContainerService .getCache("switchmanager.subnets"); if (subnets == null) { log.error("\nFailed to get cache for subnets"); } nodeProps = (ConcurrentMap<Node, Map<String, Property>>) clusterContainerService .getCache("switchmanager.nodeProps"); if (nodeProps == null) { log.error("\nFailed to get cache for nodeProps"); } nodeConnectorProps = (ConcurrentMap<NodeConnector, Map<String, Property>>) clusterContainerService .getCache("switchmanager.nodeConnectorProps"); if (nodeConnectorProps == null) { log.error("\nFailed to get cache for nodeConnectorProps"); } nodeConnectorNames = (ConcurrentMap<Node, Map<String, NodeConnector>>) clusterContainerService .getCache("switchmanager.nodeConnectorNames"); if (nodeConnectorNames == null) { log.error("\nFailed to get cache for nodeConnectorNames"); } controllerProps = (ConcurrentMap<String, Property>) clusterContainerService .getCache("switchmanager.controllerProps"); if (controllerProps == null) { log.error("\nFailed to get cache for controllerProps"); } } private void nonClusterObjectCreate() { subnetsConfigList = new ConcurrentHashMap<String, SubnetConfig>(); spanConfigList = new ConcurrentHashMap<SpanConfig, SpanConfig>(); nodeConfigList = new ConcurrentHashMap<String, SwitchConfig>(); subnets = new ConcurrentHashMap<InetAddress, Subnet>(); nodeProps = new ConcurrentHashMap<Node, Map<String, Property>>(); nodeConnectorProps = new ConcurrentHashMap<NodeConnector, Map<String, Property>>(); nodeConnectorNames = new ConcurrentHashMap<Node, Map<String, NodeConnector>>(); controllerProps = new ConcurrentHashMap<String, Property>(); } @Override public List<SubnetConfig> getSubnetsConfigList() { // if there are no subnets, return the default subnet if (USE_DEFAULT_SUBNET_GW && subnetsConfigList.isEmpty()) { return Collections.singletonList(DEFAULT_SUBNETCONFIG); } else { return new ArrayList<SubnetConfig>(subnetsConfigList.values()); } } @Override public SubnetConfig getSubnetConfig(String subnet) { // if there are no subnets, return the default subnet if (USE_DEFAULT_SUBNET_GW && subnetsConfigList.isEmpty() && subnet.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) { return DEFAULT_SUBNETCONFIG; } else { return subnetsConfigList.get(subnet); } } private List<SpanConfig> getSpanConfigList(Node node) { List<SpanConfig> confList = new ArrayList<SpanConfig>(); String nodeId = node.toString(); for (SpanConfig conf : spanConfigList.values()) { if (conf.matchNode(nodeId)) { confList.add(conf); } } return confList; } public List<SwitchConfig> getNodeConfigList() { return new ArrayList<SwitchConfig>(nodeConfigList.values()); } @Override public SwitchConfig getSwitchConfig(String switchId) { return nodeConfigList.get(switchId); } public Switch getSwitchByNode(Node node) { Switch sw = new Switch(node); sw.setNode(node); MacAddress mac = (MacAddress) this.getNodeProp(node, MacAddress.name); if (mac != null) { sw.setDataLayerAddress(mac.getMacAddress()); } Set<NodeConnector> ncSet = getPhysicalNodeConnectors(node); sw.setNodeConnectors(ncSet); List<NodeConnector> ncList = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : ncSet) { if (spanNodeConnectors.contains(nodeConnector)) { ncList.add(nodeConnector); } } sw.addSpanPorts(ncList); return sw; } @Override public List<Switch> getNetworkDevices() { List<Switch> swList = new ArrayList<Switch>(); for (Node node : getNodes()) { swList.add(getSwitchByNode(node)); } return swList; } private Status updateConfig(SubnetConfig conf, boolean add) { if (add) { if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) { String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists."; return new Status(StatusCode.CONFLICT, msg); } } else { subnetsConfigList.remove(conf.getName()); } return new Status(StatusCode.SUCCESS); } private Status updateDatabase(SubnetConfig conf, boolean add) { if (add) { Subnet subnetCurr = subnets.get(conf.getIPAddress()); Subnet subnet; if (subnetCurr == null) { subnet = new Subnet(conf); } else { subnet = subnetCurr.clone(); } // In case of API3 call we may receive the ports along with the // subnet creation if (!conf.isGlobal()) { subnet.addNodeConnectors(conf.getNodeConnectors()); } boolean putNewSubnet = false; if(subnetCurr == null) { if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) { putNewSubnet = true; } } else { putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet); } if(!putNewSubnet) { String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress(); return new Status(StatusCode.CONFLICT, msg); } // Subnet removal case } else { subnets.remove(conf.getIPAddress()); } return new Status(StatusCode.SUCCESS); } private Status semanticCheck(SubnetConfig conf) { Set<InetAddress> IPs = subnets.keySet(); if (IPs == null) { return new Status(StatusCode.SUCCESS); } Subnet newSubnet = new Subnet(conf); for (InetAddress i : IPs) { Subnet existingSubnet = subnets.get(i); if ((existingSubnet != null) && !existingSubnet.isMutualExclusive(newSubnet)) { return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one."); } } return new Status(StatusCode.SUCCESS); } private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) { // Valid configuration check Status status = conf.validate(); if (!status.isSuccess()) { log.warn(status.getDescription()); return status; } if (isAdding) { // Presence check if (subnetsConfigList.containsKey(conf.getName())) { return new Status(StatusCode.CONFLICT, "Subnet with the specified name already exists."); } // Semantic check status = semanticCheck(conf); if (!status.isSuccess()) { return status; } } else { if (conf.getName().equalsIgnoreCase(DEFAULT_SUBNET_NAME)) { return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed"); } } // Update Database status = updateDatabase(conf, isAdding); if (status.isSuccess()) { // Update Configuration status = updateConfig(conf, isAdding); if(!status.isSuccess()) { updateDatabase(conf, (!isAdding)); } else { // update the listeners Subnet subnetCurr = subnets.get(conf.getIPAddress()); Subnet subnet; if (subnetCurr == null) { subnet = new Subnet(conf); } else { subnet = subnetCurr.clone(); } notifySubnetChange(subnet, isAdding); } } return status; } /** * Adds Subnet configured in GUI or API3 */ @Override public Status addSubnet(SubnetConfig conf) { return this.addRemoveSubnet(conf, true); } @Override public Status removeSubnet(SubnetConfig conf) { return this.addRemoveSubnet(conf, false); } @Override public Status removeSubnet(String name) { if (name.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) { return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed"); } SubnetConfig conf = subnetsConfigList.get(name); if (conf == null) { return new Status(StatusCode.SUCCESS, "Subnet not present"); } return this.addRemoveSubnet(conf, false); } @Override public Status modifySubnet(SubnetConfig conf) { // Sanity check if (conf == null) { return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null"); } // Valid configuration check Status status = conf.validate(); if (!status.isSuccess()) { log.warn(status.getDescription()); return status; } // If a subnet configuration with this name does not exist, consider this is a creation SubnetConfig target = subnetsConfigList.get(conf.getName()); if (target == null) { return this.addSubnet(conf); } // No change if (target.equals(conf)) { return new Status(StatusCode.SUCCESS); } // Check not allowed modifications if (!target.getSubnet().equals(conf.getSubnet())) { return new Status(StatusCode.BADREQUEST, "IP address change is not allowed"); } // Derive the set of node connectors that are being removed Set<NodeConnector> toRemove = target.getNodeConnectors(); toRemove.removeAll(conf.getNodeConnectors()); List<String> nodeConnectorStrings = null; if (!toRemove.isEmpty()) { nodeConnectorStrings = new ArrayList<String>(); for (NodeConnector nc : toRemove) { nodeConnectorStrings.add(nc.toString()); } status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings); if (!status.isSuccess()) { return status; } } // Derive the set of node connectors that are being added Set<NodeConnector> toAdd = conf.getNodeConnectors(); toAdd.removeAll(target.getNodeConnectors()); if (!toAdd.isEmpty()) { List<String> nodeConnectorStringRemoved = nodeConnectorStrings; nodeConnectorStrings = new ArrayList<String>(); for (NodeConnector nc : toAdd) { nodeConnectorStrings.add(nc.toString()); } status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings); if (!status.isSuccess()) { // If any port was removed, add it back as a best recovery effort if (!toRemove.isEmpty()) { this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved); } return status; } } // Update Configuration subnetsConfigList.put(conf.getName(), conf); return new Status(StatusCode.SUCCESS); } @Override public Status addPortsToSubnet(String name, List<String> switchPorts) { if (name == null) { return new Status(StatusCode.BADREQUEST, "Null subnet name"); } SubnetConfig confCurr = subnetsConfigList.get(name); if (confCurr == null) { return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } if (switchPorts == null || switchPorts.isEmpty()) { return new Status(StatusCode.BADREQUEST, "Null or empty port set"); } Subnet subCurr = subnets.get(confCurr.getIPAddress()); if (subCurr == null) { log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress()); return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } // Update Database Subnet sub = subCurr.clone(); Set<NodeConnector> sp = NodeConnector.fromString(switchPorts); sub.addNodeConnectors(sp); boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub); if (!subnetsReplaced) { String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name; return new Status(StatusCode.CONFLICT, msg); } // Update Configuration SubnetConfig conf = confCurr.clone(); conf.addNodeConnectors(switchPorts); boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf); if (!configReplaced) { // TODO: recovery using Transactionality String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name; return new Status(StatusCode.CONFLICT, msg); } return new Status(StatusCode.SUCCESS); } @Override public Status removePortsFromSubnet(String name, List<String> switchPorts) { if (name == null) { return new Status(StatusCode.BADREQUEST, "Null subnet name"); } SubnetConfig confCurr = subnetsConfigList.get(name); if (confCurr == null) { return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } if (switchPorts == null || switchPorts.isEmpty()) { return new Status(StatusCode.BADREQUEST, "Null or empty port set"); } Subnet subCurr = subnets.get(confCurr.getIPAddress()); if (subCurr == null) { log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress()); return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); } // Validation check Status status = SubnetConfig.validatePorts(switchPorts); if (!status.isSuccess()) { return status; } // Update Database Subnet sub = subCurr.clone(); Set<NodeConnector> sp = NodeConnector.fromString(switchPorts); sub.deleteNodeConnectors(sp); boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub); if (!subnetsReplace) { String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name; return new Status(StatusCode.CONFLICT, msg); } // Update Configuration SubnetConfig conf = confCurr.clone(); conf.removeNodeConnectors(switchPorts); boolean result = subnetsConfigList.replace(name, confCurr, conf); if (!result) { // TODO: recovery using Transactionality String msg = "Cluster conflict: Conflict while removing ports from " + conf; return new Status(StatusCode.CONFLICT, msg); } return new Status(StatusCode.SUCCESS); } public String getContainerName() { if (containerName == null) { return GlobalConstants.DEFAULT.toString(); } return containerName; } @Override public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) { // if there are no subnets, return the default subnet if (subnets.size() == 0) { return DEFAULT_SUBNET; } for(Map.Entry<InetAddress,Subnet> subnetEntry : subnets.entrySet()) { if(subnetEntry.getValue().isSubnetOf(networkAddress)) { return subnetEntry.getValue(); } } return null; } @Override public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException { // Perform the class deserialization locally, from inside the package // where the class is defined return ois.readObject(); } private void loadSubnetConfiguration() { for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SUBNETS_FILE_NAME)) { addSubnet((SubnetConfig) conf); } } private void loadSpanConfiguration() { for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SPAN_FILE_NAME)) { addSpanConfig((SpanConfig) conf); } } private void loadSwitchConfiguration() { for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SWITCH_CONFIG_FILE_NAME)) { updateNodeConfig((SwitchConfig) conf); } } @SuppressWarnings("deprecation") @Override public void updateSwitchConfig(SwitchConfig cfgObject) { // update default container only if (!isDefaultContainer) { return; } SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId()); if (sc == null) { if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) { return; } } else { if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) { return; } } boolean modeChange = false; if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) { modeChange = true; } String nodeId = cfgObject.getNodeId(); Node node = Node.fromString(nodeId); Map<String, Property> propMapCurr = nodeProps.get(node); if (propMapCurr == null) { return; } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); Property desc = new Description(cfgObject.getNodeDescription()); propMap.put(desc.getName(), desc); Property tier = new Tier(Integer.parseInt(cfgObject.getTier())); propMap.put(tier.getName(), tier); if (!nodeProps.replace(node, propMapCurr, propMap)) { // TODO rollback using Transactionality return; } log.trace("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode()); if (modeChange) { notifyModeChange(node, cfgObject.isProactive()); } } @Override public Status updateNodeConfig(SwitchConfig switchConfig) { Status status = switchConfig.validate(); if (!status.isSuccess()) { return status; } Map<String, Property> updateProperties = switchConfig.getNodeProperties(); ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name); if (mode != null) { if (isDefaultContainer) { if (!mode.isValid()) { return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value"); } } else { return new Status(StatusCode.NOTACCEPTABLE, "Forwarding Mode modification is allowed only in default container"); } } Description description = (Description) switchConfig.getProperty(Description.propertyName); String nodeId = switchConfig.getNodeId(); Node node = Node.fromString(nodeId); NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager .getNodeDescription(node); String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription(); if (description != null && description.getValue() != null) { if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) { updateProperties.remove(Description.propertyName); switchConfig = new SwitchConfig(nodeId, updateProperties); } else { // check if description is configured or was published by any other node for (Map.Entry<Node, Map<String, Property>> entry : nodeProps.entrySet()) { Node n = entry.getKey(); Description desc = (Description) getNodeProp(n, Description.propertyName); NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager .getNodeDescription(n); String advDesc = (nDesc == null) ? "" : nDesc.getDescription(); if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) { return new Status(StatusCode.CONFLICT, "Node name already in use"); } } } } boolean modeChange = false; SwitchConfig sc = nodeConfigList.get(nodeId); Map<String, Property> prevNodeProperties = new HashMap<String, Property>(); if (sc == null) { if ((mode != null) && mode.isProactive()) { modeChange = true; } if (!updateProperties.isEmpty()) { if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) { return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); } } } else { prevNodeProperties = new HashMap<String, Property>(sc.getNodeProperties()); ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name); if (mode == null) { if ((prevMode != null) && (prevMode.isProactive())) { modeChange = true; } } else { if (((prevMode != null) && (prevMode.getValue() != mode.getValue())) || (prevMode == null && mode.isProactive())) { modeChange = true; } } if (updateProperties.isEmpty()) { nodeConfigList.remove(nodeId); } else { if (!nodeConfigList.replace(nodeId, sc, switchConfig)) { return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); } } } Map<String, Property> propMapCurr = nodeProps.get(node); if (propMapCurr == null) { return new Status(StatusCode.SUCCESS); } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); for (Map.Entry<String, Property> entry : prevNodeProperties.entrySet()) { String prop = entry.getKey(); if (!updateProperties.containsKey(prop)) { if (prop.equals(Description.propertyName)) { if (advertisedDesc != null) { if (!advertisedDesc.isEmpty()) { Property desc = new Description(advertisedDesc); propMap.put(Description.propertyName, desc); } } else { propMap.remove(prop); } continue; } else if (prop.equals(ForwardingMode.name)) { Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING); propMap.put(ForwardingMode.name, defaultMode); continue; } propMap.remove(prop); } } propMap.putAll(updateProperties); if (!nodeProps.replace(node, propMapCurr, propMap)) { // TODO rollback using Transactionality return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); } if (modeChange) { notifyModeChange(node, (mode == null) ? false : mode.isProactive()); } return new Status(StatusCode.SUCCESS); } @Override public Status removeNodeConfig(String nodeId) { if ((nodeId == null) || (nodeId.isEmpty())) { return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty."); } Map<String, Property> nodeProperties = getSwitchConfig(nodeId).getNodeProperties(); Node node = Node.fromString(nodeId); Map<String, Property> propMapCurr = nodeProps.get(node); if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) { Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); for (Map.Entry<String, Property> entry : nodeProperties.entrySet()) { String prop = entry.getKey(); if (prop.equals(Description.propertyName)) { Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps(); if (nodeProp.get(node) != null) { propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName)); continue; } } propMap.remove(prop); } if (!nodeProps.replace(node, propMapCurr, propMap)) { return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration."); } } if (nodeConfigList != null) { nodeConfigList.remove(nodeId); } return new Status(StatusCode.SUCCESS); } @Override public Status saveSwitchConfig() { return saveSwitchConfigInternal(); } public Status saveSwitchConfigInternal() { Status status; short number = 0; status = configurationService.persistConfiguration( new ArrayList<ConfigurationObject>(subnetsConfigList.values()), SUBNETS_FILE_NAME); if (status.isSuccess()) { number++; } else { log.warn("Failed to save subnet gateway configurations: " + status.getDescription()); } status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(spanConfigList.values()), SPAN_FILE_NAME); if (status.isSuccess()) { number++; } else { log.warn("Failed to save span port configurations: " + status.getDescription()); } status = configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(nodeConfigList.values()), SWITCH_CONFIG_FILE_NAME); if (status.isSuccess()) { number++; } else { log.warn("Failed to save node configurations: " + status.getDescription()); } if (number == 0) { return new Status(StatusCode.INTERNALERROR, "Save failed"); } if (number < 3) { return new Status(StatusCode.INTERNALERROR, "Partial save failure"); } return status; } @Override public List<SpanConfig> getSpanConfigList() { return new ArrayList<SpanConfig>(spanConfigList.values()); } @Override public Status addSpanConfig(SpanConfig conf) { // Valid config check if (!conf.isValidConfig()) { String msg = "Invalid Span configuration"; log.warn(msg); return new Status(StatusCode.BADREQUEST, msg); } // Presence check if (spanConfigList.containsKey(conf)) { return new Status(StatusCode.CONFLICT, "Same span config exists"); } // Update configuration if (spanConfigList.putIfAbsent(conf, conf) == null) { // Update database and notify clients addSpanPorts(conf.getNode(), conf.getPortArrayList()); } return new Status(StatusCode.SUCCESS); } @Override public Status removeSpanConfig(SpanConfig conf) { removeSpanPorts(conf.getNode(), conf.getPortArrayList()); // Update configuration spanConfigList.remove(conf); return new Status(StatusCode.SUCCESS); } @Override public List<NodeConnector> getSpanPorts(Node node) { List<NodeConnector> ncList = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : spanNodeConnectors) { if (nodeConnector.getNode().equals(node)) { ncList.add(nodeConnector); } } return ncList; } private void addNode(Node node, Set<Property> props) { log.trace("{} added, props: {}", node, props); if (nodeProps == null) { return; } Map<String, Property> propMapCurr = nodeProps.get(node); Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>() : new HashMap<String, Property>(propMapCurr); // copy node properties from plugin if (props != null) { for (Property prop : props) { propMap.put(prop.getName(), prop); } } boolean forwardingModeChanged = false; // copy node properties from config if (nodeConfigList != null) { String nodeId = node.toString(); SwitchConfig conf = nodeConfigList.get(nodeId); if (conf != null && (conf.getNodeProperties() != null)) { Map<String, Property> nodeProperties = conf.getNodeProperties(); propMap.putAll(nodeProperties); if (nodeProperties.get(ForwardingMode.name) != null) { ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name); forwardingModeChanged = mode.isProactive(); } } else if ((conf == null) && !(GlobalConstants.DEFAULT.toString().equals(containerName))) { ISwitchManager defaultSwitchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, GlobalConstants.DEFAULT.toString(), this); if (defaultSwitchManager != null) { Property defaultContainerSwitchDesc = (Description) defaultSwitchManager.getNodeProp(node, Description.propertyName); if (defaultContainerSwitchDesc != null) { Map<String, Property> descPropMap = new HashMap<String, Property>(); descPropMap.put(Description.propertyName, defaultContainerSwitchDesc); conf = new SwitchConfig(nodeId, descPropMap); updateNodeConfig(conf); propMap.put(Description.propertyName, defaultContainerSwitchDesc); } } } } if (!propMap.containsKey(ForwardingMode.name)) { Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING); propMap.put(ForwardingMode.name, defaultMode); } boolean propsAdded = false; // Attempt initial add if (nodeProps.putIfAbsent(node, propMap) == null) { propsAdded = true; /* Notify listeners only for initial node addition * to avoid expensive tasks triggered by redundant notifications */ notifyNode(node, UpdateType.ADDED, propMap); } else { propsAdded = nodeProps.replace(node, propMapCurr, propMap); // check whether forwarding mode changed if (propMapCurr.get(ForwardingMode.name) != null) { ForwardingMode mode = (ForwardingMode) propMapCurr.get(ForwardingMode.name); forwardingModeChanged ^= mode.isProactive(); } } if (!propsAdded) { log.debug("Cluster conflict while adding node {}. Overwriting with latest props: {}", node.getID(), props); addNodeProps(node, propMap); } // check if span ports are configured addSpanPorts(node); // notify proactive mode forwarding if (forwardingModeChanged) { notifyModeChange(node, true); } } private void removeNode(Node node) { log.trace("{} removed", node); if (nodeProps == null) { return; } if (nodeProps.remove(node) == null) { log.debug("Received redundant node REMOVED udate for {}. Skipping..", node); return; } nodeConnectorNames.remove(node); Set<NodeConnector> removeNodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (nodeConnector.getNode().equals(node)) { removeNodeConnectorSet.add(nodeConnector); } } for (NodeConnector nc : removeNodeConnectorSet) { nodeConnectorProps.remove(nc); } // check if span ports need to be cleaned up removeSpanPorts(node); /* notify node listeners */ notifyNode(node, UpdateType.REMOVED, null); } private void updateNode(Node node, Set<Property> props) { log.trace("{} updated, props: {}", node, props); if (nodeProps == null || props == null) { return; } Map<String, Property> propMapCurr = nodeProps.get(node); Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>() : new HashMap<String, Property>(propMapCurr); // copy node properties from plugin String nodeId = node.toString(); for (Property prop : props) { if (nodeConfigList != null) { SwitchConfig conf = nodeConfigList.get(nodeId); if (conf != null && (conf.getNodeProperties() != null) && conf.getNodeProperties().containsKey(prop.getName())) { continue; } } propMap.put(prop.getName(), prop); } if (propMapCurr == null) { if (nodeProps.putIfAbsent(node, propMap) != null) { log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}", node.getID(), props); addNodeProps(node, propMap); } } else { if (!nodeProps.replace(node, propMapCurr, propMap)) { log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}", node.getID(), props); addNodeProps(node, propMap); } } /* notify node listeners */ notifyNode(node, UpdateType.CHANGED, propMap); } @Override public void updateNode(Node node, UpdateType type, Set<Property> props) { log.debug("updateNode: {} type {} props {} for container {}", new Object[] { node, type, props, containerName }); switch (type) { case ADDED: addNode(node, props); break; case CHANGED: updateNode(node, props); break; case REMOVED: removeNode(node); break; default: break; } } @Override public void updateNodeConnector(NodeConnector nodeConnector, UpdateType type, Set<Property> props) { Map<String, Property> propMap = new HashMap<String, Property>(); boolean update = true; log.debug("updateNodeConnector: {} type {} props {} for container {}", new Object[] { nodeConnector, type, props, containerName }); if (nodeConnectorProps == null) { return; } switch (type) { case ADDED: // Skip redundant ADDED update (e.g. cluster switch-over) if (nodeConnectorProps.containsKey(nodeConnector)) { log.debug("Redundant nodeconnector ADDED for {}, props {} for container {}", nodeConnector, props, containerName); update = false; } if (props != null) { for (Property prop : props) { addNodeConnectorProp(nodeConnector, prop); propMap.put(prop.getName(), prop); } } else { addNodeConnectorProp(nodeConnector, null); } addSpanPort(nodeConnector); break; case CHANGED: if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) { update = false; } else { for (Property prop : props) { addNodeConnectorProp(nodeConnector, prop); propMap.put(prop.getName(), prop); } } break; case REMOVED: if (!nodeConnectorProps.containsKey(nodeConnector)) { update = false; } removeNodeConnectorAllProps(nodeConnector); // clean up span config removeSpanPort(nodeConnector); break; default: update = false; break; } if (update) { notifyNodeConnector(nodeConnector, type, propMap); } } @Override public Set<Node> getNodes() { return (nodeProps != null) ? new HashSet<Node>(nodeProps.keySet()) : new HashSet<Node>(); } @Override public Map<String, Property> getControllerProperties() { return new HashMap<String, Property>(this.controllerProps); } @Override public Property getControllerProperty(String propertyName) { if (propertyName != null) { HashMap<String, Property> propertyMap = new HashMap<String, Property>(this.controllerProps); return propertyMap.get(propertyName); } return null; } @Override public Status setControllerProperty(Property property) { if (property != null) { this.controllerProps.put(property.getName(), property); return new Status(StatusCode.SUCCESS); } return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property"); } @Override public Status removeControllerProperty(String propertyName) { if (propertyName != null) { if (this.controllerProps.containsKey(propertyName)) { this.controllerProps.remove(propertyName); if (!this.controllerProps.containsKey(propertyName)) { return new Status(StatusCode.SUCCESS); } } String msg = "Unable to remove property " + propertyName + " from Controller"; return new Status(StatusCode.BADREQUEST, msg); } String msg = "Invalid property provided when removing property from Controller"; return new Status(StatusCode.BADREQUEST, msg); } /* * Returns a copy of a list of properties for a given node * * (non-Javadoc) * * @see * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps * (org.opendaylight.controller.sal.core.Node) */ @Override public Map<String, Property> getNodeProps(Node node) { Map<String, Property> rv = new HashMap<String, Property>(); if (this.nodeProps != null) { rv = this.nodeProps.get(node); if (rv != null) { /* make a copy of it */ rv = new HashMap<String, Property>(rv); } } return rv; } @Override public Property getNodeProp(Node node, String propName) { Map<String, Property> propMap = getNodeProps(node); return (propMap != null) ? propMap.get(propName) : null; } @Override public void setNodeProp(Node node, Property prop) { for (int i = 0; i <= REPLACE_RETRY; i++) { /* Get a copy of the property map */ Map<String, Property> propMapCurr = getNodeProps(node); if (propMapCurr == null) { return; } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); propMap.put(prop.getName(), prop); if (nodeProps.replace(node, propMapCurr, propMap)) { return; } } log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID()); } @Override public Status removeNodeProp(Node node, String propName) { for (int i = 0; i <= REPLACE_RETRY; i++) { Map<String, Property> propMapCurr = getNodeProps(node); if (propMapCurr != null) { if (!propMapCurr.containsKey(propName)) { return new Status(StatusCode.SUCCESS); } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); propMap.remove(propName); if (nodeProps.replace(node, propMapCurr, propMap)) { return new Status(StatusCode.SUCCESS); } } else { return new Status(StatusCode.SUCCESS); } } String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID(); return new Status(StatusCode.CONFLICT, msg); } @Override public Status removeNodeAllProps(Node node) { this.nodeProps.remove(node); return new Status(StatusCode.SUCCESS); } @Override public Set<NodeConnector> getUpNodeConnectors(Node node) { if (nodeConnectorProps == null) { return null; } Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (!nodeConnector.getNode().equals(node)) { continue; } if (isNodeConnectorEnabled(nodeConnector)) { nodeConnectorSet.add(nodeConnector); } } return nodeConnectorSet; } @Override public Set<NodeConnector> getNodeConnectors(Node node) { if (nodeConnectorProps == null) { return null; } Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (!nodeConnector.getNode().equals(node)) { continue; } nodeConnectorSet.add(nodeConnector); } return nodeConnectorSet; } @Override public Set<NodeConnector> getPhysicalNodeConnectors(Node node) { if (nodeConnectorProps == null) { return null; } Set<NodeConnector> nodeConnectorSet = new HashSet<NodeConnector>(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); if (!nodeConnector.getNode().equals(node) || isSpecial(nodeConnector)) { continue; } nodeConnectorSet.add(nodeConnector); } return nodeConnectorSet; } @Override public Map<String, Property> getNodeConnectorProps(NodeConnector nodeConnector) { Map<String, Property> rv = new HashMap<String, Property>(); if (this.nodeConnectorProps != null) { rv = this.nodeConnectorProps.get(nodeConnector); if (rv != null) { rv = new HashMap<String, Property>(rv); } } return rv; } @Override public Property getNodeConnectorProp(NodeConnector nodeConnector, String propName) { Map<String, Property> propMap = getNodeConnectorProps(nodeConnector); return (propMap != null) ? propMap.get(propName) : null; } @Override public byte[] getControllerMAC() { MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name); return (macProperty == null) ? null : macProperty.getMacAddress(); } @Override public NodeConnector getNodeConnector(Node node, String nodeConnectorName) { if (nodeConnectorNames == null) { return null; } Map<String, NodeConnector> map = nodeConnectorNames.get(node); if (map == null) { return null; } return map.get(nodeConnectorName); } /** * Adds a node connector and its property if any * * @param nodeConnector * {@link org.opendaylight.controller.sal.core.NodeConnector} * @param propName * name of {@link org.opendaylight.controller.sal.core.Property} * @return success or failed reason */ @Override public Status addNodeConnectorProp(NodeConnector nodeConnector, Property prop) { Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector); Map<String, Property> propMap = (propMapCurr == null) ? new HashMap<String, Property>() : new HashMap<String, Property>(propMapCurr); String msg = "Cluster conflict: Unable to add NodeConnector Property."; // Just add the nodeConnector if prop is not available (in a non-default // container) if (prop == null) { if (propMapCurr == null) { if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) { return new Status(StatusCode.CONFLICT, msg); } } else { if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) { return new Status(StatusCode.CONFLICT, msg); } } return new Status(StatusCode.SUCCESS); } propMap.put(prop.getName(), prop); if (propMapCurr == null) { if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) { return new Status(StatusCode.CONFLICT, msg); } } else { if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) { return new Status(StatusCode.CONFLICT, msg); } } if (prop.getName().equals(Name.NamePropName)) { if (nodeConnectorNames != null) { Node node = nodeConnector.getNode(); Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node); Map<String, NodeConnector> map = new HashMap<String, NodeConnector>(); if (mapCurr != null) { for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) { String s = entry.getKey(); try { map.put(s, new NodeConnector(entry.getValue())); } catch (ConstructionException e) { log.error("An error occured",e); } } } map.put(((Name) prop).getValue(), nodeConnector); if (mapCurr == null) { if (nodeConnectorNames.putIfAbsent(node, map) != null) { // TODO: recovery using Transactionality return new Status(StatusCode.CONFLICT, msg); } } else { if (!nodeConnectorNames.replace(node, mapCurr, map)) { // TODO: recovery using Transactionality return new Status(StatusCode.CONFLICT, msg); } } } } return new Status(StatusCode.SUCCESS); } /** * Removes one property of a node connector * * @param nodeConnector * {@link org.opendaylight.controller.sal.core.NodeConnector} * @param propName * name of {@link org.opendaylight.controller.sal.core.Property} * @return success or failed reason */ @Override public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) { Map<String, Property> propMapCurr = getNodeConnectorProps(nodeConnector); if (propMapCurr == null) { /* Nothing to remove */ return new Status(StatusCode.SUCCESS); } Map<String, Property> propMap = new HashMap<String, Property>(propMapCurr); propMap.remove(propName); boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap); String msg = "Cluster conflict: Unable to remove NodeConnector property."; if (!result) { return new Status(StatusCode.CONFLICT, msg); } if (propName.equals(Name.NamePropName)) { if (nodeConnectorNames != null) { Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName)); if (name != null) { Node node = nodeConnector.getNode(); Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node); if (mapCurr != null) { Map<String, NodeConnector> map = new HashMap<String, NodeConnector>(); for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) { String s = entry.getKey(); try { map.put(s, new NodeConnector(entry.getValue())); } catch (ConstructionException e) { log.error("An error occured",e); } } map.remove(name.getValue()); if (!nodeConnectorNames.replace(node, mapCurr, map)) { // TODO: recovery using Transactionality return new Status(StatusCode.CONFLICT, msg); } } } } } return new Status(StatusCode.SUCCESS); } /** * Removes all the properties of a node connector * * @param nodeConnector * {@link org.opendaylight.controller.sal.core.NodeConnector} * @return success or failed reason */ @Override public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) { if (nodeConnectorNames != null) { Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName)); if (name != null) { Node node = nodeConnector.getNode(); Map<String, NodeConnector> mapCurr = nodeConnectorNames.get(node); if (mapCurr != null) { Map<String, NodeConnector> map = new HashMap<String, NodeConnector>(); for (Map.Entry<String, NodeConnector> entry : mapCurr.entrySet()) { String s = entry.getKey(); try { map.put(s, new NodeConnector(entry.getValue())); } catch (ConstructionException e) { log.error("An error occured",e); } } map.remove(name.getValue()); if (map.isEmpty()) { nodeConnectorNames.remove(node); } else { if (!nodeConnectorNames.replace(node, mapCurr, map)) { log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.", nodeConnector.getID()); } } } } } nodeConnectorProps.remove(nodeConnector); return new Status(StatusCode.SUCCESS); } /** * Function called by the dependency manager when all the required * dependencies are satisfied * */ void init(Component c) { Dictionary<?, ?> props = c.getServiceProperties(); if (props != null) { this.containerName = (String) props.get("containerName"); log.trace("Running containerName: {}", this.containerName); } else { // In the Global instance case the containerName is empty this.containerName = ""; } isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT .toString()); } /** * Function called by the dependency manager when at least one dependency * become unsatisfied or when the component is shutting down because for * example bundle is being stopped. * */ void destroy() { shutDown(); } /** * Function called by dependency manager after "init ()" is called and after * the services provided by the class are registered in the service registry * */ void start() { startUp(); /* * Read startup and build database if we are the coordinator */ loadSubnetConfiguration(); loadSpanConfiguration(); loadSwitchConfiguration(); // OSGI console registerWithOSGIConsole(); } /** * Function called after registered the service in OSGi service registry. */ void started() { // solicit for existing inventories getInventories(); } /** * Function called by the dependency manager before the services exported by * the component are unregistered, this will be followed by a "destroy ()" * calls * */ void stop() { } public void setConfigurationContainerService(IConfigurationContainerService service) { log.trace("Got configuration service set request {}", service); this.configurationService = service; } public void unsetConfigurationContainerService(IConfigurationContainerService service) { log.trace("Got configuration service UNset request"); this.configurationService = null; } public void setInventoryService(IInventoryService service) { log.trace("Got inventory service set request {}", service); this.inventoryService = service; // solicit for existing inventories getInventories(); } public void unsetInventoryService(IInventoryService service) { log.trace("Got a service UNset request"); this.inventoryService = null; // clear existing inventories clearInventories(); } public void setStatisticsManager(IStatisticsManager statisticsManager) { log.trace("Got statistics manager set request {}", statisticsManager); this.statisticsManager = statisticsManager; } public void unsetStatisticsManager(IStatisticsManager statisticsManager) { log.trace("Got statistics manager UNset request"); this.statisticsManager = null; } public void setSwitchManagerAware(ISwitchManagerAware service) { log.trace("Got inventory service set request {}", service); if (this.switchManagerAware != null) { this.switchManagerAware.add(service); } // bulk update for newly joined switchManagerAwareNotify(service); } public void unsetSwitchManagerAware(ISwitchManagerAware service) { log.trace("Got a service UNset request"); if (this.switchManagerAware != null) { this.switchManagerAware.remove(service); } } public void setInventoryListener(IInventoryListener service) { log.trace("Got inventory listener set request {}", service); if (this.inventoryListeners != null) { this.inventoryListeners.add(service); } // bulk update for newly joined bulkUpdateService(service); } public void unsetInventoryListener(IInventoryListener service) { log.trace("Got a service UNset request"); if (this.inventoryListeners != null) { this.inventoryListeners.remove(service); } } public void setSpanAware(ISpanAware service) { log.trace("Got SpanAware set request {}", service); if (this.spanAware != null) { this.spanAware.add(service); } // bulk update for newly joined spanAwareNotify(service); } public void unsetSpanAware(ISpanAware service) { log.trace("Got a service UNset request"); if (this.spanAware != null) { this.spanAware.remove(service); } } void setClusterContainerService(IClusterContainerServices s) { log.trace("Cluster Service set"); this.clusterContainerService = s; } void unsetClusterContainerService(IClusterContainerServices s) { if (this.clusterContainerService == s) { log.trace("Cluster Service removed!"); this.clusterContainerService = null; } } public void setControllerProperties(IControllerProperties controllerProperties) { log.trace("Got controller properties set request {}", controllerProperties); this.controllerProperties = controllerProperties; } public void unsetControllerProperties(IControllerProperties controllerProperties) { log.trace("Got controller properties UNset request"); this.controllerProperties = null; } private void getInventories() { if (inventoryService == null) { log.trace("inventory service not avaiable"); return; } Map<Node, Map<String, Property>> nodeProp = this.inventoryService.getNodeProps(); for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) { Node node = entry.getKey(); log.debug("getInventories: {} added for container {}", new Object[] { node, containerName }); Map<String, Property> propMap = entry.getValue(); Set<Property> props = new HashSet<Property>(); for (Property property : propMap.values()) { props.add(property); } addNode(node, props); } Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService.getNodeConnectorProps(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp.entrySet()) { Map<String, Property> propMap = entry.getValue(); for (Property property : propMap.values()) { addNodeConnectorProp(entry.getKey(), property); } } } private void clearInventories() { nodeProps.clear(); nodeConnectorProps.clear(); nodeConnectorNames.clear(); spanNodeConnectors.clear(); } private void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) { synchronized (inventoryListeners) { for (IInventoryListener service : inventoryListeners) { service.notifyNode(node, type, propMap); } } } private void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) { synchronized (inventoryListeners) { for (IInventoryListener service : inventoryListeners) { service.notifyNodeConnector(nodeConnector, type, propMap); } } } /* * For those joined late, bring them up-to-date. */ private void switchManagerAwareNotify(ISwitchManagerAware service) { for (Subnet sub : subnets.values()) { service.subnetNotify(sub, true); } for (Node node : getNodes()) { SwitchConfig sc = getSwitchConfig(node.toString()); if ((sc != null) && isDefaultContainer) { ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name); service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive()); } } } private void bulkUpdateService(IInventoryListener service) { Map<String, Property> propMap; UpdateType type = UpdateType.ADDED; for (Node node : getNodes()) { propMap = nodeProps.get(node); service.notifyNode(node, type, propMap); } for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProps.entrySet()) { NodeConnector nodeConnector = entry.getKey(); propMap = nodeConnectorProps.get(nodeConnector); service.notifyNodeConnector(nodeConnector, type, propMap); } } private void spanAwareNotify(ISpanAware service) { for (Node node : getNodes()) { for (SpanConfig conf : getSpanConfigList(node)) { service.spanUpdate(node, conf.getPortArrayList(), true); } } } private void registerWithOSGIConsole() { BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) .getBundleContext(); bundleContext.registerService(CommandProvider.class.getName(), this, null); } @Override public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) { if (nodeConnector == null) { return false; } Config config = (Config) getNodeConnectorProp(nodeConnector, Config.ConfigPropName); State state = (State) getNodeConnectorProp(nodeConnector, State.StatePropName); return ((config != null) && (config.getValue() == Config.ADMIN_UP) && (state != null) && (state.getValue() == State.EDGE_UP)); } @Override public boolean doesNodeConnectorExist(NodeConnector nc) { return (nc != null && nodeConnectorProps != null && nodeConnectorProps.containsKey(nc)); } @Override public String getHelp() { StringBuffer help = new StringBuffer(); help.append(" help.append("\t pencs <node id> - Print enabled node connectors for a given node\n"); help.append("\t pdm <node id> - Print switch ports in device map\n"); return help.toString(); } public void _pencs(CommandInterpreter ci) { String st = ci.nextArgument(); if (st == null) { ci.println("Please enter node id"); return; } Node node = Node.fromString(st); if (node == null) { ci.println("Please enter node id"); return; } Set<NodeConnector> nodeConnectorSet = getUpNodeConnectors(node); if (nodeConnectorSet == null) { return; } for (NodeConnector nodeConnector : nodeConnectorSet) { if (nodeConnector == null) { continue; } ci.println(nodeConnector); } ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size()); } public void _pdm(CommandInterpreter ci) { String st = ci.nextArgument(); if (st == null) { ci.println("Please enter node id"); return; } Node node = Node.fromString(st); if (node == null) { ci.println("Please enter node id"); return; } Switch sw = getSwitchByNode(node); ci.println(" NodeConnector Name"); Set<NodeConnector> nodeConnectorSet = sw.getNodeConnectors(); String nodeConnectorName; if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) { for (NodeConnector nodeConnector : nodeConnectorSet) { Map<String, Property> propMap = getNodeConnectorProps(nodeConnector); nodeConnectorName = (propMap == null) ? null : ((Name) propMap .get(Name.NamePropName)).getValue(); if (nodeConnectorName != null) { Node nd = nodeConnector.getNode(); if (!nd.equals(node)) { log.debug("node not match {} {}", nd, node); } Map<String, NodeConnector> map = nodeConnectorNames .get(node); if (map != null) { NodeConnector nc = map.get(nodeConnectorName); if (nc == null) { log.debug("no nodeConnector named {}", nodeConnectorName); } else if (!nc.equals(nodeConnector)) { log.debug("nodeConnector not match {} {}", nc, nodeConnector); } } } ci.println(nodeConnector + " " + ((nodeConnectorName == null) ? "" : nodeConnectorName) + "(" + nodeConnector.getID() + ")"); } ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size()); } } @Override public byte[] getNodeMAC(Node node) { MacAddress mac = (MacAddress) this.getNodeProp(node, MacAddress.name); return (mac != null) ? mac.getMacAddress() : null; } @Override public boolean isSpecial(NodeConnector p) { if (p.getType().equals(NodeConnectorIDType.CONTROLLER) || p.getType().equals(NodeConnectorIDType.ALL) || p.getType().equals(NodeConnectorIDType.SWSTACK) || p.getType().equals(NodeConnectorIDType.HWPATH)) { return true; } return false; } /* * Add span configuration to local cache and notify clients */ private void addSpanPorts(Node node, List<NodeConnector> nodeConnectors) { List<NodeConnector> ncLists = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : nodeConnectors) { if (!spanNodeConnectors.contains(nodeConnector)) { ncLists.add(nodeConnector); } } if (ncLists.size() > 0) { spanNodeConnectors.addAll(ncLists); notifySpanPortChange(node, ncLists, true); } } private void addSpanPorts(Node node) { for (SpanConfig conf : getSpanConfigList(node)) { addSpanPorts(node, conf.getPortArrayList()); } } private void addSpanPort(NodeConnector nodeConnector) { // only add if span is configured on this nodeConnector for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) { if (conf.getPortArrayList().contains(nodeConnector)) { List<NodeConnector> ncList = new ArrayList<NodeConnector>(); ncList.add(nodeConnector); addSpanPorts(nodeConnector.getNode(), ncList); return; } } } /* * Remove span configuration to local cache and notify clients */ private void removeSpanPorts(Node node, List<NodeConnector> nodeConnectors) { List<NodeConnector> ncLists = new ArrayList<NodeConnector>(); for (NodeConnector nodeConnector : nodeConnectors) { if (spanNodeConnectors.contains(nodeConnector)) { ncLists.add(nodeConnector); } } if (ncLists.size() > 0) { spanNodeConnectors.removeAll(ncLists); notifySpanPortChange(node, ncLists, false); } } private void removeSpanPorts(Node node) { for (SpanConfig conf : getSpanConfigList(node)) { addSpanPorts(node, conf.getPortArrayList()); } } private void removeSpanPort(NodeConnector nodeConnector) { if (spanNodeConnectors.contains(nodeConnector)) { List<NodeConnector> ncLists = new ArrayList<NodeConnector>(); ncLists.add(nodeConnector); removeSpanPorts(nodeConnector.getNode(), ncLists); } } private void addNodeProps(Node node, Map<String, Property> propMap) { if (propMap == null) { propMap = new HashMap<String, Property>(); } nodeProps.put(node, propMap); } @Override public Status saveConfiguration() { return saveSwitchConfig(); } /** * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property * object based on given property name and value. Other property types are * not supported yet. * * @param propName * Name of the Property * @param propValue * Value of the Property * @return {@link org.opendaylight.controller.sal.core.Property} */ @Override public Property createProperty(String propName, String propValue) { if (propName == null) { log.debug("propName is null"); return null; } if (propValue == null) { log.debug("propValue is null"); return null; } try { if (propName.equalsIgnoreCase(Description.propertyName)) { return new Description(propValue); } else if (propName.equalsIgnoreCase(Tier.TierPropName)) { int tier = Integer.parseInt(propValue); return new Tier(tier); } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) { long bw = Long.parseLong(propValue); return new Bandwidth(bw); } else if (propName.equalsIgnoreCase(ForwardingMode.name)) { int mode = Integer.parseInt(propValue); return new ForwardingMode(mode); } else if (propName.equalsIgnoreCase(MacAddress.name)){ return new MacAddress(propValue); } else { log.debug("Not able to create {} property", propName); } } catch (Exception e) { log.debug("createProperty caught exception {}", e.getMessage()); } return null; } @SuppressWarnings("deprecation") @Override public String getNodeDescription(Node node) { // Check first if user configured a name SwitchConfig config = getSwitchConfig(node.toString()); if (config != null) { String configuredDesc = config.getNodeDescription(); if (configuredDesc != null && !configuredDesc.isEmpty()) { return configuredDesc; } } // No name configured by user, get the node advertised name Description desc = (Description) getNodeProp(node, Description.propertyName); return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? "" : desc.getValue(); } @Override public Set<Switch> getConfiguredNotConnectedSwitches() { Set<Switch> configuredNotConnectedSwitches = new HashSet<Switch>(); if (this.inventoryService == null) { log.trace("inventory service not available"); return configuredNotConnectedSwitches; } Set<Node> configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes(); if (configuredNotConnectedNodes != null) { for (Node node : configuredNotConnectedNodes) { Switch sw = getSwitchByNode(node); configuredNotConnectedSwitches.add(sw); } } return configuredNotConnectedSwitches; } }
package ua.com.fielden.platform.swing.components.bind.development; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.DynamicEntityKey; import ua.com.fielden.platform.entity.IBindingEntity; import ua.com.fielden.platform.entity.annotation.KeyType; import ua.com.fielden.platform.entity.meta.MetaProperty; import ua.com.fielden.platform.entity.validation.annotation.ValidationAnnotation; import ua.com.fielden.platform.error.Result; import ua.com.fielden.platform.reflection.AnnotationReflector; import ua.com.fielden.platform.reflection.TitlesDescsGetter; import ua.com.fielden.platform.swing.components.bind.development.Binder.IPropertyConnector; import ua.com.fielden.platform.swing.components.bind.development.Binder.IRebindable; import ua.com.fielden.platform.swing.components.bind.development.ComponentFactory.IOnCommitAction; import ua.com.fielden.platform.swing.components.bind.development.ComponentFactory.IOnCommitActionable; import ua.com.fielden.platform.swing.components.smart.autocompleter.development.AutocompleterTextFieldLayer; import ua.com.fielden.platform.utils.PropertyChangeSupportEx; import ua.com.fielden.platform.utils.PropertyChangeSupportEx.CheckingStrategy; import ua.com.fielden.platform.utils.PropertyChangeSupportEx.PropertyChangeOrIncorrectAttemptListener; import com.jgoodies.binding.value.BufferedValueModel; import com.jgoodies.binding.value.Trigger; import com.jgoodies.binding.value.ValueModel; @SuppressWarnings("unchecked") @KeyType(String.class) public final class AutocompleterBufferedPropertyWrapper<T> implements IBindingEntity, IOnCommitActionable, IRebindable { private List<IPropertyConnector> connectors = new ArrayList<IPropertyConnector>(); /** * Provides property change support. */ private final PropertyChangeSupportEx changeSupport; private final Logger logger = Logger.getLogger(this.getClass()); public boolean addPropertyConnector(final IPropertyConnector propertyConnector) { return connectors.add(propertyConnector); } private static final long serialVersionUID = 1L; /** * The name of the bound read-only bean property that indicates whether this models is buffering or in write-through state. * * @see #isBuffering() */ public static final String PROPERTYNAME_BUFFERING = "buffering"; /** * The name of the bound read-write bean property for the subject. * * @see #getSubjectBean() * @see #setSubjectBean(ValueModel) */ public static final String PROPERTYNAME_SUBJECT_BEAN = "subjectBean"; /** * The name of the bound read-write bean property for the trigger channel. * * @see #getTriggerChannel() * @see #setTriggerChannel(ValueModel) */ public static final String PROPERTYNAME_TRIGGER_CHANNEL = "triggerChannel"; /** * Holds the subject that provides the underlying value of type <code>Object</code>. */ private IBindingEntity subjectBean; private String propertyName; /** * Holds the three-state trigger of type <code>Boolean</code>. */ private ValueModel triggerChannel; /** * Holds the buffered value. This value is ignored if we are not buffering. */ private Object bufferedValue; /** * Indicates whether a value has been assigned since the last trigger change. */ private boolean valueAssigned; // /** // * Holds a PropertyChangeListener that observes subject value changes. // */ // private final ValueChangeHandler valueChangeHandler; /** * Holds a PropertyChangeListener that observes trigger changes. */ private final TriggerChangeHandler triggerChangeHandler; private final AutocompleterTextFieldLayer<T> autocompleter; private final List<IOnCommitAction> onCommitActions = new ArrayList<IOnCommitAction>(); private final boolean stringBinding; /** * Constructs a BufferedPropertyWrapper on the given entity and propertyName using the given trigger channel. * * @param subjectBean * the value model to be buffered * @param triggerChannel * the value model that triggers the commit or flush event * @throws NullPointerException * if the triggerChannel is {@code null} */ AutocompleterBufferedPropertyWrapper(final IBindingEntity subjectBean, final String propertyName, final ValueModel triggerChannel, final AutocompleterTextFieldLayer<T> autocompleter, final boolean stringBinding, final IOnCommitAction... actions) { changeSupport = new PropertyChangeSupportEx(this); if (subjectBean == null) { throw new NullPointerException("The entity must not be null."); } if (propertyName == null) { throw new NullPointerException("The propertyName must not be null."); } this.stringBinding = stringBinding; this.propertyName = propertyName; // valueChangeHandler = new ValueChangeHandler(); triggerChangeHandler = new TriggerChangeHandler(); setSubjectBean(subjectBean); setTriggerChannel(triggerChannel); setBuffering(false); this.autocompleter = autocompleter; if (autocompleter == null) { throw new NullPointerException("The autocompleter must not be null."); } for (int i = 0; i < actions.length; i++) { this.addOnCommitAction(actions[i]); } } @Override public void rebindTo(final IBindingEntity entity) { if (entity == null) { new IllegalArgumentException("the component cannot be reconnected to the Null entity!!").printStackTrace(); } else { unbound(); setSubjectBean(entity); for (final IPropertyConnector propertyConnector : connectors) { propertyConnector.addOwnEntitySpecificListeners(); propertyConnector.updateStates(); } } } @Override public void unbound() { for (final IPropertyConnector propertyConnector : connectors) { propertyConnector.removeOwnEntitySpecificListeners(); } // TODO maybe need to remove component-specific listeners } /** * Returns the subjectBean, i.e. the underlying {@link IBindingEntity} that provides the unbuffered value. * * @return the ValueModel that provides the unbuffered value */ @Override public IBindingEntity getSubjectBean() { return subjectBean; } @Override /* * overridden from IBindingEntity to get SubjectBeanProperty value or * buffered value */ public Object get(final String propertyName) { if (!propertyName.equals(this.propertyName)) { logger.error("PropertyName have to be the propertyName incapsulated in this " + getClass().getSimpleName() + "."); return null; } return getValue(); } /** * overridden from IBindingEntity to set SubjectBeanProperty value or buffered value */ @Override public void set(final String propertyName, final Object value) { if (!propertyName.equals(this.propertyName)) { logger.error("PropertyName have to be the propertyName incapsulated in this " + getClass().getSimpleName() + "."); return; } setValue(value); } /** * Sets a new subject bean, i.e. the model that provides the unbuffered value. Notifies all listeners that the <i>subjectBean</i> property has changed. * * @param newSubjectBean * the subject ValueModel to be set */ public void setSubjectBean(final IBindingEntity newSubjectBean) throws NullPointerException { if (newSubjectBean == null) { throw new NullPointerException("the new Subject Bean for BufferedPropertyWrapper cannot be null"); } final IBindingEntity oldSubjectBean = getSubjectBean(); subjectBean = newSubjectBean; firePropertyChange(PROPERTYNAME_SUBJECT_BEAN, oldSubjectBean, newSubjectBean); } @Override public final PropertyChangeSupportEx getChangeSupport() { return changeSupport; } /** * Registers property change listener.<br> * <br> * Note : Please, refer also to {@link PropertyChangeOrIncorrectAttemptListener} JavaDocs. * * @param propertyName * @param listener */ @Override public final synchronized void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("PropertyChangeListener cannot be null."); } // if (!isObservable(propertyName)) { getChangeSupport().addPropertyChangeListener(propertyName, listener); } /** * Removes property change listener. */ @Override public final synchronized void removePropertyChangeListener(final String propertyName, final PropertyChangeListener listener) { getChangeSupport().removePropertyChangeListener(propertyName, listener); } private final void firePropertyChange(final String propertyName, final Object oldValue, final Object newValue) { if (getChangeSupport() == null) { return; } getChangeSupport().firePropertyChange(propertyName, oldValue, newValue); } /** * Returns the ValueModel that is used to trigger commit and flush events. * * @return the ValueModel that is used to trigger commit and flush events */ public ValueModel getTriggerChannel() { return triggerChannel; } /** * Sets the ValueModel that triggers the commit and flush events. * * @param newTriggerChannel * the ValueModel to be set as trigger channel * @throws NullPointerException * if the newTriggerChannel is {@code null} */ public void setTriggerChannel(final ValueModel newTriggerChannel) { if (newTriggerChannel == null) { throw new NullPointerException("The trigger channel must not be null."); } final ValueModel oldTriggerChannel = getTriggerChannel(); if (oldTriggerChannel != null) { oldTriggerChannel.removeValueChangeListener(triggerChangeHandler); } triggerChannel = newTriggerChannel; newTriggerChannel.addValueChangeListener(triggerChangeHandler); firePropertyChange(PROPERTYNAME_TRIGGER_CHANNEL, oldTriggerChannel, newTriggerChannel); } /** * Returns the subjectBean property's value if no value has been set since the last commit or flush, and returns the buffered value otherwise. Attempts to read a value when no * subject is set are rejected with a NullPointerException. * * @return the buffered value * @throws NullPointerException * if no subject is set */ public Object getValue() { if (subjectBean == null) { throw new NullPointerException("The subject must not be null " + "when reading a value from a BufferedValueModel."); } return isBuffering() ? bufferedValue : subjectBean.get(propertyName); } /** * Sets a new buffered value and turns this {@link BufferedPropertyWrapper} into the buffering state. The buffered value is not provided to the underlying model until the * trigger channel indicates a commit. Attempts to set a value when no subject is set are rejected with a NullPointerException. * <p> * * The above semantics is easy to understand, however it is tempting to check the new value against the current subject value to avoid that the buffer unnecessary turns into * the buffering state. But here's a problem. Let's say the subject value is "first" at buffer creation time, and let's say the subject value has changed in the meantime to * "second". Now someone sets the value "second" to this buffer. The subject value and the value to be set are equal. Shall we buffer? Also, this decision would depend on the * ability to read the subject. The semantics would depend on the subject' state and capabilities. * <p> * * It is often sufficient to observe the buffering state when enabling or disabling a commit command button like "OK" or "Apply". And later check the <em>changed</em> state in * a PresentationModel. You may want to do better and may want to observe a property like "defersTrueChange" that indicates whether flushing a buffer will actually change the * subject. But note that such a state may change with subject value changes, which may be hard to understand for a user. * <p> * * * model is already in buffering state. In this case the old buffered value can be used instead of invoking <code>#readBufferedOrSubjectValue()</code>. * * @param newBufferedValue * the value to be buffered * @throws NullPointerException * if no subject is set */ public void setValue(final Object newBufferedValue) { if (subjectBean == null) { throw new NullPointerException("The subject must not be null " + "when setting a value to a BufferedValueModel."); } final ReadAccessResult oldReadValue = readBufferedOrSubjectValue(); final Object oldValue = oldReadValue.value; bufferedValue = newBufferedValue; logger.info("Buffered value := " + newBufferedValue); setBuffering(true); if (oldReadValue.readable && oldValue == newBufferedValue) { return; } } /** * Tries to lookup the current buffered or subject value and returns this value plus a marker that indicates whether the read-access succeeded or failed. The latter situation * arises in an attempt to read a value from a write-only subject if this {@link BufferedPropertyWrapper} is not buffering and if this model changes its subject. * * @return the current value plus a boolean that indicates the success or failure */ private ReadAccessResult readBufferedOrSubjectValue() { try { final Object value = getValue(); // May fail with write-only models return new ReadAccessResult(value, true); } catch (final Exception e) { return new ReadAccessResult(null, false); } } /** * Removes the PropertyChangeListeners from the subject and trigger channel. * <p> * * To avoid memory leaks it is recommended to invoke this method if the subject and trigger channel live much longer than this buffer. Once #release has been invoked the * BufferedValueModel instance must not be used any longer. * <p> * * As an alternative you may use event listener lists in subjects and trigger channels that are based on <code>WeakReference</code>s. * * @see java.lang.ref.WeakReference */ public void release() { final ValueModel aTriggerChannel = getTriggerChannel(); if (aTriggerChannel != null) { aTriggerChannel.removeValueChangeListener(triggerChangeHandler); } } /** * Returns whether this model buffers a value or not, that is, whether a value has been assigned since the last commit or flush. * * @return true if a value has been assigned since the last commit or flush */ public boolean isBuffering() { return valueAssigned; } private void setBuffering(final boolean newValue) { final boolean oldValue = isBuffering(); valueAssigned = newValue; firePropertyChange(PROPERTYNAME_BUFFERING, oldValue, newValue); } /** * * Gets the actualValues from autocompleter and sets as subjectValue (when autocompleter singleValued - the only one value, otherwise - the List) Also notifies appropriate * listeners. * * Sets the buffered value as new subject value - if any value has been set. After this commit this {@link BufferedPropertyWrapper} behaves as if no value has been set before. * This method is invoked if the trigger has changed to {@code Boolean.TRUE}. * <p> * * Since the subject's value is assigned <em>after</em> the buffer marker is reset, subject change notifications will be handled. In this case the subject's old value is not * this {@link BufferedPropertyWrapper}'s old value; instead the old value reported to listeners of this model is the formerly buffered value. * * The commit logic has been enhanced with indication of the start and finish for the property validation process (refer {@link Property} for more details). Validation is not * considered finished if the validation result is not successful. * * @throws Exception * - throws when single valued autocompleter returns multiple values! * * @throws NullPointerException * if no subject is set */ private void commit() { if (isBuffering()) { // lock subject bean, even if the setter will not be performed (it is more safe) subjectBean.lock(); // IMPORTANT: need to capture the relevant values in the EDT before entering the SwingWorker // this is essential in order to have UI control value writes and reads synchronised final String controlValue = autocompleter.getView().getText(); final Object bufferedValue = this.bufferedValue; // now create and execute the swing worker new SwingWorkerCatcher<String, Void>() { private boolean setterPerformed = false; @Override protected String tryToDoInBackground() { setBuffering(false); logger.debug("Buffered value [" + bufferedValue + "] commits."); if (!bufferedValue.equals(controlValue)) { logger.error("Buffered value == [" + bufferedValue + "] is not identical to autocompleter.getView().getText() == [" + controlValue + "]"); } // IMPORTANT: bufferedValue is of type String!!!! // that is why need to get actual values from autocompleter. final List values = stringBinding && autocompleter.isMulti() ? new ArrayList<T>() : autocompleter.values((String) bufferedValue); if (autocompleter.isMulti()) { // multi-valued autocompleter final Object valueToSet = stringBinding ? (AutocompleterConnector.constructStringListFromStringBufferedValue((String) bufferedValue, autocompleter.getAutocompleter().getValueSeparator())) : values; subjectBean.set(propertyName, valueToSet); setterPerformed = true; } else { // otherwise single-valued if (StringUtils.isEmpty(controlValue)) { // if text is empty then there should no value -- hence null subjectBean.set(propertyName, null); setterPerformed = true; } else if (isEmpty(values, bufferedValue, stringBinding)) { // otherwise, if there is some text, but autocompleter failed to find a corresponding entity then this should be reported as non-existing entity case final String errorMsg = TitlesDescsGetter.processEntityExistsErrorMsg(propertyName, bufferedValue, subjectBean.getProperty(propertyName).getEntity().getType()); final Result result = new Result(subjectBean, new Exception(!StringUtils.isEmpty(errorMsg) ? errorMsg : "Could not find a matching value/values for " + bufferedValue)); logger.info("Could not find a matching value/values for " + bufferedValue); if (!stringBinding) { // if autocompleter binds to IBindingEntity : update ENTITY_EXISTS validation result // (it ensures that ENTITY_EXISTS should be specified as validation annotation in the property setter) // but the same can be simply performed with fireImaginaryValidationResult(...) method!!! if (subjectBean.getProperty(propertyName) != null) { subjectBean.getProperty(propertyName).setRequiredValidationResult(null); subjectBean.getProperty(propertyName).setEntityExistsValidationResult(result); } } else { //subjectBean.getMetaProperty(propertyName).fireImaginaryValidationResult(result); if (subjectBean.getProperty(propertyName) != null && subjectBean.getProperty(propertyName).getValidators().containsKey(ValidationAnnotation.ENTITY_EXISTS)) { // if String property annotated by EntityExists, // then should report "early" validation result error subjectBean.getProperty(propertyName).setRequiredValidationResult(null); subjectBean.getProperty(propertyName).setEntityExistsValidationResult(result); } else { subjectBean.set(propertyName, bufferedValue); setterPerformed = true; } } return null; } else { // everything is cool and we can set a single value that was returned by the autocompleter subjectBean.set(propertyName, stringBinding ? bufferedValue : ((values.size() > 1) ? findValue((String) bufferedValue, values) : values.get(0))); setterPerformed = true; } } // end of single-valued autocompleter processing return null; } /** * This method defines what "empty" means for a list of resultant from autocompleter matcher values. * * @param values * @param bufferedValue * @param stringBinding * @return */ private boolean isEmpty(final List values, final Object bufferedValue, final boolean stringBinding) { if (stringBinding) { for (final Object value : values) { if (bufferedValue.equals(value)) { return false; } } } else { for (final Object v : values) { final AbstractEntity value = (AbstractEntity) v; Object that; if (value.getKeyType() == DynamicEntityKey.class) { that = value.getKey().toString(); } else { that = value.getKey(); } // well... the internal logic is really all about strings, so for better Integer support make it a String... if (that instanceof Integer) { that = value.getKey().toString(); } // if (bufferedValue.equals(that)) { // return false; // TODO take into account case sensitivity from upper logic if ((bufferedValue instanceof String) && (that instanceof String) && ((String) bufferedValue).equalsIgnoreCase((String) that)) { return false; } else if (bufferedValue.equals(that)) { return false; } } } return true; } @Override protected void tryToDone() { if (setterPerformed) { for (int i = 0; i < onCommitActions.size(); i++) { if (onCommitActions.get(i) != null) { onCommitActions.get(i).postCommitAction(); if (subjectBean.getProperty(propertyName) == null || subjectBean.getProperty(propertyName).isValid()) { onCommitActions.get(i).postSuccessfulCommitAction(); } else { onCommitActions.get(i).postNotSuccessfulCommitAction(); } } } } // need to unlock subjectBean in all cases: // 1. setter not performed - exception throwed // 2. setter not performed - the committing logic didn't invoke setter // 3. setter performed correctly subjectBean.unlock(); } }.execute(); } } private static <N extends AbstractEntity> N findValue(final String bufferedValue, final List<N> values) { for (final N value : values) { if (value.getKey().equals(bufferedValue)) { return value; } } return null; } /** * Flushes the buffered value. This method is invoked if the trigger has changed to {@code Boolean.FALSE}. After this flush this {@link BufferedPropertyWrapper} behaves as if * no value has been set before. * <p> * * * * @throws NullPointerException * if no subject is set */ protected void flush() { logger.debug("Inner flush perfomed."); final boolean wasBuffering = isBuffering(); final Object oldValue = subjectBean.get(propertyName); setBuffering(false); final Object newValue = getValue(); if (subjectBean.getChangeSupport() != null) { subjectBean.getChangeSupport().firePropertyChange(propertyName, oldValue, newValue, wasBuffering ? CheckingStrategy.CHECK_NOTHING : CheckingStrategy.CHECK_EQUALITY, false); } } protected String valueString() { try { final Object value = getValue(); return value == null ? "null" : value.toString(); } catch (final Exception e) { return "Can't read"; } } protected String paramString() { return "value=" + valueString() + "; buffering" + isBuffering(); } /** * Describes the result of a subject value read-access plus a marker that indicates if the value could be read or not. The latter is used in <code>#setValue</code> to suppress * some unnecessary change notifications in case the value could be read successfully. * * @see BufferedValueModel#setValue(Object) */ private static final class ReadAccessResult { final Object value; final boolean readable; private ReadAccessResult(final Object value, final boolean readable) { this.value = value; this.readable = readable; } } /** * Listens to changes of the trigger channel. */ private final class TriggerChangeHandler implements PropertyChangeListener { /** * The trigger has been changed. Commits or flushes the buffered value. * * @param evt * the property change event to be handled */ @Override public void propertyChange(final PropertyChangeEvent evt) { if (Boolean.TRUE.equals(evt.getNewValue())) { commit(); } else if (Boolean.FALSE.equals(evt.getNewValue())) { flush(); } } } @Override public String getPropertyName() { return propertyName; } @Override public synchronized boolean addOnCommitAction(final IOnCommitAction onCommitAction) { return onCommitActions.add(onCommitAction); } @Override public synchronized boolean removeOnCommitAction(final IOnCommitAction onCommitAction) { return onCommitActions.remove(onCommitAction); } @Override public List<IOnCommitAction> getOnCommitActions() { return Collections.unmodifiableList(onCommitActions); } public boolean isStringBinding() { return stringBinding; } @Override public MetaProperty getProperty(final String name) { throw new RuntimeException("Illegal operation."); } @Override public void lock() { throw new RuntimeException("Illegal operation."); } @Override public void unlock() { throw new RuntimeException("Illegal operation."); } @Override public Class<?> getPropertyType(final String propertyName) { throw new RuntimeException("Illegal operation."); } @Override public void updateToolTip() { for (final IPropertyConnector connector : connectors){ connector.updateToolTip(); } } }
package org.wyona.yanel.impl.resources.updatefinder; import org.apache.log4j.Category; import org.apache.xml.resolver.tools.CatalogResolver; import org.apache.xml.serializer.Serializer; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.serialization.SerializerFactory; import org.wyona.yanel.core.source.ResourceResolver; import org.wyona.yanel.core.transformation.I18nTransformer2; import org.wyona.yanel.core.transformation.XIncludeTransformer; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yanel.impl.resources.updatefinder.utils.*; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Collections; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamSource; import javax.servlet.http.HttpSession; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; public class UpdateFinder extends Resource implements ViewableV2 { private static Category log = Category.getInstance(UpdateFinder.class); public UpdateFinder() { } public boolean exists() { return true; } public long getSize() { return -1; } public String getMimeType(String viewId) { if (viewId != null && viewId.equals("source")) return "application/xml"; return "application/xhtml+xml"; } public View getView(String viewId) { View view = new View(); String mimeType = getMimeType(viewId); view.setMimeType(mimeType); try { org.wyona.yarep.core.Repository repo = getRealm().getRepository(); if (viewId != null && viewId.equals("source")) { view.setInputStream(new java.io.StringBufferInputStream(getScreen())); view.setMimeType("application/xml"); return view; } String[] xsltPath = getXSLTPath(getPath()); if (xsltPath != null) { // create reader: XMLReader xmlReader = XMLReaderFactory.createXMLReader(); CatalogResolver catalogResolver = new CatalogResolver(); xmlReader.setEntityResolver(catalogResolver); // create xslt transformer: SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler[] xsltHandlers = new TransformerHandler[xsltPath.length]; for (int i = 0; i < xsltPath.length; i++) { xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(repo.getNode(xsltPath[i]) .getInputStream())); xsltHandlers[i].getTransformer().setParameter("yanel.path.name", org.wyona.commons.io.PathUtil.getName(getPath())); xsltHandlers[i].getTransformer().setParameter("yanel.path", getPath()); xsltHandlers[i].getTransformer().setParameter("yanel.back2context", PathUtil.backToContext(realm, getPath())); xsltHandlers[i].getTransformer().setParameter("yarep.back2realm", PathUtil.backToRealm(getPath())); xsltHandlers[i].getTransformer().setParameter("language", getRequestedLanguage()); } // create i18n transformer: I18nTransformer2 i18nTransformer = new I18nTransformer2("global", getRequestedLanguage(), getRealm().getDefaultLanguage()); i18nTransformer.setEntityResolver(catalogResolver); // create xinclude transformer: XIncludeTransformer xIncludeTransformer = new XIncludeTransformer(); ResourceResolver resolver = new ResourceResolver(this); xIncludeTransformer.setResolver(resolver); // create serializer: Serializer serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // chain everything together (create a pipeline): xmlReader.setContentHandler(xsltHandlers[0]); for (int i = 0; i < xsltHandlers.length - 1; i++) { xsltHandlers[i].setResult(new SAXResult(xsltHandlers[i + 1])); } xsltHandlers[xsltHandlers.length - 1].setResult(new SAXResult(xIncludeTransformer)); xIncludeTransformer.setResult(new SAXResult(i18nTransformer)); i18nTransformer.setResult(new SAXResult(serializer.asContentHandler())); serializer.setOutputStream(baos); // execute pipeline: xmlReader.parse(new InputSource(new java.io.StringBufferInputStream(getScreen()))); // write result into view: view.setInputStream(new ByteArrayInputStream(baos.toByteArray())); return view; } log.debug("Mime-Type: " + mimeType); view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; } catch (Exception e) { log.error(e + " (" + getPath() + ", " + getRealm() + ")", e); } view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; } public ViewDescriptor[] getViewDescriptors() { ViewDescriptor[] vd = new ViewDescriptor[2]; vd[0] = new ViewDescriptor("default"); vd[0].setMimeType(getMimeType(null)); vd[1] = new ViewDescriptor("source"); vd[1].setMimeType(getMimeType("source")); return vd; } /** * Generate screen */ private String getScreen() { StringBuffer body = new StringBuffer(); StringBuffer head = new StringBuffer(); Enumeration parameters = request.getParameterNames(); if (!parameters.hasMoreElements()) { plainRequest(body); } else { if (request.getParameter("save-as") != null) { plainRequest(body); } else if (request.getParameter("usecase") != null && request.getParameter("usecase").equals("update")) { getUpdateConfirmScreen(body); } else if (request.getParameter("usecase") != null && request.getParameter("usecase").equals("updateconfirmed")) { getUpdateScreen(body,head); } else { log.info("Fallback ..."); plainRequest(body); } } StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http: sb.append("<head>"); sb.append("<title>Yanel Updater</title>"); sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-css/progressBarTerminated.css\"/>"); /* sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/prototype.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/progressBar.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/sorttable.js\" type=\"text/javascript\"></script>"); */ sb.append(head); sb.append("</head>"); sb.append("<body>"); sb.append("<h1>Yanel Updater</h1>"); sb.append(body); sb.append("</body>"); sb.append("</html>"); return sb.toString(); } private void plainRequest(StringBuffer htmlBodyContent) { InstallInfo installInfo = null; try { installInfo = getInstallInfo(); } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>Could not get install information. " + e.getMessage() + "</p>"); return; } UpdateInfo updateInfo = null; try { updateInfo = getUpdateInfo(); } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>Could not get update information. " + e.getMessage() + "</p>"); return; } if (!installInfo.getInstalltype().equals("bin-snapshot")) { htmlBodyContent.append("<p>This Yanel was not installed from binary. You can only use the updater if you installed yanel from binary. Please use Subversion or get another source snapshot.</p><p>NOTE: In order to enhance the Yanel Updater resource developers might want to modify <a href=\"file://" + installInfo.getInstallRdfFilename() + "\">" + installInfo.getInstallRdfFilename() + "</a> by replacing the installtype \"source\" with \"bin-snapshot\" and also customize the version and revision!</p>"); return; } String idVersionRevisionCurrent = installInfo.getId() + "-v-" + installInfo.getVersion() + "-r-" + installInfo.getRevision(); // show installed version htmlBodyContent.append("<p>"); htmlBodyContent.append("Your installed yanel is: " + installInfo.getId() + "-v-" + installInfo.getVersion() + "-r-" + installInfo.getRevision()); htmlBodyContent.append("</p>"); // TODO: implement getBestYanelWebapp() to get all yanel-webapp version which has an // yanel-updater which fits the targetRevision requirement of the current yanel and is not // already installed. ArrayList updatebleYanelVersions = null; try { updatebleYanelVersions = getSuitableYanelUpdates(installInfo, updateInfo); } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>Could not get Updates. " + e.getMessage() + "</p>"); } if (updatebleYanelVersions == null) { htmlBodyContent.append("<p>"); htmlBodyContent.append("No updates found."); htmlBodyContent.append("</p>"); } else { HashMap newestYanel = (HashMap) updatebleYanelVersions.get(updatebleYanelVersions.size() - 1); String newestYanelName = (String) newestYanel.get("id") + "-v-" + (String) newestYanel.get("version") + "-r-" + (String) newestYanel.get("revision"); if (newestYanelName.equals(idVersionRevisionCurrent)) { htmlBodyContent.append("<p>"); htmlBodyContent.append("Your yanel is already the newest version."); htmlBodyContent.append("</p>"); } else { htmlBodyContent.append("<p>"); htmlBodyContent.append("Newest yanel is: " + newestYanelName); htmlBodyContent.append("<form method=\"GET\"><input type=\"submit\" name=\"button\" value=\"update\"></input><input type=\"hidden\" name=\"usecase\" value=\"update\"></input><input type=\"hidden\" name=\"updatelink\" value=\"" + newestYanel.get("updateLink") + "\"/></form>"); htmlBodyContent.append("</p>"); } htmlBodyContent.append("<p>"); htmlBodyContent.append("All versions you can get:"); htmlBodyContent.append("</p>"); htmlBodyContent.append("<ul>"); for (int i = 0; i < updatebleYanelVersions.size(); i++) { HashMap versionDetails = (HashMap) updatebleYanelVersions.get(i); String idVersionRevisionItem = (String) versionDetails.get("id") + "-v-" + (String) versionDetails.get("version") + "-r-" + (String) versionDetails.get("revision"); htmlBodyContent.append("<li>" + versionDetails.get("title") + "<ul>" + "<li>Version: " + idVersionRevisionItem + "</li>" + "<li>Type: " + versionDetails.get("type") + "</li>" + "<li> ChangeLog: " + versionDetails.get("changeLog") + "</li>" + "<li> <form method=\"GET\"><input type=\"submit\" name=\"button\" value=\"update\"></input><input type=\"hidden\" name=\"usecase\" value=\"update\"/><input type=\"hidden\" name=\"updatelink\" value=\"" + versionDetails.get("updateLink") + "\"/></form></li>" + "</ul></li>"); } htmlBodyContent.append("</ul>"); } // show installed versions try { htmlBodyContent.append("<p>"); htmlBodyContent.append("Installed versions:"); htmlBodyContent.append("</p>"); TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); Map contextAndWebapp = tomcatContextHandler.getContextAndWebapp(); htmlBodyContent.append("<table class=\"sortable\">"); htmlBodyContent.append("<thead>"); htmlBodyContent.append("<tr><th>Context</th><th>Webapp</th></tr>"); htmlBodyContent.append("</thead>"); htmlBodyContent.append("<tbody>"); Iterator iterator = contextAndWebapp.keySet().iterator(); while (iterator.hasNext()) { String context = (String) iterator.next(); String webapp = (String) contextAndWebapp.get(context); htmlBodyContent.append("<tr><td><a href=\"" + "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + context.replaceAll("/", "") + "\">" + context + "</a></td><td>" + webapp + "</td></tr>"); } htmlBodyContent.append("</tbody>"); htmlBodyContent.append("</table>"); } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>Could not get installed versions. " + e.getMessage() + "</p>"); //return; } } private void getUpdateConfirmScreen(StringBuffer htmlBodyContent) { try { UpdateInfo updateInfo = getUpdateInfo(); InstallInfo installInfo = getInstallInfo(); Map bestUpdater = getBestUpdater(); TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); HashMap versionDetails = updateInfo.getUpdateVersionDetail("updateLink", request.getParameter("updatelink")); String version = (String) versionDetails.get("version"); String revision = (String) versionDetails.get("revision"); String id = (String) versionDetails.get("id"); if (tomcatContextHandler.getWebappOfContext(bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision")) != null) { htmlBodyContent.append("<p>Yanel will redirect you to the update-manager which will download and install " + id + "-v-" + version + "-r-" + revision + "</p>"); htmlBodyContent.append("<p>Do you want to continue?</p>"); htmlBodyContent.append("<p>"); htmlBodyContent.append("<form method=\"post\" action=\"" + "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision") + "/\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"YES\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"usecase\" value=\"updateconfirmed\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"updatelink\" value=\"" + request.getParameter("updatelink") + "\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"requestingwebapp\" value=\"" + installInfo.getWebaName() + "\"/>"); // TODO: here it should ask for a password which should be set in the new updater // NOTE: One can protect the URL itself and hence a specific authentication/authorization is not really necessary! htmlBodyContent.append("</form>"); htmlBodyContent.append("<form method=\"GET\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"Cancel\"></input>"); htmlBodyContent.append("</form>"); htmlBodyContent.append("</p>"); } else { htmlBodyContent.append("<p>In order to download and install the Yanel update \"" + id + "-v-" + version + "-r-" + revision + "\" the update-manager \"" + bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision") + "\" needs to be downloaded first.</p>"); htmlBodyContent.append("<p>Do you want to continue?</p>"); htmlBodyContent.append("<p>"); htmlBodyContent.append("<form method=\"GET\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"YES\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"usecase\" value=\"updateconfirmed\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"updatelink\" value=\"" + request.getParameter("updatelink") + "\"/>"); htmlBodyContent.append("</form>"); htmlBodyContent.append("<form method=\"GET\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"Cancel\"></input>"); htmlBodyContent.append("</form>"); htmlBodyContent.append("</p>"); } } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>An error occoured. Exception: " + e.getMessage() + "</p>"); } } private void getUpdateScreen(StringBuffer htmlBodyContent, StringBuffer head) { HttpSession session = request.getSession(); try { String destDir = request.getSession().getServletContext().getRealPath(".") + File.separator + ".."; Map bestUpdater = getBestUpdater(); InstallInfo installInfo = getInstallInfo(); URL updaterURL = new URL("http://" + request.getServerName() + ":" + request.getServerPort() + "/" + bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision")); HttpURLConnection updaterURLConn = (HttpURLConnection)updaterURL.openConnection(); if (updaterURLConn.getResponseCode() == 200) { session.removeAttribute(WarFetcher.SESSION_ATTR_TASK); session.removeAttribute(WarFetcher.SESSION_ATTR_PROGRESS); session.removeAttribute(WarFetcher.SESSION_ATTR_ITEMS_DONE); session.removeAttribute(WarFetcher.SESSION_ATTR_ITEMS_TO_BE_DONE); head.append("<meta http-equiv=\"refresh\" content=\"0; URL=http://" + request.getServerName() + ":" + request.getServerPort() + "/" + bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision") + "/?updatelink=" + request.getParameter("updatelink") + "&amp;requestingwebapp=" + installInfo.getWebaName() + "\"/>"); htmlBodyContent.append("<p>Update-Manager has been downloaded and installed.</p>"); htmlBodyContent.append("<p>You will be <a href=\""+"http://" + request.getServerName() + ":" + request.getServerPort() + "/" + bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision") + "/?updatelink=" + request.getParameter("updatelink") + "&amp;requestingwebapp=" + installInfo.getWebaName() + ""+"\">redirected</a> to the update-manager which will automatically download and install the requested yanel.</p>"); return; } if (session.getAttribute(WarFetcher.SESSION_ATTR_TASK) == null ){ Runnable runFetcher = new WarFetcher(request, (String) bestUpdater.get("updateLink"), destDir); new Thread(runFetcher).start(); session.setAttribute(WarFetcher.SESSION_ATTR_TASK, "started"); session.setAttribute(WarFetcher.SESSION_ATTR_PROGRESS, "0"); } //TODO here it should set a password for the updater if (session.getAttribute(WarFetcher.SESSION_ATTR_TASK) != null && session.getAttribute(WarFetcher.SESSION_ATTR_TASK).equals("downloaded")) { TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); tomcatContextHandler.setContext(bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision"), bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision")); session.setAttribute(WarFetcher.SESSION_ATTR_TASK, "loading"); //htmlBodyContent.append("<p>Tomcat is loading and startup the update-manager</p>"); //head.append("<meta http-equiv=\"refresh\" content=\"2; URL=?usecase=updateconfirmed&amp;updatelink=" + request.getParameter("updatelink") + "\"/>"); } if (session.getAttribute(WarFetcher.SESSION_ATTR_TASK) != null && session.getAttribute(WarFetcher.SESSION_ATTR_TASK).equals("loading")) { int pseudoprogress = Integer.valueOf((String) session.getAttribute(WarFetcher.SESSION_ATTR_PROGRESS)).intValue() + 1; session.setAttribute(WarFetcher.SESSION_ATTR_PROGRESS, "" + pseudoprogress); } if (session.getAttribute(WarFetcher.SESSION_ATTR_TASK) != null) { head.append("<meta http-equiv=\"refresh\" content=\"2; URL=?usecase=updateconfirmed&amp;updatelink=" + request.getParameter("updatelink") + "\"/>"); htmlBodyContent.append("<p>Working: " + session.getAttribute(WarFetcher.SESSION_ATTR_TASK) + "</p><p>"); if (session.getAttribute(WarFetcher.SESSION_ATTR_ITEMS_DONE) != null) { if (session.getAttribute(WarFetcher.SESSION_ATTR_TASK).equals("download")) { htmlBodyContent.append("Downloaded " + session.getAttribute(WarFetcher.SESSION_ATTR_ITEMS_DONE) + " bytes of " + session.getAttribute(WarFetcher.SESSION_ATTR_ITEMS_TO_BE_DONE) + " bytes"); } if (session.getAttribute(WarFetcher.SESSION_ATTR_TASK).equals("extract")) { htmlBodyContent.append("Extracted " + session.getAttribute(WarFetcher.SESSION_ATTR_ITEMS_DONE) + " items of " + session.getAttribute(WarFetcher.SESSION_ATTR_ITEMS_TO_BE_DONE) + " items"); } } htmlBodyContent.append("</p>"); htmlBodyContent.append("<p>Progress: <div id=\"yanelprogressbarterminated\"><div id=\"yanelprogressbarindicatorterminated\" style=\"width:" + session.getAttribute(WarFetcher.SESSION_ATTR_PROGRESS) + "%\">" + session.getAttribute(WarFetcher.SESSION_ATTR_PROGRESS) +"%</div></div></p>"); } } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>Update failed. Exception: " + e.getMessage() + "</p>"); } } private InstallInfo getInstallInfo() throws Exception { return new InstallInfo(request); } private UpdateInfo getUpdateInfo() throws Exception { return new UpdateInfo(getInstallInfo().getUpdateURL(), getInstallInfo()); } /** * Get Updater */ private HashMap getBestUpdater() throws Exception { InstallInfo installInfo = getInstallInfo(); UpdateInfo updateInfo = getUpdateInfo(); HashMap updateVersionDetails = updateInfo.getUpdateVersionDetail("updateLink", request.getParameter("updatelink")); VersionComparator versionComparator = new VersionComparator(); String updateId = (String) updateVersionDetails.get("id"); String updateVersion = (String) updateVersionDetails.get("version"); String updateRevision = (String) updateVersionDetails.get("revision"); ArrayList bestUpdater = updateInfo.getUpdateVersionsOf("type", "updater", installInfo.getRevision()); for (int i = 0; i < bestUpdater.size(); i++) { HashMap versionDetail = (HashMap) bestUpdater.get(i); log.error("DEBUG: Updater details: " + versionDetail); if (versionComparator.compare((String) versionDetail.get(UpdateInfo.TARGET_APPLICATION_MIN_REVISION), updateRevision) > 0 ) { bestUpdater.remove(i); } if (versionComparator.compare((String) versionDetail.get(UpdateInfo.TARGET_APPLICATION_MAX_REVISION), updateRevision) < 0 ) { bestUpdater.remove(i); } } Collections.sort(bestUpdater, new UpdateInfoVersionComparator()); if (bestUpdater.size() < 1) { throw new Exception("No updater found for updating your current version (" + installInfo.getId() + "-v-" + installInfo.getVersion() + "-r-" + installInfo.getRevision() + ") to your requested version (" + updateId + "-v-" + updateVersion + "-r-" + updateRevision + ")"); } return (HashMap) bestUpdater.get(bestUpdater.size() - 1); } /** * @return ArrayList with all updates which are matching the revision requirement and are not installed yet. or null if none. * @throws Exception */ private ArrayList getSuitableYanelUpdates(InstallInfo installInfo, UpdateInfo updateInfo) throws Exception { TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); ArrayList updates = updateInfo.getYanelUpdatesForYanelRevision(installInfo.getRevision()); if (updates == null) return null; for (int i = 0; i < updates.size(); i++) { HashMap versionDetail = (HashMap) updates.get(i); log.error("DEBUG: Update: " + versionDetail.get("id") + "-v-" + versionDetail.get("version") + "-r-" + versionDetail.get("revision")); for (int j = 0; j < tomcatContextHandler.getWebappNames().length; j++) { if (tomcatContextHandler.getWebappNames()[j].equals(versionDetail.get("id") + "-v-" + versionDetail.get("version") + "-r-" + versionDetail.get("revision"))) { updates.remove(i); } } } if (updates.size() < 1) return null; return updates; } /** * Get XSLT path */ private String[] getXSLTPath(String path) throws Exception { String[] xsltPath = getResourceConfigProperties("xslt"); if (xsltPath != null) return xsltPath; log.info("No XSLT Path within: " + path); return null; } }
package org.carlspring.strongbox.storage.checksum; import org.carlspring.strongbox.util.MessageDigestUtils; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.junit.Ignore; import org.junit.Test; import static junit.framework.Assert.assertEquals; /** * @author mtodorov */ @Ignore public class ChecksumCacheManagerTest { @Test public void testChecksumManagement() throws Exception { ChecksumCacheManager manager = new ChecksumCacheManager(); manager.setCachedChecksumLifetime(3000l); manager.setCachedChecksumExpiredCheckInterval(500l); manager.startMonitor(); final String artifact1BasePath = "storage0/repositories/snapshots/org/carlspring/maven/test-project/1.0-SNAPSHOT/maven-metadata.xml"; final String artifact2BasePath = "storage0/repositories/snapshots/org/carlspring/maven/test-project/1.0-SNAPSHOT/test-project-1.0-20131004.115330-1.jar"; manager.addArtifactChecksum(artifact1BasePath, "md5", "d0s#3E59jszLsPj3#edp!$"); manager.addArtifactChecksum(artifact1BasePath, "sha1", "d0s#3E59jszLsPj3#edp!$"); manager.addArtifactChecksum(artifact2BasePath, "md5", "eps0#!_)fs0-qWadg manager.addArtifactChecksum(artifact2BasePath, "sha1", "eps0#!_)fs0-qWadg Thread.sleep(3000l); manager.getArtifactChecksum(artifact1BasePath, "md5"); Thread.sleep(3000l); assertEquals("Failed to expire checksums from cache!", 1, manager.getSize()); } @Test public void testDigests() throws NoSuchAlgorithmException, IOException, CloneNotSupportedException { String s = "This is a test."; MessageDigest md5Digest = MessageDigest.getInstance("MD5"); MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1"); md5Digest.update(s.getBytes()); sha1Digest.update(s.getBytes()); String md5 = MessageDigestUtils.convertToHexadecimalString(md5Digest); String sha1 = MessageDigestUtils.convertToHexadecimalString(sha1Digest); assertEquals("Incorrect MD5 sum!", "120ea8a25e5d487bf68b5f7096440019", md5); assertEquals("Incorrect SHA-1 sum!", "afa6c8b3a2fae95785dc7d9685a57835d703ac88", sha1); System.out.println("md5: " + md5); System.out.println("sha1: " + sha1); } }
package org.elasticsearch.xpack.core.ml.inference.trainedmodel.langident; import org.apache.lucene.util.RamUsageEstimator; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.ConstructingObjectParser; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.xpack.core.ml.inference.results.ClassificationInferenceResults; import org.elasticsearch.xpack.core.ml.inference.results.InferenceResults; import org.elasticsearch.xpack.core.ml.inference.results.TopClassEntry; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.ClassificationConfig; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.InferenceConfig; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.InferenceHelpers; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.LenientlyParsedTrainedModel; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.PredictionFieldType; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.StrictlyParsedTrainedModel; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.TargetType; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.inference.InferenceModel; import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; import static org.elasticsearch.xpack.core.ml.inference.utils.Statistics.softMax; public class LangIdentNeuralNetwork implements StrictlyParsedTrainedModel, LenientlyParsedTrainedModel, InferenceModel { public static final ParseField NAME = new ParseField("lang_ident_neural_network"); public static final ParseField EMBEDDED_VECTOR_FEATURE_NAME = new ParseField("embedded_vector_feature_name"); public static final ParseField HIDDEN_LAYER = new ParseField("hidden_layer"); public static final ParseField SOFTMAX_LAYER = new ParseField("softmax_layer"); public static final ConstructingObjectParser<LangIdentNeuralNetwork, Void> STRICT_PARSER = createParser(false); public static final ConstructingObjectParser<LangIdentNeuralNetwork, Void> LENIENT_PARSER = createParser(true); private static final List<String> LANGUAGE_NAMES = Arrays.asList( "eo", "co", "eu", "ta", "de", "mt", "ps", "te", "su", "uz", "zh-Latn", "ne", "nl", "sw", "sq", "hmn", "ja", "no", "mn", "so", "ko", "kk", "sl", "ig", "mr", "th", "zu", "ml", "hr", "bs", "lo", "sd", "cy", "hy", "uk", "pt", "lv", "iw", "cs", "vi", "jv", "be", "km", "mk", "tr", "fy", "am", "zh", "da", "sv", "fi", "ht", "af", "la", "id", "fil", "sm", "ca", "el", "ka", "sr", "it", "sk", "ru", "ru-Latn", "bg", "ny", "fa", "haw", "gl", "et", "ms", "gd", "bg-Latn", "ha", "is", "ur", "mi", "hi", "bn", "hi-Latn", "fr", "yi", "hu", "xh", "my", "tg", "ro", "ar", "lb", "el-Latn", "st", "ceb", "kn", "az", "si", "ky", "mg", "en", "gu", "es", "pl", "ja-Latn", "ga", "lt", "sn", "yo", "pa", "ku"); private static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(LangIdentNeuralNetwork.class); private static final int EMBEDDING_VECTOR_LENGTH = 80; @SuppressWarnings("unchecked") private static ConstructingObjectParser<LangIdentNeuralNetwork, Void> createParser(boolean lenient) { ConstructingObjectParser<LangIdentNeuralNetwork, Void> parser = new ConstructingObjectParser<>( NAME.getPreferredName(), lenient, a -> new LangIdentNeuralNetwork((String) a[0], (LangNetLayer) a[1], (LangNetLayer) a[2])); parser.declareString(constructorArg(), EMBEDDED_VECTOR_FEATURE_NAME); parser.declareObject(constructorArg(), (p, c) -> lenient ? LangNetLayer.LENIENT_PARSER.apply(p, c) : LangNetLayer.STRICT_PARSER.apply(p, c), HIDDEN_LAYER); parser.declareObject(constructorArg(), (p, c) -> lenient ? LangNetLayer.LENIENT_PARSER.apply(p, c) : LangNetLayer.STRICT_PARSER.apply(p, c), SOFTMAX_LAYER); return parser; } public static LangIdentNeuralNetwork fromXContentStrict(XContentParser parser) { return STRICT_PARSER.apply(parser, null); } public static LangIdentNeuralNetwork fromXContentLenient(XContentParser parser) { return LENIENT_PARSER.apply(parser, null); } private final LangNetLayer hiddenLayer; private final LangNetLayer softmaxLayer; private final String embeddedVectorFeatureName; public LangIdentNeuralNetwork(String embeddedVectorFeatureName, LangNetLayer hiddenLayer, LangNetLayer softmaxLayer) { this.embeddedVectorFeatureName = ExceptionsHelper.requireNonNull(embeddedVectorFeatureName, EMBEDDED_VECTOR_FEATURE_NAME); this.hiddenLayer = ExceptionsHelper.requireNonNull(hiddenLayer, HIDDEN_LAYER); this.softmaxLayer = ExceptionsHelper.requireNonNull(softmaxLayer, SOFTMAX_LAYER); } public LangIdentNeuralNetwork(StreamInput in) throws IOException { this.embeddedVectorFeatureName = in.readString(); this.hiddenLayer = new LangNetLayer(in); this.softmaxLayer = new LangNetLayer(in); } @Override public InferenceResults infer(Map<String, Object> fields, InferenceConfig config, Map<String, String> featureDecoderMap) { if (config.requestingImportance()) { throw ExceptionsHelper.badRequestException("[{}] model does not supports feature importance", NAME.getPreferredName()); } if (config instanceof ClassificationConfig == false) { throw ExceptionsHelper.badRequestException("[{}] model only supports classification", NAME.getPreferredName()); } Object vector = fields.get(embeddedVectorFeatureName); if (vector instanceof double[] == false) { throw ExceptionsHelper.badRequestException("[{}] model could not find non-null numerical array named [{}]", NAME.getPreferredName(), embeddedVectorFeatureName); } double[] embeddedVector = (double[]) vector; if (embeddedVector.length != EMBEDDING_VECTOR_LENGTH) { throw ExceptionsHelper.badRequestException("[{}] model is expecting embedding vector of length [{}] but got [{}]", NAME.getPreferredName(), EMBEDDING_VECTOR_LENGTH, embeddedVector.length); } double[] h0 = hiddenLayer.productPlusBias(false, embeddedVector); double[] scores = softmaxLayer.productPlusBias(true, h0); double[] probabilities = softMax(scores); ClassificationConfig classificationConfig = (ClassificationConfig) config; Tuple<InferenceHelpers.TopClassificationValue, List<TopClassEntry>> topClasses = InferenceHelpers.topClasses( probabilities, LANGUAGE_NAMES, null, classificationConfig.getNumTopClasses(), PredictionFieldType.STRING); final InferenceHelpers.TopClassificationValue classificationValue = topClasses.v1(); assert classificationValue.getValue() >= 0 && classificationValue.getValue() < LANGUAGE_NAMES.size() : "Invalid language predicted. Predicted language index " + topClasses.v1(); return new ClassificationInferenceResults(classificationValue.getValue(), LANGUAGE_NAMES.get(classificationValue.getValue()), topClasses.v2(), Collections.emptyList(), classificationConfig, classificationValue.getProbability(), classificationValue.getScore()); } @Override public InferenceResults infer(double[] embeddedVector, InferenceConfig config) { throw new UnsupportedOperationException("[lang_ident] does not support nested inference"); } @Override public void rewriteFeatureIndices(Map<String, Integer> newFeatureIndexMapping) { if (newFeatureIndexMapping != null && newFeatureIndexMapping.isEmpty() == false) { throw new UnsupportedOperationException("[lang_ident] does not support nested inference"); } } @Override public String[] getFeatureNames() { return new String[] {embeddedVectorFeatureName}; } @Override public TargetType targetType() { return TargetType.CLASSIFICATION; } @Override public void validate() { } @Override public long estimatedNumOperations() { long numOps = hiddenLayer.getBias().length; // adding bias numOps += hiddenLayer.getWeights().length; // multiplying weights numOps += softmaxLayer.getBias().length; // adding bias numOps += softmaxLayer.getWeights().length; // multiplying softmax weights return numOps; } @Override public boolean supportsFeatureImportance() { return false; } @Override public long ramBytesUsed() { long size = SHALLOW_SIZE; size += RamUsageEstimator.sizeOf(hiddenLayer); size += RamUsageEstimator.sizeOf(softmaxLayer); return size; } @Override public String getWriteableName() { return NAME.getPreferredName(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(embeddedVectorFeatureName); this.hiddenLayer.writeTo(out); this.softmaxLayer.writeTo(out); } @Override public String getName() { return NAME.getPreferredName(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(EMBEDDED_VECTOR_FEATURE_NAME.getPreferredName(), embeddedVectorFeatureName); builder.field(HIDDEN_LAYER.getPreferredName(), hiddenLayer); builder.field(SOFTMAX_LAYER.getPreferredName(), softmaxLayer); builder.endObject(); return builder; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LangIdentNeuralNetwork that = (LangIdentNeuralNetwork) o; return Objects.equals(embeddedVectorFeatureName, that.embeddedVectorFeatureName) && Objects.equals(hiddenLayer, that.hiddenLayer) && Objects.equals(softmaxLayer, that.softmaxLayer); } @Override public int hashCode() { return Objects.hash(embeddedVectorFeatureName, hiddenLayer, softmaxLayer); } }
package org.innovateuk.ifs.registration; import org.innovateuk.ifs.BaseController; import org.innovateuk.ifs.address.resource.AddressResource; import org.innovateuk.ifs.address.resource.OrganisationAddressType; import org.innovateuk.ifs.application.service.OrganisationService; import org.innovateuk.ifs.commons.error.exception.InvalidURLException; import org.innovateuk.ifs.commons.rest.RestResult; import org.innovateuk.ifs.commons.security.UserAuthenticationService; import org.innovateuk.ifs.filter.CookieFlashMessageFilter; import org.innovateuk.ifs.invite.constant.InviteStatus; import org.innovateuk.ifs.invite.resource.ApplicationInviteResource; import org.innovateuk.ifs.invite.resource.InviteOrganisationResource; import org.innovateuk.ifs.invite.service.InviteRestService; import org.innovateuk.ifs.organisation.resource.OrganisationAddressResource; import org.innovateuk.ifs.registration.service.RegistrationService; import org.innovateuk.ifs.user.resource.OrganisationResource; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.util.CookieUtil; import org.innovateuk.ifs.util.InviteUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; import java.util.Optional; /** * This class is use as an entry point to accept a invite, to a application. */ @Controller public class AcceptInviteAuthenticatedController extends BaseController{ @Autowired private InviteRestService inviteRestService; @Autowired private CookieFlashMessageFilter cookieFlashMessageFilter; @Autowired private OrganisationService organisationService; @Autowired private RegistrationService registrationService; @Autowired private UserAuthenticationService userAuthenticationService; @Autowired private CookieUtil cookieUtil; @RequestMapping(value = "/accept-invite-authenticated/confirm-invited-organisation", method = RequestMethod.GET) public String confirmInvite(HttpServletResponse response, HttpServletRequest request, Model model) { UserResource loggedInUser = userAuthenticationService.getAuthenticatedUser(request); String hash = cookieUtil.getCookieValue(request, InviteUtil.INVITE_HASH); RestResult<ApplicationInviteResource> invite = inviteRestService.getInviteByHash(hash); if (invite.isSuccess()) { ApplicationInviteResource inviteResource = invite.getSuccessObject(); if (InviteStatus.SENT.equals(inviteResource.getStatus())) { InviteOrganisationResource inviteOrganisation = inviteRestService.getInviteOrganisationByHash(hash).getSuccessObjectOrThrowException(); Map<String, String> failureMessages = registrationService.getInvalidInviteMessages(loggedInUser, inviteResource, inviteOrganisation); if (failureMessages.size() > 0){ failureMessages.forEach((messageKey, messageValue) -> model.addAttribute(messageKey, messageValue)); return "registration/accept-invite-failure"; } OrganisationResource organisation = getUserOrInviteOrganisation(loggedInUser, inviteOrganisation); model.addAttribute("invite", inviteResource); model.addAttribute("organisation", organisation); model.addAttribute("organisationAddress", getOrganisationAddress(organisation)); model.addAttribute("acceptInviteUrl", "/accept-invite-authenticated/confirm-invited-organisation/confirm"); return "registration/confirm-registered-organisation"; } else { cookieUtil.removeCookie(response, InviteUtil.INVITE_HASH); cookieFlashMessageFilter.setFlashMessage(response, "inviteAlreadyAccepted"); return "redirect:/login"; } } else { cookieUtil.removeCookie(response, InviteUtil.INVITE_HASH); throw new InvalidURLException("Invite url is not valid", null); } } @RequestMapping(value = "/accept-invite-authenticated/confirm-invited-organisation/confirm", method = RequestMethod.GET) public String confirmedInvite(HttpServletResponse response, HttpServletRequest request, Model model) { UserResource loggedInUser = userAuthenticationService.getAuthenticatedUser(request); String hash = cookieUtil.getCookieValue(request, InviteUtil.INVITE_HASH); RestResult<ApplicationInviteResource> invite = inviteRestService.getInviteByHash(hash); if (invite.isSuccess()) { ApplicationInviteResource inviteResource = invite.getSuccessObject(); if (InviteStatus.SENT.equals(inviteResource.getStatus())) { InviteOrganisationResource inviteOrganisation = inviteRestService.getInviteOrganisationByHash(hash).getSuccessObjectOrThrowException(); Map<String, String> failureMessages = registrationService.getInvalidInviteMessages(loggedInUser, inviteResource, inviteOrganisation); if (failureMessages.size() > 0){ failureMessages.forEach((messageKey, messageValue) -> model.addAttribute(messageKey, messageValue)); return "registration/accept-invite-failure"; } inviteRestService.acceptInvite(hash, loggedInUser.getId()).getSuccessObjectOrThrowException(); cookieUtil.removeCookie(response, InviteUtil.INVITE_HASH); return "redirect:/application/"+ inviteResource.getApplication(); } else { return InviteUtil.handleAcceptedInvite(cookieFlashMessageFilter, response, cookieUtil); } } else { InviteUtil.handleInvalidInvite(response, cookieUtil); } return ""; } private OrganisationResource getUserOrInviteOrganisation(UserResource loggedInUser, InviteOrganisationResource inviteOrganisation) { OrganisationResource organisation; if(inviteOrganisation.getOrganisation() == null){ // no one has confirmed the InviteOrganisation, we can use the users organisation. organisation = organisationService.getOrganisationById(loggedInUser.getOrganisations().get(0)); }else{ organisation = organisationService.getOrganisationById(inviteOrganisation.getOrganisation()); } return organisation; } /** * Get the most import address of the organisation. If there is a operating address, use that otherwise just get the first one. */ private AddressResource getOrganisationAddress(OrganisationResource organisation) { AddressResource address = null; if (organisation.getAddresses().size() == 1) { address = organisation.getAddresses().get(0).getAddress(); } else if (!organisation.getAddresses().isEmpty()) { Optional<OrganisationAddressResource> addressOptional = organisation.getAddresses().stream().filter(a -> OrganisationAddressType.OPERATING.equals(OrganisationAddressType.valueOf(a.getAddressType().getName()))).findAny(); if (addressOptional.isPresent()) { address = addressOptional.get().getAddress(); } else { address = organisation.getAddresses().get(0).getAddress(); } } return address; } }
package org.kie.workbench.common.widgets.metadata.client.lpr; import java.util.Collections; import java.util.Date; import java.util.List; import javax.enterprise.event.Event; import javax.enterprise.event.Observes; import javax.inject.Inject; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.ui.IsWidget; import org.guvnor.common.services.shared.message.Level; import org.guvnor.common.services.shared.metadata.model.LprRuleType; import org.guvnor.common.services.shared.metadata.model.Overview; import org.guvnor.common.services.shared.validation.ValidationService; import org.guvnor.common.services.shared.validation.model.ValidationMessage; import org.guvnor.messageconsole.events.PublishMessagesEvent; import org.guvnor.messageconsole.events.SystemMessage; import org.guvnor.messageconsole.events.UnpublishMessagesEvent; import org.gwtbootstrap3.client.ui.Button; import org.jboss.errai.bus.client.api.messaging.Message; import org.jboss.errai.common.client.api.Caller; import org.jboss.errai.common.client.api.ErrorCallback; import org.jboss.errai.common.client.api.RemoteCallback; import org.jboss.errai.ioc.client.container.IOC; import org.kie.workbench.common.services.shared.lpr.LPRManageProductionService; import org.kie.workbench.common.services.shared.preferences.ApplicationPreferences; import org.kie.workbench.common.widgets.client.popups.validation.ValidationPopup; import org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants; import org.kie.workbench.common.widgets.metadata.client.KieEditor; import org.kie.workbench.common.widgets.metadata.client.KieEditorView; import org.uberfire.backend.vfs.Path; import org.uberfire.client.annotations.WorkbenchPartTitle; import org.uberfire.client.annotations.WorkbenchPartTitleDecoration; import org.uberfire.client.mvp.UpdatedLockStatusEvent; import org.uberfire.client.workbench.events.ChangeTitleWidgetEvent; import org.uberfire.ext.editor.commons.client.file.ArchivePopup; import org.uberfire.ext.editor.commons.client.file.MoveToProductionPopup; import org.uberfire.ext.editor.commons.client.file.SaveOperationService; import org.uberfire.ext.editor.commons.client.history.SaveButton; import org.uberfire.ext.widgets.common.client.callbacks.DefaultErrorCallback; import org.uberfire.mvp.Command; import org.uberfire.rpc.SessionInfo; import org.uberfire.workbench.events.NotificationEvent; import org.uberfire.workbench.model.menu.MenuItem; public abstract class LPREditor extends KieEditor { private Command moveToProdCmdWaitingForValidation = null; private final static String VALIDATION_ERROR_MESSAGE_TYPE = "VALIDATION_ERROR_"; private boolean lockedByOtherUser; @Inject private Caller<LPRManageProductionService> lprProdService; @Inject private SessionInfo sessionInfo; @Inject private Event<PublishMessagesEvent> publishMessages; @Inject private Event<UnpublishMessagesEvent> unpublishMessages; @Inject private LPRFileMenuBuilder lprMenuBuilder; public LPREditor() { } public LPREditor( KieEditorView baseView ) { super( baseView ); } protected abstract Integer getCurrentHash(); protected abstract void setDroolsMetadata(); @Override protected void makeMenuBar() { menus = lprMenuBuilder .addSave( versionRecordManager.newSaveMenuItem( new Command() { @Override public void execute() { metadata.setProductionDate( 0L ); //save as draft version onSave(); } } ) ) .addDelete( versionRecordManager.getPathToLatest() ) .addRename( versionRecordManager.getPathToLatest(), fileNameValidator ) .addCopy( versionRecordManager.getCurrentPath(), fileNameValidator ) .addMoveToProduction( new MoveToProductionCommand() ) .addArchive( new ArchiveCommand() ) // .addSimulate( new SimulateCommand() ) .addValidate( onValidate() ) .addVersionMenu( versionRecordManager.buildMenu() ) .build(); } @WorkbenchPartTitleDecoration public IsWidget getTitle() { return super.getTitle(); } @WorkbenchPartTitle public String getTitleText() { String titleText = versionRecordManager.getCurrentPath().getFileName(); //filename titleText = titleText.substring( 0, titleText.lastIndexOf( '.' ) ); //strip extension if ( metadata != null ) { //add rule status DateTimeFormat dateFormatter = DateTimeFormat.getFormat( ApplicationPreferences.getDroolsDateFormat() ); if ( metadata.getProductionDate() > 0 ) { titleText += " - Produktionssat d. " + dateFormatter.format( new Date( metadata.getProductionDate() ) ); } else { titleText += " - Kladde"; } if ( metadata.getArchivedDate() > 0 ) { titleText += " - Arkiveret d. " + dateFormatter.format( new Date( metadata.getArchivedDate() ) ); } } return titleText; } @Override protected void resetEditorPages( Overview overview ) { super.resetEditorPages( overview ); if ( metadata != null ) { metadata.setRuleType( LprRuleType.REPORT_VALIDATION ); //Mark resources managed by this editor as LPR rules } updateUI(); } @Override protected RemoteCallback<Path> getSaveSuccessCallback( final int newHash ) { final RemoteCallback<Path> superSaveSuccess = super.getSaveSuccessCallback( newHash ); return new RemoteCallback<Path>() { @Override public void callback( final Path path ) { superSaveSuccess.callback( path ); updateUI(); if ( metadata != null && metadata.getProductionDate() > 0 ) { //rule was just put into production - copy the rule to prod branch so it is ready to build & deploy lprProdService.call( new RemoteCallback<Path>() { @Override public void callback( Path path ) { notification.fire( new NotificationEvent( CommonConstants.INSTANCE.LPRItemMoveToProductionSuccessfully(), NotificationEvent.NotificationType.SUCCESS ) ); } }, new ErrorCallback<Message>() { @Override public boolean error( Message message, Throwable throwable ) { //exception already logged by DroolsLoggingToDBInterceptor //todo ttn unit test this rollback behaviour metadata.setProductionDate( 0L ); save( "Produktionsættelse rullet tilbage pga. systemfejl" ); return new DefaultErrorCallback().error( message, throwable ); } } ).copyToProductionBranch( path ); } } }; } @SuppressWarnings("unchecked") protected Command getValidationCallback( final Caller<? extends ValidationService> validationService, final KieEditorView view ) { return new Command() { @Override public void execute() { validationService.call( new RemoteCallback<List<ValidationMessage>>() { @Override public void callback( final List<ValidationMessage> results ) { String fileName = versionRecordManager.getCurrentPath().getFileName(); unpublishErrorMessages( VALIDATION_ERROR_MESSAGE_TYPE + fileName ); //remove any old error logs about validation errors if ( results == null || results.isEmpty() ) { notification.fire( new NotificationEvent( CommonConstants.INSTANCE.ItemValidatedSuccessfully(), NotificationEvent.NotificationType.SUCCESS ) ); if ( moveToProdCmdWaitingForValidation != null ) { moveToProdCmdWaitingForValidation.execute(); } } else { moveToProdCmdWaitingForValidation = null; for ( ValidationMessage result : results ) { publishErrorMessage( result.getText(), VALIDATION_ERROR_MESSAGE_TYPE + fileName, result.getColumn(), result.getLine() ); } ValidationPopup.showMessages( results ); } } }, new DefaultErrorCallback() ).validate( versionRecordManager.getCurrentPath(), view.getContent() ); } }; } private void updateUI() { updateEnabledStateOnMenuItems(); baseView.refreshTitle( getTitleText() ); changeTitleNotification.fire( new ChangeTitleWidgetEvent( place, getTitleText(), getTitle() ) ); if ( metadata != null && metadata.getArchivedDate() > 0 ) { isReadOnly = true; reload(); //we have to reload to change the view to readonly mode } } private void onEditorLockInfo( @Observes UpdatedLockStatusEvent lockInfo ) { lockedByOtherUser = !(!lockInfo.isLocked() || lockInfo.isLockedByCurrentUser()); if ( lockedByOtherUser ) { for ( MenuItem menuItem : lprMenuBuilder.getMenuItemsSyncedWithLockState() ) { menuItem.setEnabled( false ); } } else { updateEnabledStateOnMenuItems(); } } private void updateEnabledStateOnMenuItems() { if ( this.metadata != null ) { for ( MenuItem mi : menus.getItemsMap().values() ) { if ( mi instanceof SaveButton ) { Button button = ( Button ) (( SaveButton ) mi).build(); if ( CommonConstants.INSTANCE.Save().equals( button.getText() ) ) { //only allow save if rule is not archived boolean enabled = !isReadOnly && this.metadata.getArchivedDate() == 0L && versionRecordManager.isCurrentLatest(); mi.setEnabled( enabled ); } if ( CommonConstants.INSTANCE.Restore().equals( button.getText() ) ) { //only allow restore if rule is not archived and restore should save the new version in draft status //todo ttn restore is disabled until this is implemented - see issue LPR-1357 mi.setEnabled( false ); } } //only allow copy if rule is not archived if ( CommonConstants.INSTANCE.Copy().equals( mi.getCaption() ) ) { boolean enabled = this.metadata.getArchivedDate() == 0L; mi.setEnabled( enabled ); } //only allow delete, rename or 'move to production' if rule is not in production and not archived if ( CommonConstants.INSTANCE.Delete().equals( mi.getCaption() ) || CommonConstants.INSTANCE.Rename().equals( mi.getCaption() ) || CommonConstants.INSTANCE.LPRMoveToProduction().equals( mi.getCaption() ) ) { boolean enabled = !isReadOnly && this.metadata.getProductionDate() == 0 && this.metadata.getArchivedDate() == 0 && versionRecordManager.isCurrentLatest(); mi.setEnabled( enabled ); } //only allow archive if rule is in production and not already archived if ( CommonConstants.INSTANCE.LPRArchive().equals( mi.getCaption() ) ) { boolean enabled = !isReadOnly && this.metadata.getProductionDate() > 0 && this.metadata.getArchivedDate() == 0 && versionRecordManager.isCurrentLatest(); mi.setEnabled( enabled ); } } } } private void publishErrorMessage( String errorText, String messageType, int column, int line ) { SystemMessage systemMessage = new SystemMessage(); systemMessage.setText( errorText ); systemMessage.setColumn( column ); systemMessage.setLine( line ); systemMessage.setMessageType( messageType ); systemMessage.setLevel( Level.ERROR ); systemMessage.setPath( versionRecordManager.getCurrentPath() ); PublishMessagesEvent event = new PublishMessagesEvent(); event.setSessionId( sessionInfo.getId() ); event.setMessagesToPublish( Collections.singletonList( systemMessage ) ); publishMessages.fire( event ); } /** * Deletes all published messages for the current session with the given type * @param messageType null to delete all messages regardless of type */ private void unpublishErrorMessages( String messageType ) { UnpublishMessagesEvent event = new UnpublishMessagesEvent(); event.setSessionId( sessionInfo.getId() ); event.setUserId( sessionInfo.getIdentity().getIdentifier() ); event.setMessageType( messageType ); unpublishMessages.fire( event ); } private class MoveToProductionCommand implements Command { private final String MOVE_TO_PROD_DIRTY_ERROR_MESSAGE_TYPE = "MOVE_TO_PROD_DIRTY_ERROR_"; private final String MOVE_TO_PROD_SAVE_ERROR_MESSAGE_TYPE = "MOVE_TO_PROD_SAVE_ERROR_"; @Override public void execute() { //check rule has no unsaved changes before moving to production (to prevent saving unintentional changes) String fileName = versionRecordManager.getCurrentPath().getFileName(); if ( overviewWidget.isDirty() || isDirty( getCurrentHash() ) ) { String errorText = fileName + " kan ikke produktionssættes. Reglen har ikke-gemte ændringer. Gem eller fjern ændringerne."; NotificationEvent errorEvent = new NotificationEvent( errorText, NotificationEvent.NotificationType.ERROR ); notification.fire( errorEvent ); publishErrorMessage( errorText, MOVE_TO_PROD_DIRTY_ERROR_MESSAGE_TYPE + fileName, 0, 0 ); return; //abort command } unpublishErrorMessages( MOVE_TO_PROD_DIRTY_ERROR_MESSAGE_TYPE + fileName ); //remove any old error logs about unsaved changes //check rule has no validation errors before moving to production moveToProdCmdWaitingForValidation = getShowPopupCommand(); onValidate().execute(); } private Command getShowPopupCommand() { return new Command() { @Override public void execute() { moveToProdCmdWaitingForValidation = null; //we have executed, remove ourselves from the waiting position MoveToProductionPopup popup = new MoveToProductionPopup( getSaveInProdCommand() ); popup.show(); } }; } private Command getSaveInProdCommand() { return new Command() { @Override public void execute() { //check state is as expected String fileName = versionRecordManager.getCurrentPath().getFileName(); String errorText = null; if ( lockedByOtherUser ) { errorText = fileName + " kan ikke produktionssættes: Reglen er låst af en anden bruger"; } if ( concurrentUpdateSessionInfo != null ) { errorText = fileName + " kan ikke produktionssættes: Reglen blev ændret samtidigt andetsteds fra"; } if ( isReadOnly ) { errorText = fileName + " kan ikke produktionssættes: Reglen er skrivebeskyttet"; } if ( !versionRecordManager.isCurrentLatest() ) { errorText = fileName + " kan ikke produktionssættes: Kun nyeste version kan produktionssættes"; } if ( metadata.getProductionDate() > 0 ) { errorText = fileName + " kan ikke produktionssættes: Reglen er allerede i produktion"; } if ( metadata.getArchivedDate() > 0 ) { errorText = fileName + " kan ikke produktionssættes: Reglen er arkiveret"; } if ( errorText != null ) { publishErrorMessage( errorText, MOVE_TO_PROD_SAVE_ERROR_MESSAGE_TYPE + fileName, 0, 0 ); notification.fire( new NotificationEvent( errorText, NotificationEvent.NotificationType.ERROR ) ); updateEnabledStateOnMenuItems(); return; //abort command } unpublishErrorMessages( MOVE_TO_PROD_SAVE_ERROR_MESSAGE_TYPE + fileName ); //remove any old error logs about save errors //set metadata and save rule metadata.setProductionDate( new Date().getTime() ); baseView.showSaving(); save( "Produktionsættelse" ); concurrentUpdateSessionInfo = null; final SaveOperationService.SaveOperationNotifier notifier = IOC.getBeanManager().lookupBean( SaveOperationService.SaveOperationNotifier.class ).getInstance(); notifier.notify( versionRecordManager.getCurrentPath() ); } }; } } private class ArchiveCommand implements Command { private final String ARCHIVE_DIRTY_ERROR_MESSAGE_TYPE = "ARCHIVE_DIRTY_ERROR_"; private final String ARCHIVE_SAVE_ERROR_MESSAGE_TYPE = "ARCHIVE_SAVE_ERROR_"; @Override public void execute() { //check rule has no unsaved changes before moving to production (to prevent saving unintentional changes) String fileName = versionRecordManager.getCurrentPath().getFileName(); if ( overviewWidget.isDirty() || isDirty( getCurrentHash() ) ) { String errorText = fileName + " kan ikke arkiveres. Reglen har ikke-gemte ændringer. Gem eller fjern ændringerne."; NotificationEvent errorEvent = new NotificationEvent( errorText, NotificationEvent.NotificationType.ERROR ); notification.fire( errorEvent ); publishErrorMessage( errorText, ARCHIVE_DIRTY_ERROR_MESSAGE_TYPE + fileName, 0, 0 ); return; //abort command } unpublishErrorMessages( ARCHIVE_DIRTY_ERROR_MESSAGE_TYPE + fileName ); //remove old error logs about unsaved changes for this rule file ArchivePopup popup = new ArchivePopup( new Command() { @Override public void execute() { //check state is as expected String fileName = versionRecordManager.getCurrentPath().getFileName(); NotificationEvent errorEvent = null; String errorMsg = null; if ( lockedByOtherUser ) { errorMsg = fileName + " kan ikke arkiveres: Reglen er låst af en anden bruger"; } if ( concurrentUpdateSessionInfo != null ) { errorMsg = fileName + " kan ikke arkiveres: Reglen blev ændret samtidigt andetsteds fra"; } if ( isReadOnly ) { errorMsg = fileName + " kan ikke arkiveres: Reglen er skrivebeskyttet"; } if ( !versionRecordManager.isCurrentLatest() ) { errorMsg = fileName + " kan ikke arkiveres: Kun nyeste version kan arkiveres"; } if ( metadata.getProductionDate() == 0 ) { errorMsg = fileName + " kan ikke arkiveres: Reglen er ikke i produktion"; } if ( metadata.getArchivedDate() > 0 ) { errorMsg = fileName + " kan ikke arkiveres: Reglen er allerede arkiveret"; } if ( errorMsg != null ) { publishErrorMessage( errorMsg, ARCHIVE_SAVE_ERROR_MESSAGE_TYPE + fileName, 0, 0 ); notification.fire( new NotificationEvent( errorMsg, NotificationEvent.NotificationType.ERROR ) ); updateEnabledStateOnMenuItems(); return; //abort command } unpublishErrorMessages( ARCHIVE_SAVE_ERROR_MESSAGE_TYPE + fileName ); //remove any old error logs about save errors //set metadata and save rule metadata.setArchivedDate( new Date().getTime() ); baseView.showSaving(); save( "Arkivering" ); concurrentUpdateSessionInfo = null; final SaveOperationService.SaveOperationNotifier notifier = IOC.getBeanManager().lookupBean( SaveOperationService.SaveOperationNotifier.class ).getInstance(); notifier.notify( versionRecordManager.getCurrentPath() ); } } ); popup.show(); } } private class SimulateCommand implements Command { @Override public void execute() { notification.fire( new NotificationEvent( "Not yet implemented", NotificationEvent.NotificationType.ERROR ) ); } } }
package io.subutai.core.hubmanager.impl.requestor; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import io.subutai.common.peer.LocalPeer; import io.subutai.core.hubmanager.api.HubRequester; import io.subutai.core.hubmanager.api.RestClient; import io.subutai.core.hubmanager.api.RestResult; import io.subutai.core.hubmanager.api.exception.HubManagerException; import io.subutai.core.hubmanager.impl.HubManagerImpl; import io.subutai.core.metric.api.Monitor; import io.subutai.core.metric.api.pojo.P2Pinfo; import io.subutai.hub.share.dto.P2PDto; import io.subutai.hub.share.dto.SystemLogsDto; import static java.lang.String.format; public class P2pLogsSender extends HubRequester { private final Logger log = LoggerFactory.getLogger( getClass() ); private LocalPeer localPeer; private Monitor monitor; private Date lastSendDate; public P2pLogsSender( HubManagerImpl hubManager, LocalPeer localPeer, Monitor monitor, RestClient restClient ) { super( hubManager, restClient ); this.localPeer = localPeer; this.monitor = monitor; } @Override public void request() throws HubManagerException { try { sendP2PStatus(); } catch ( Exception e ) { log.error( "Error sending P2P status: {} ", e.getMessage() ); } } private void sendP2PStatus() throws HubManagerException { try { log.info( "Getting P2P status" ); List<P2Pinfo> p2Pinfos = monitor.getP2PStatus(); List<P2PDto> p2pList = Lists.newArrayList(); boolean hasProblems = false; for ( final P2Pinfo info : p2Pinfos ) { P2PDto dto = new P2PDto(); dto.setRhId( info.getRhId() ); dto.setRhVersion( info.getRhVersion() ); dto.setP2pVersion( info.getP2pVersion() ); dto.setP2pStatus( info.getP2pStatus() ); dto.setState( info.getState() ); if ( info.getP2pStatus() != 0 ) { hasProblems = true; } p2pList.add( dto ); } if ( !hasProblems && lastSendDate != null && System.currentTimeMillis() - lastSendDate.getTime() < TimeUnit.MINUTES.toMillis( 60 ) ) { return; } SystemLogsDto logsDto = new SystemLogsDto(); logsDto.setP2PInfo( p2pList ); log.info( "Sending P2P status to Bazaar..." ); String path = format( "/rest/v1/peers/%s/resource-hosts/system-logs", localPeer.getId() ); RestResult<Object> restResult = restClient.post( path, logsDto ); if ( restResult.isSuccess() ) { log.info( "P2P status was sent to Bazaar successfully" ); lastSendDate = new Date(); } } catch ( Exception e ) { throw new HubManagerException( e ); } } }
/* @java.file.header */ package org.gridgain.grid.kernal.processors.cache.distributed.near; import org.gridgain.grid.cache.*; import org.gridgain.grid.kernal.processors.cache.*; import static org.gridgain.grid.cache.GridCacheMode.*; import static org.gridgain.grid.cache.GridCachePreloadMode.*; import static org.gridgain.grid.cache.GridCacheWriteSynchronizationMode.*; /** * Partitioned cache metrics test. */ public class GridCachePartitionedMetricsSelfTest extends GridCacheTransactionalAbstractMetricsSelfTest { private static final int GRID_CNT = 2; /** {@inheritDoc} */ @Override protected GridCacheConfiguration cacheConfiguration(String gridName) throws Exception { GridCacheConfiguration cfg = super.cacheConfiguration(gridName); cfg.setCacheMode(PARTITIONED); cfg.setBackups(gridCount() - 1); cfg.setPreloadMode(SYNC); cfg.setTxSerializableEnabled(true); cfg.setWriteSynchronizationMode(FULL_SYNC); return cfg; } /** {@inheritDoc} */ @Override protected int gridCount() { return GRID_CNT; } /** {@inheritDoc} */ @Override protected int expectedReadsPerPut(boolean isPrimary) { return isPrimary ? 1 : 2; } /** {@inheritDoc} */ @Override protected int expectedMissesPerPut(boolean isPrimary) { return isPrimary ? 1 : 2; } }
package org.opendaylight.controller.netconf.util; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.ssl.SslHandler; import io.netty.util.Timeout; import io.netty.util.Timer; import io.netty.util.TimerTask; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.Promise; import org.opendaylight.controller.netconf.api.NetconfMessage; import org.opendaylight.controller.netconf.api.NetconfSession; import org.opendaylight.controller.netconf.api.NetconfSessionPreferences; import org.opendaylight.controller.netconf.util.handler.FramingMechanismHandlerFactory; import org.opendaylight.controller.netconf.util.handler.NetconfMessageAggregator; import org.opendaylight.controller.netconf.util.handler.NetconfMessageChunkDecoder; import org.opendaylight.controller.netconf.util.messages.FramingMechanism; import org.opendaylight.controller.netconf.util.xml.XmlElement; import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants; import org.opendaylight.controller.netconf.util.xml.XmlUtil; import org.opendaylight.protocol.framework.AbstractSessionNegotiator; import org.opendaylight.protocol.framework.SessionListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import java.util.concurrent.TimeUnit; public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends NetconfSession> extends AbstractSessionNegotiator<NetconfMessage, S> { private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class); public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler"; protected final P sessionPreferences; private final SessionListener sessionListener; private Timeout timeout; /** * Possible states for Finite State Machine */ private enum State { IDLE, OPEN_WAIT, FAILED, ESTABLISHED } private State state = State.IDLE; private final Timer timer; private final long connectionTimeoutMillis; protected AbstractNetconfSessionNegotiator(P sessionPreferences, Promise<S> promise, Channel channel, Timer timer, SessionListener sessionListener, long connectionTimeoutMillis) { super(promise, channel); this.sessionPreferences = sessionPreferences; this.timer = timer; this.sessionListener = sessionListener; this.connectionTimeoutMillis = connectionTimeoutMillis; } @Override protected void startNegotiation() { final Optional<SslHandler> sslHandler = getSslHandler(channel); if (sslHandler.isPresent()) { Future<Channel> future = sslHandler.get().handshakeFuture(); future.addListener(new GenericFutureListener<Future<? super Channel>>() { @Override public void operationComplete(Future<? super Channel> future) throws Exception { Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful"); logger.debug("Ssl handshake complete"); start(); } }); } else start(); } private static Optional<SslHandler> getSslHandler(Channel channel) { final SslHandler sslHandler = channel.pipeline().get(SslHandler.class); return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler); } private void start() { final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage(); logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument())); channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ChannelHandler() { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause); cancelTimeout(); negotiationFailed(cause); changeState(State.FAILED); } }); timeout = this.timer.newTimeout(new TimerTask() { @Override public void run(final Timeout timeout) throws Exception { synchronized (this) { if (state != State.ESTABLISHED) { logger.debug("Connection timeout after {}, session is in state {}", timeout, state); final IllegalStateException cause = new IllegalStateException( "Session was not established after " + timeout); negotiationFailed(cause); changeState(State.FAILED); } else if(channel.isOpen()) { channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER); } } } }, connectionTimeoutMillis, TimeUnit.MILLISECONDS); sendMessage(helloMessage); changeState(State.OPEN_WAIT); } private void cancelTimeout() { if(timeout!=null) timeout.cancel(); } private void sendMessage(NetconfMessage message) { this.channel.writeAndFlush(message); } @Override protected void handleMessage(NetconfMessage netconfMessage) { final Document doc = netconfMessage.getDocument(); if (isHelloMessage(doc)) { if (containsBase11Capability(doc) && containsBase11Capability(sessionPreferences.getHelloMessage().getDocument())) { channel.pipeline().replace("frameEncoder", "frameEncoder", FramingMechanismHandlerFactory.createHandler(FramingMechanism.CHUNK)); channel.pipeline().replace("aggregator", "aggregator", new NetconfMessageAggregator(FramingMechanism.CHUNK)); channel.pipeline().addAfter("aggregator", "chunkDecoder", new NetconfMessageChunkDecoder()); } changeState(State.ESTABLISHED); S session = getSession(sessionListener, channel, netconfMessage); negotiationSuccessful(session); } else { final IllegalStateException cause = new IllegalStateException( "Received message was not hello as expected, but was " + XmlUtil.toString(doc)); logger.warn("Negotiation of netconf session failed", cause); negotiationFailed(cause); } } protected abstract S getSession(SessionListener sessionListener, Channel channel, NetconfMessage message); private boolean isHelloMessage(Document doc) { try { XmlElement.fromDomElementWithExpected(doc.getDocumentElement(), "hello", XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); } catch (IllegalArgumentException | IllegalStateException e) { return false; } return true; } private synchronized void changeState(final State newState) { logger.debug("Changing state from : {} to : {}", state, newState); Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state, newState); this.state = newState; } private boolean containsBase11Capability(final Document doc) { final NodeList nList = doc.getElementsByTagName("capability"); for (int i = 0; i < nList.getLength(); i++) { if (nList.item(i).getTextContent().contains("base:1.1")) { return true; } } return false; } private static boolean isStateChangePermitted(State state, State newState) { if (state == State.IDLE && newState == State.OPEN_WAIT) return true; if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) return true; if (state == State.OPEN_WAIT && newState == State.FAILED) return true; logger.debug("Transition from {} to {} is not allowed", state, newState); return false; } }
package org.gemoc.execution.engine.io.views.engine; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.Observable; import java.util.Observer; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.gemoc.commons.eclipse.ui.TreeViewerHelper; import org.gemoc.execution.engine.core.GemocRunningEnginesRegistry; import org.gemoc.execution.engine.core.ObservableBasicExecutionEngine; import org.gemoc.execution.engine.io.Activator; import org.gemoc.execution.engine.io.SharedIcons; import org.gemoc.execution.engine.io.views.IMotorSelectionListener; import org.gemoc.gemoc_language_workbench.api.core.GemocExecutionEngine; public class EnginesStatusView extends ViewPart implements Observer { /** * The ID of the view as specified by the extension. */ public static final String ID = "org.gemoc.execution.engine.io.views.engine.EnginesStatusView"; public TreeViewer _viewer; private ViewContentProvider _contentProvider; /** * The constructor. */ public EnginesStatusView() { } private Object _lastSelection; /** * This is a callback that will allow us * to create the viewer and initialize it. */ public void createPartControl(Composite parent) { _viewer = new TreeViewer(parent, SWT.FULL_SELECTION | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); _contentProvider = new ViewContentProvider(); _viewer.setContentProvider(_contentProvider); ColumnViewerToolTipSupport.enableFor(_viewer); _viewer.addSelectionChangedListener( new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (event.getSelection() instanceof TreeSelection) { TreeSelection selection = (TreeSelection)event.getSelection(); if (selection.getPaths().length > 0) _lastSelection = selection.getPaths()[0].getFirstSegment(); } fireEngineSelectionChanged(); } }); createColumns(_viewer); _viewer.setColumnProperties( new String[] {"Identifier", "Step", "Status"} ); _viewer.getTree().setHeaderVisible(true); Font mono = JFaceResources.getFont(JFaceResources.TEXT_FONT); _viewer.getTree().setFont(mono); // Create the help context id for the viewer's control PlatformUI.getWorkbench().getHelpSystem().setHelp(_viewer.getControl(), "org.gemoc.execution.engine.io.viewer"); // register for changes in the RunningEngineRegistry org.gemoc.execution.engine.Activator.getDefault().gemocRunningEngineRegistry.addObserver(this); } /** * used by createPartControl * Creates the columns in the view * @param viewer */ private void createColumns(TreeViewer viewer) { TreeColumn column1 = new TreeColumn(viewer.getTree(), SWT.LEFT); column1.setText("Identifier"); // column1.setWidth(250); // column1.setResizable(true); TreeViewerColumn viewerColumn1 = new TreeViewerColumn(viewer, column1); viewerColumn1.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { String result = ""; if (element instanceof GemocExecutionEngine) { GemocExecutionEngine engine = (GemocExecutionEngine)element; result = engine.getModelUnderExecutionResource().getURI().segmentsList().get(engine.getModelUnderExecutionResource().getURI().segments().length-1); } return result; } @Override public Image getImage(Object element) { Image result = null; if (element instanceof GemocExecutionEngine) { GemocExecutionEngine engine = (GemocExecutionEngine)element; switch (engine.getEngineStatus().getRunningStatus()) { case Running: result = SharedIcons.getSharedImage(SharedIcons.RUNNING_ENGINE_ICON); break; case Stopped: result = SharedIcons.getSharedImage(SharedIcons.STOPPED_ENGINE_ICON); break; case WaitingLogicalStepSelection: result = SharedIcons.getSharedImage(SharedIcons.WAITING_ENGINE_ICON); break; case Initializing: result = SharedIcons.getSharedImage(SharedIcons.ENGINE_ICON); break; default: break; } } return result; } @Override public String getToolTipText(Object element) { String result = ""; if (element instanceof GemocExecutionEngine) { GemocExecutionEngine engine = (GemocExecutionEngine)element; GemocRunningEnginesRegistry registry = org.gemoc.execution.engine.Activator.getDefault().gemocRunningEngineRegistry; for (Entry<String, GemocExecutionEngine> e : registry.getRunningEngines().entrySet()) { if (e.getValue() == engine) { result = e.getKey(); break; } } } return result; } }); TreeColumn column3 = new TreeColumn(viewer.getTree(), SWT.LEFT); column3.setText("Step"); // column3.setWidth(50); // column3.setResizable(true); TreeViewerColumn viewerColumn3 = new TreeViewerColumn(viewer, column3); viewerColumn3.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { String result = ""; if (element instanceof GemocExecutionEngine) { GemocExecutionEngine engine = (GemocExecutionEngine)element; result = String.format("%d", engine.getEngineStatus().getNbLogicalStepRun()); } return result; } }); TreeColumn column4 = new TreeColumn(viewer.getTree(), SWT.LEFT); column4.setText("Details"); // column4.setWidth(250); // column4.setResizable(true); TreeViewerColumn viewerColumn4 = new TreeViewerColumn(viewer, column4); viewerColumn4.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { String result = ""; if (element instanceof GemocExecutionEngine) { GemocExecutionEngine engine = (GemocExecutionEngine)element; switch(engine.getEngineStatus().getRunningStatus()) { case Initializing : result = "Initializing"; break; case Running: result = "Running"; break; case WaitingLogicalStepSelection: result = "Waiting LogicalStep Selection"; break; case Stopped: result = "Stopped"; break; } } return result; } }); } // public MenuManager menuMgr; // private void hookContextMenu() // //MenuManager menuManager = new MenuManager(); // MenuManager menuManager = new MenuManager(); // menuMgr = menuManager; // Menu menu = menuManager.createContextMenu(viewer.getControl()); // viewer.getControl().setMenu(menu); // getSite().registerContextMenu(menuManager, viewer); // // make the selection available // getSite().setSelectionProvider(viewer); /** * Passing the focus request to the viewer's control. */ public void setFocus() { _viewer.getControl().setFocus(); } /** * get the selection * @return the engine selected or null if no engine selected */ public GemocExecutionEngine getSelectedEngine() { try{ IStructuredSelection selection = (IStructuredSelection) _viewer.getSelection(); return (GemocExecutionEngine)selection.getFirstElement(); } catch(Exception e){ Activator.getDefault().error(e.getMessage(), e); } return null; } public void removeStoppedEngines(){ Display.getDefault().asyncExec(new Runnable() { public void run() { // we may be triggered by a registry change or by an engine change // if registry changes, then may need to observe the new engine List<String> engineStopped = new ArrayList<String>(); for( Entry<String, GemocExecutionEngine> engineEntry :org.gemoc.execution.engine.Activator.getDefault().gemocRunningEngineRegistry.getRunningEngines().entrySet()){ switch(engineEntry.getValue().getEngineStatus().getRunningStatus()){ case Stopped: engineStopped.add(engineEntry.getKey()); break; default: } } for(String engine : engineStopped){ org.gemoc.execution.engine.Activator.getDefault().gemocRunningEngineRegistry.getRunningEngines().remove(engine); } update(null, null); } }); } @Override public void update(Observable o, Object arg) { Display.getDefault().syncExec(new Runnable() { public void run() { // we may be triggered by a registry change or by an engine change // if registry changes, then may need to observe the new engine for (GemocExecutionEngine engine : org.gemoc.execution.engine.Activator.getDefault().gemocRunningEngineRegistry.getRunningEngines().values()){ ObservableBasicExecutionEngine observable = (ObservableBasicExecutionEngine) engine; observable.addObserver(EnginesStatusView.this); } _viewer.setInput(org.gemoc.execution.engine.Activator.getDefault().gemocRunningEngineRegistry); TreeViewerHelper.resizeColumns(_viewer); if (_lastSelection != null) { TreePath treePath = new TreePath(new Object[] {_lastSelection}); TreeSelection newSelection = new TreeSelection(treePath); _viewer.setSelection(newSelection, true); } _viewer.expandAll(); } }); } private ArrayList<IMotorSelectionListener> _motorSelectionListeners = new ArrayList<IMotorSelectionListener>(); public void addMotorSelectionListener(IMotorSelectionListener listener) { assert(listener != null); _motorSelectionListeners.add(listener); } public void removeMotorSelectionListener(IMotorSelectionListener listener) { assert(listener != null); _motorSelectionListeners.remove(listener); } private void fireEngineSelectionChanged() { GemocExecutionEngine engine = getSelectedEngine(); for(IMotorSelectionListener listener: _motorSelectionListeners) { listener.motorSelectionChanged(engine); } } }
package cc.topicexplorer.plugin.fulltext.preprocessing.tables.document; import java.sql.SQLException; import cc.topicexplorer.chain.commands.TableCreateCommand; public class DocumentCreate extends TableCreateCommand { @Override public void createTable() { try { database.executeUpdateQuery("ALTER IGNORE TABLE `" + this.tableName + "` ADD COLUMN FULLTEXT$FULLTEXT TEXT COLLATE UTF8_BIN;"); } catch (SQLException e) { logger.error("Column FULLTEXT$FULLTEXT could not be added to table " + this.tableName); throw new RuntimeException(e); } } @Override public void dropTable() { try { this.database.executeUpdateQuery("ALTER TABLE " + this.tableName + " DROP COLUMN FULLTEXT$FULLTEXT;"); } catch (SQLException e) { if (e.getErrorCode() != 1091) { // MySQL Error code for 'Can't DROP // ..; check that column/key exists logger.error("Document.dropColumns: Cannot drop column."); throw new RuntimeException(e); } } } @Override public void setTableName() { tableName = "DOCUMENT"; } @Override public void addDependencies() { beforeDependencies.add("DocumentCreate"); } }
package org.openhab.binding.zwave.internal.converter; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import org.openhab.binding.zwave.ZWaveBindingConfig; import org.openhab.binding.zwave.ZWaveBindingProvider; import org.openhab.binding.zwave.internal.protocol.ZWaveController; import org.openhab.binding.zwave.internal.protocol.ZWaveNode; import org.openhab.binding.zwave.internal.protocol.NodeStage; import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass; import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass.CommandClass; import org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent; import org.openhab.core.events.EventPublisher; import org.openhab.core.items.Item; import org.openhab.core.library.items.ContactItem; import org.openhab.core.library.items.DimmerItem; import org.openhab.core.library.items.NumberItem; import org.openhab.core.library.items.RollershutterItem; import org.openhab.core.library.items.SwitchItem; import org.openhab.core.types.Command; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ZWaveConverterHandler class. Acts as a factory * and manager of all the converters the binding can * use to convert between the Z-Wave api and the binding. * @author Jan-Willem Spuij * @since 1.4.0 */ public class ZWaveConverterHandler { private static final Logger logger = LoggerFactory.getLogger(ZWaveConverterHandler.class); private final Map<CommandClass, ZWaveCommandClassConverter<?>> converters = new HashMap<CommandClass, ZWaveCommandClassConverter<?>>(); private final Map<Class<? extends Item>, CommandClass[]> preferredCommandClasses = new HashMap<Class<? extends Item>, CommandClass[]>(); private final ZWaveController controller; private final ZWaveInfoConverter infoConverter; /** * Constructor. Creates a new instance of the {@ link ZWaveConverterHandler} class. * @param controller the {@link ZWaveController} to use to send messages. * @param eventPublisher the {@link EventPublisher} to use to post updates. */ public ZWaveConverterHandler(ZWaveController controller, EventPublisher eventPublisher) { this.controller = controller; // add converters here converters.put(CommandClass.THERMOSTAT_SETPOINT, new ZWaveThermostatSetpointConverter(controller, eventPublisher)); converters.put(CommandClass.THERMOSTAT_MODE, new ZWaveThermostatModeConverter(controller, eventPublisher)); converters.put(CommandClass.THERMOSTAT_FAN_MODE, new ZWaveThermostatFanModeConverter(controller, eventPublisher)); converters.put(CommandClass.THERMOSTAT_OPERATING_STATE, new ZWaveThermostatOperatingStateConverter(controller, eventPublisher)); converters.put(CommandClass.THERMOSTAT_FAN_STATE, new ZWaveThermostatFanStateConverter(controller, eventPublisher)); converters.put(CommandClass.BATTERY, new ZWaveBatteryConverter(controller, eventPublisher)); converters.put(CommandClass.SWITCH_BINARY, new ZWaveBinarySwitchConverter(controller, eventPublisher)); converters.put(CommandClass.SWITCH_MULTILEVEL, new ZWaveMultiLevelSwitchConverter(controller, eventPublisher)); converters.put(CommandClass.SENSOR_BINARY, new ZWaveBinarySensorConverter(controller, eventPublisher)); converters.put(CommandClass.SENSOR_MULTILEVEL, new ZWaveMultiLevelSensorConverter(controller, eventPublisher)); converters.put(CommandClass.SENSOR_ALARM, new ZWaveAlarmSensorConverter(controller, eventPublisher)); converters.put(CommandClass.METER, new ZWaveMeterConverter(controller, eventPublisher)); converters.put(CommandClass.BASIC, new ZWaveBasicConverter(controller, eventPublisher)); converters.put(CommandClass.SCENE_ACTIVATION, new ZWaveSceneConverter(controller, eventPublisher)); converters.put(CommandClass.ALARM, new ZWaveAlarmConverter(controller, eventPublisher)); infoConverter = new ZWaveInfoConverter(controller, eventPublisher); // add preferred command classes per Item class here preferredCommandClasses.put(SwitchItem.class, new CommandClass[] { CommandClass.SWITCH_BINARY, CommandClass.SWITCH_MULTILEVEL, CommandClass.METER, CommandClass.BASIC, CommandClass.SENSOR_BINARY, CommandClass.SENSOR_ALARM }); preferredCommandClasses.put(DimmerItem.class, new CommandClass[] { CommandClass.SWITCH_MULTILEVEL, CommandClass.SWITCH_BINARY, CommandClass.BASIC, CommandClass.SENSOR_MULTILEVEL, CommandClass.SENSOR_BINARY, CommandClass.SENSOR_ALARM }); preferredCommandClasses.put(RollershutterItem.class, new CommandClass[] { CommandClass.SWITCH_MULTILEVEL, CommandClass.SWITCH_BINARY, CommandClass.BASIC, CommandClass.SENSOR_MULTILEVEL, CommandClass.SENSOR_BINARY, CommandClass.SENSOR_ALARM }); preferredCommandClasses.put(NumberItem.class, new CommandClass[] { CommandClass.SENSOR_MULTILEVEL, CommandClass.METER, CommandClass.SWITCH_MULTILEVEL, CommandClass.BATTERY, CommandClass.BASIC, CommandClass.SENSOR_BINARY, CommandClass.SENSOR_ALARM, CommandClass.SWITCH_BINARY, CommandClass.THERMOSTAT_SETPOINT, CommandClass.THERMOSTAT_MODE, CommandClass.THERMOSTAT_FAN_MODE, CommandClass.THERMOSTAT_OPERATING_STATE, CommandClass.THERMOSTAT_FAN_STATE}); preferredCommandClasses.put(ContactItem.class, new CommandClass[] { CommandClass.SENSOR_BINARY, CommandClass.SENSOR_ALARM, CommandClass.SWITCH_BINARY, CommandClass.BASIC }); } /** * Returns a converter to convert between the Z-Wave API and the binding. * @param commandClass the {@link CommandClass} to create a converter for. * @return a {@link ZWaveCommandClassConverter} or null if a converter is not found. */ public ZWaveCommandClassConverter<?> getConverter(CommandClass commandClass) { return converters.get(commandClass); } /** * Returns the command class that provides the best suitable converter to convert between the Z-Wave API and the binding. * @param item the {@link item} to resolve a converter for. * @param node the {@link ZWaveNode} node to resolve a Command class on. * @param the enpoint ID to use to resolve a converter. * @return the {@link ZWaveCommandClass} that can be used to get a converter suitable to do the conversion. */ private ZWaveCommandClass resolveConverter(Item item, ZWaveNode node, int endpointId) { if(item == null) { return null; } if (!preferredCommandClasses.containsKey(item.getClass())) { logger.warn("No preferred command classes found for item class = {}", item.getClass().toString()); return null; } for (CommandClass commandClass : preferredCommandClasses.get(item.getClass())) { ZWaveCommandClass result = node.resolveCommandClass(commandClass, endpointId); if (result != null && converters.containsKey(commandClass)) { return result; } } logger.warn("No matching command classes found for item class = {}, node id = {}, endpoint id = {}", item.getClass().toString(), node.getNodeId(), endpointId); return null; } /** * Execute refresh method. This method is called every time a binding item is * refreshed and the corresponding node should be sent a message. * @param provider the {@link ZWaveBindingProvider} that provides the item * @param itemName the name of the item to poll. * @param forceRefresh indicates that a polling refresh should be forced. */ @SuppressWarnings("unchecked") public void executeRefresh(ZWaveBindingProvider provider, String itemName, boolean forceRefresh) { ZWaveBindingConfig bindingConfiguration = provider.getZwaveBindingConfig(itemName); ZWaveCommandClass commandClass; String commandClassName = bindingConfiguration.getArguments().get("command"); // this binding is configured not to poll. if (!forceRefresh && bindingConfiguration.getRefreshInterval() != null && 0 == bindingConfiguration.getRefreshInterval()) return; ZWaveNode node = this.controller.getNode(bindingConfiguration.getNodeId()); // ignore nodes that are not initialized. if (node == null) return; if (commandClassName != null) { // this is a report item, handle it with the report info converter. if (commandClassName.equalsIgnoreCase("info")) { infoConverter.executeRefresh(provider.getItem(itemName), node, bindingConfiguration.getEndpoint(), bindingConfiguration.getArguments()); return; } // ignore nodes that are not initialized or dead. if (node.getNodeStage() != NodeStage.DONE) return; commandClass = node.resolveCommandClass(CommandClass.getCommandClass(commandClassName), bindingConfiguration.getEndpoint()); if (commandClass == null) { logger.warn("No command class found for item = {}, command class name = {}, ignoring execute refresh.", itemName, commandClassName); return; } } else { commandClass = resolveConverter(provider.getItem(itemName), node , bindingConfiguration.getEndpoint()); } if (commandClass == null) { logger.warn("No converter found for item = {}, ignoring execute refresh.", itemName); return; } ZWaveCommandClassConverter<ZWaveCommandClass> converter = (ZWaveCommandClassConverter<ZWaveCommandClass>) getConverter(commandClass.getCommandClass()); if (converter == null) { logger.warn("No converter found for item = {}, ignoring execute refresh.", itemName); return; } if (bindingConfiguration.getRefreshInterval() == null) { bindingConfiguration.setRefreshInterval(converter.getRefreshInterval()); // this binding is configured not to poll. if (!forceRefresh && 0 == bindingConfiguration.getRefreshInterval()) return; } // not enough time has passed to refresh the item. if (!forceRefresh && bindingConfiguration.getLastRefreshed() != null && (bindingConfiguration.getLastRefreshed().getTime() + (bindingConfiguration.getRefreshInterval() * 1000) > Calendar.getInstance().getTimeInMillis())) return; bindingConfiguration.setLastRefreshed(Calendar.getInstance().getTime()); converter.executeRefresh(node, commandClass, bindingConfiguration.getEndpoint(), bindingConfiguration.getArguments()); } /** * Get the refresh interval for an item binding * * @param provider * the {@link ZWaveBindingProvider} that provides the item * @param itemName * the name of the item to poll. */ @SuppressWarnings("unchecked") public Integer getRefreshInterval(ZWaveBindingProvider provider, String itemName) { ZWaveBindingConfig bindingConfiguration = provider.getZwaveBindingConfig(itemName); ZWaveCommandClass commandClass; String commandClassName = bindingConfiguration.getArguments().get("command"); // this binding is configured not to poll. if (bindingConfiguration.getRefreshInterval() != null && 0 == bindingConfiguration.getRefreshInterval()) return 0; ZWaveNode node = this.controller.getNode(bindingConfiguration.getNodeId()); // ignore nodes that are not initialized. if (node == null) return 0; if (commandClassName != null) { // this is a report item, handle it with the report info converter. if (commandClassName.equalsIgnoreCase("info")) { return infoConverter.getRefreshInterval(); } commandClass = node.resolveCommandClass(CommandClass.getCommandClass(commandClassName), bindingConfiguration.getEndpoint()); if (commandClass == null) { logger.warn("No command class found for item = {}, command class name = {}, using 0 refresh interval.", itemName, commandClassName); return 0; } } else { commandClass = resolveConverter(provider.getItem(itemName), node, bindingConfiguration.getEndpoint()); } if (commandClass == null) { logger.warn("No converter found for item = {}, using 0 refresh interval.", itemName); return 0; } ZWaveCommandClassConverter<ZWaveCommandClass> converter = (ZWaveCommandClassConverter<ZWaveCommandClass>) getConverter(commandClass .getCommandClass()); if (converter == null) { logger.warn("No converter found for item = {}, using 0 refresh interval.", itemName); return 0; } if (bindingConfiguration.getRefreshInterval() == null) { bindingConfiguration.setRefreshInterval(converter.getRefreshInterval()); } return bindingConfiguration.getRefreshInterval(); } /** * Handles an incoming {@link ZWaveCommandClassValueEvent}. Implement * this message in derived classes to convert the value and post an * update on the openHAB bus. * @param provider the {@link ZWaveBindingProvider} that provides the item * @param itemName the name of the item that will receive the event. * @param event the received {@link ZWaveCommandClassValueEvent}. */ public void handleEvent(ZWaveBindingProvider provider, String itemName, ZWaveCommandClassValueEvent event) { ZWaveBindingConfig bindingConfiguration = provider.getZwaveBindingConfig(itemName); Item item = provider.getItem(itemName); String commandClassName = bindingConfiguration.getArguments().get("command"); boolean respondToBasic = "true".equalsIgnoreCase(bindingConfiguration.getArguments().get("respond_to_basic")); logger.trace("Getting converter for item = {}, command class = {}, item command class = {}", itemName, event.getCommandClass().getLabel(), commandClassName); if (item == null) { return; } // check whether this item is bound to the right command class. if (commandClassName != null && !commandClassName.equalsIgnoreCase(event.getCommandClass().getLabel().toLowerCase()) && !(respondToBasic && event.getCommandClass() == CommandClass.BASIC)) { return; } ZWaveCommandClassConverter<?> converter = this.getConverter(event.getCommandClass()); if (converter == null) { logger.warn("No converter found for command class = {}, ignoring event.",event.getCommandClass().toString()); return; } converter.handleEvent(event, item, bindingConfiguration.getArguments()); } /** * Receives a command from openHAB and translates it to an operation * on the Z-Wave network. * @param provider the {@link ZWaveBindingProvider} that provides the item * @param itemName the name of the item that will receive the event. * @param command the received {@link Command} */ @SuppressWarnings("unchecked") public void receiveCommand(ZWaveBindingProvider provider, String itemName, Command command) { ZWaveBindingConfig bindingConfiguration = provider.getZwaveBindingConfig(itemName); ZWaveNode node = this.controller.getNode(bindingConfiguration.getNodeId()); if(node == null) { logger.error("Item {} has non existant node {}", itemName, bindingConfiguration.getNodeId()); return; } ZWaveCommandClass commandClass; String commandClassName = bindingConfiguration.getArguments().get("command"); if (commandClassName != null) { commandClass = node.resolveCommandClass(CommandClass.getCommandClass(commandClassName), bindingConfiguration.getEndpoint()); if (commandClass == null) { logger.warn("No command class found for item = {}, command class name = {}, ignoring command.", itemName, commandClassName); return; } } else { commandClass = resolveConverter(provider.getItem(itemName), node , bindingConfiguration.getEndpoint()); } if (commandClass == null) { logger.warn("No converter found for item = {}, ignoring command.", itemName); return; } ZWaveCommandClassConverter<ZWaveCommandClass> converter = (ZWaveCommandClassConverter<ZWaveCommandClass>) getConverter(commandClass.getCommandClass()); if (converter == null) { logger.warn("No converter found for item = {}, ignoring command.", itemName); return; } converter.receiveCommand(provider.getItem(itemName), command, node, commandClass, bindingConfiguration.getEndpoint(), bindingConfiguration.getArguments()); } }
package gov.nih.nci.cagrid.introduce.test.unit; import gov.nih.nci.cagrid.introduce.common.CommonTools; import junit.framework.TestCase; public class IntroduceToolsTestCase extends TestCase { protected void setUp() throws Exception { super.setUp(); } public void testIsValidSeviceName() { assertTrue(CommonTools.isValidServiceName("MyService")); assertTrue(CommonTools.isValidServiceName("My123")); assertTrue(CommonTools.isValidServiceName("My123_Service")); assertTrue(CommonTools.isValidServiceName("My123_TestService")); assertTrue(CommonTools.isValidServiceName("M123_TestService23")); assertTrue(CommonTools.isValidServiceName("M123_TestService23$")); } public void testIsNotValidServiceName() { assertFalse(CommonTools.isValidServiceName("_MyService")); assertFalse(CommonTools.isValidServiceName("My1-23")); assertFalse(CommonTools.isValidServiceName("abacadabra")); assertFalse(CommonTools.isValidServiceName("0My123_Service")); assertFalse(CommonTools.isValidServiceName("_2My123_TestService")); assertFalse(CommonTools.isValidServiceName("*&M123_TestService23")); assertFalse(CommonTools.isValidServiceName("@#M123_TestService23$")); assertFalse(CommonTools.isValidServiceName("M123_TestServ!@ice23$")); } public void testIsValidPackageName() { assertTrue(CommonTools.isValidPackageName("test.org")); assertTrue(CommonTools.isValidPackageName("sdjr23lkj23lk456jl")); assertTrue(CommonTools.isValidPackageName("a0193")); assertTrue(CommonTools.isValidPackageName("i")); assertTrue(CommonTools.isValidPackageName("is")); assertTrue(CommonTools .isValidPackageName("is.a.really.name.just.to.be.sure.is.ok.with.my.parser.i.will.even.put.in.some.stupid.characters.like.a0193.and.sdjr23lkj23lk456jl.test.org")); assertTrue(CommonTools.isValidPackageName("_test.org")); } public void testIsNotValidPackageName() { assertFalse(CommonTools.isValidPackageName("test.1org")); assertFalse(CommonTools.isValidPackageName("sdjr23lkj23%lk456jl")); assertFalse(CommonTools.isValidPackageName("a&0193")); assertFalse(CommonTools.isValidPackageName("1")); assertFalse(CommonTools.isValidPackageName("1.2")); assertFalse(CommonTools.isValidPackageName("1s")); assertFalse(CommonTools.isValidPackageName("import.package")); assertFalse(CommonTools .isValidPackageName("this.is.a.really.long.package.name.just.to.be.sure.this.is.ok.with.my.package.parser.i.will.even.put.in.some.stupid.characters.like.a0193.and.sdjr23lkj23lk456jl.test.#org")); assertFalse(CommonTools.isValidPackageName("_test.Forg")); } protected void tearDown() throws Exception { super.tearDown(); } public static void main(String[] args) { junit.textui.TestRunner.run(IntroduceToolsTestCase.class); } }
package edu.ucdenver.ccp.nlp.wrapper.conceptmapper.stemmer; import org.apache.uima.conceptMapper.support.stemmer.Stemmer; /** * @author Colorado Computational Pharmacology, UC Denver; ccpsupport@ucdenver.edu * */ public class ConceptMapperStemmerFactory { public enum StemmerType { PORTER, BIOLEMMATIZER, NONE } public static Class<? extends Stemmer> getStemmerClass(StemmerType stemmerType) { switch (stemmerType) { case PORTER: return ConceptMapperPorterStemmer.class; case BIOLEMMATIZER: return ConceptMapperBioLemmatizer.class; case NONE: return ConceptMapperNullStemmer.class; default: throw new IllegalArgumentException("Unhandled stemmer type: " + stemmerType.name()); } } }
package org.opendaylight.yangtools.yang.data.codec.xml; import static java.util.Objects.requireNonNull; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.ImmutableClassToInstanceMap; import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.dom.DOMSource; import org.eclipse.jdt.annotation.NonNull; import org.opendaylight.yangtools.rfc7952.data.api.StreamWriterMetadataExtension; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.YangConstants; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedAnydata; import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter; import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriterExtension; import org.opendaylight.yangtools.yang.data.util.NormalizedNodeStreamWriterStack; import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext; import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference; import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Node; /** * A {@link NormalizedNodeStreamWriter} which translates the events into an {@link XMLStreamWriter}, resulting in an * RFC6020 XML encoding. There are 2 versions of this class, one that takes a SchemaContext and encodes values * appropriately according to the YANG schema. The other is schema-less and merely outputs values using toString. The * latter is intended for debugging where doesn't have a SchemaContext available and isn't meant for production use. * * <p> * Due to backwards compatibility reasons this writer recognizes RFC7952 metadata include keys QNames with empty URI * (as exposed via {@link XmlParserStream#LEGACY_ATTRIBUTE_NAMESPACE}) as their QNameModule. These indicate an * unqualified XML attribute and their value can be assumed to be a String. Furthermore, this extends to qualified * attributes, which uses the proper namespace, but will not bind to a proper module revision. This caveat will be * removed in a future version. */ public abstract class XMLStreamNormalizedNodeStreamWriter<T> implements NormalizedNodeStreamWriter, StreamWriterMetadataExtension { private static final Logger LOG = LoggerFactory.getLogger(XMLStreamNormalizedNodeStreamWriter.class); private static final Set<String> BROKEN_ATTRIBUTES = ConcurrentHashMap.newKeySet(); private final @NonNull StreamWriterFacade facade; XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) { facade = new StreamWriterFacade(writer); } /** * Create a new writer with the specified context as its root. * * @param writer Output {@link XMLStreamWriter} * @param context Associated {@link EffectiveModelContext}. * @return A new {@link NormalizedNodeStreamWriter} */ public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final EffectiveModelContext context) { return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, NormalizedNodeStreamWriterStack.of(context)); } /** * Create a new writer with the specified context and rooted at the specified node. * * @param writer Output {@link XMLStreamWriter} * @param inference root node inference * @return A new {@link NormalizedNodeStreamWriter} */ public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final EffectiveStatementInference inference) { return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, inference.getEffectiveModelContext(), NormalizedNodeStreamWriterStack.of(inference)); } /** * Create a new writer with the specified context and rooted in the specified schema path. * * @param writer Output {@link XMLStreamWriter} * @param context Associated {@link EffectiveModelContext}. * @param path path * @return A new {@link NormalizedNodeStreamWriter} */ public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final EffectiveModelContext context, final Absolute path) { return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, NormalizedNodeStreamWriterStack.of(context, path)); } /** * Create a new writer with the specified context and rooted in the specified {@link YangInstanceIdentifier}. * * @param writer Output {@link XMLStreamWriter} * @param context Associated {@link EffectiveModelContext}. * @param path path * @return A new {@link NormalizedNodeStreamWriter} */ public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final EffectiveModelContext context, final YangInstanceIdentifier path) { return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, NormalizedNodeStreamWriterStack.of(context, path)); } /** * Create a new writer with the specified context and rooted in the specified operation's input. * * @param writer Output {@link XMLStreamWriter} * @param context Associated {@link EffectiveModelContext}. * @param operationPath Parent operation (RPC or action) path. * @return A new {@link NormalizedNodeStreamWriter} */ public static @NonNull NormalizedNodeStreamWriter forInputOf(final XMLStreamWriter writer, final EffectiveModelContext context, final Absolute operationPath) { return forOperation(writer, context, operationPath, YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule())); } /** * Create a new writer with the specified context and rooted in the specified operation's output. * * @param writer Output {@link XMLStreamWriter} * @param context Associated {@link EffectiveModelContext}. * @param operationPath Parent operation (RPC or action) path. * @return A new {@link NormalizedNodeStreamWriter} */ public static @NonNull NormalizedNodeStreamWriter forOutputOf(final XMLStreamWriter writer, final EffectiveModelContext context, final Absolute operationPath) { return forOperation(writer, context, operationPath, YangConstants.operationOutputQName(operationPath.lastNodeIdentifier().getModule())); } private static @NonNull NormalizedNodeStreamWriter forOperation(final XMLStreamWriter writer, final EffectiveModelContext context, final Absolute operationPath, final QName qname) { return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, NormalizedNodeStreamWriterStack.ofOperation(context, operationPath, qname)); } /** * Create a new schema-less writer. Note that this version is intended for debugging * where doesn't have a SchemaContext available and isn't meant for production use. * * @param writer Output {@link XMLStreamWriter} * * @return A new {@link NormalizedNodeStreamWriter} */ public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) { return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer); } @Override public final ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() { return ImmutableClassToInstanceMap.of(StreamWriterMetadataExtension.class, this); } abstract void startAnydata(NodeIdentifier name); abstract void startList(NodeIdentifier name); abstract void startListItem(PathArgument name) throws IOException; abstract String encodeAnnotationValue(@NonNull ValueWriter xmlWriter, @NonNull QName qname, @NonNull Object value) throws XMLStreamException; abstract String encodeValue(@NonNull ValueWriter xmlWriter, @NonNull Object value, T context) throws XMLStreamException; final void writeValue(final @NonNull Object value, final T context) throws IOException { try { facade.writeCharacters(encodeValue(facade, value, context)); } catch (XMLStreamException e) { throw new IOException("Failed to write value", e); } } final void startElement(final QName qname) throws IOException { try { facade.writeStartElement(qname); } catch (XMLStreamException e) { throw new IOException("Failed to start element", e); } } final void endElement() throws IOException { try { facade.writeEndElement(); } catch (XMLStreamException e) { throw new IOException("Failed to end element", e); } } final void anydataValue(final Object value) throws IOException { if (value instanceof DOMSourceAnydata) { try { facade.anydataWriteStreamReader(((DOMSourceAnydata) value).toStreamReader()); } catch (XMLStreamException e) { throw new IOException("Unable to transform anydata value: " + value, e); } } else if (value instanceof NormalizedAnydata) { try { facade.emitNormalizedAnydata((NormalizedAnydata) value); } catch (XMLStreamException e) { throw new IOException("Unable to emit anydata value: " + value, e); } } else { throw new IllegalStateException("Unexpected anydata value " + value); } } final void anyxmlValue(final DOMSource domSource) throws IOException { if (domSource != null) { final Node domNode = requireNonNull(domSource.getNode()); try { facade.anyxmlWriteStreamReader(new DOMSourceXMLStreamReader(domSource)); } catch (XMLStreamException e) { throw new IOException("Unable to transform anyXml value: " + domNode, e); } } } @Override public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException { startListItem(name); } @Override public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint) throws IOException { startListItem(identifier); } @Override public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) { startList(name); } @Override public final void startMapNode(final NodeIdentifier name, final int childSizeHint) { startList(name); } @Override public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) { startList(name); } @Override public final void close() throws IOException { try { facade.close(); } catch (XMLStreamException e) { throw new IOException("Failed to close writer", e); } } @Override public final void flush() throws IOException { try { facade.flush(); } catch (XMLStreamException e) { throw new IOException("Failed to flush writer", e); } } @Override public final void metadata(final ImmutableMap<QName, Object> attributes) throws IOException { for (final Entry<QName, Object> entry : attributes.entrySet()) { final QName qname = entry.getKey(); final String namespace = qname.getNamespace().toString(); final String localName = qname.getLocalName(); final Object value = entry.getValue(); // FIXME: remove this handling once we have complete mapping to metadata try { if (namespace.isEmpty()) { // Legacy attribute, which is expected to be a String StreamWriterFacade.warnLegacyAttribute(localName); if (!(value instanceof String)) { if (BROKEN_ATTRIBUTES.add(localName)) { LOG.warn("Unbound annotation {} does not have a String value, ignoring it. Please fix the " + "source of this annotation either by formatting it to a String or removing its " + "use", localName, new Throwable("Call stack")); } LOG.debug("Ignoring annotation {} value {}", localName, value); } else { facade.writeAttribute(localName, (String) value); continue; } } else { final String prefix = facade.getPrefix(qname.getNamespace(), namespace); final String attrValue = encodeAnnotationValue(facade, qname, value); facade.writeAttribute(prefix, namespace, localName, attrValue); } } catch (final XMLStreamException e) { throw new IOException("Unable to emit attribute " + qname, e); } } } @Override public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException { if (DOMSourceAnydata.class.isAssignableFrom(objectModel) || NormalizedAnydata.class.isAssignableFrom(objectModel)) { startAnydata(name); startElement(name.getNodeType()); return true; } return false; } }
package edu.cuny.citytech.foreachlooptolambda.ui.visitors; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.BooleanLiteral; import org.eclipse.jdt.core.dom.BreakStatement; import org.eclipse.jdt.core.dom.ContinueStatement; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.ThrowStatement; public class EnhancedForStatementVisitor extends ASTVisitor { private boolean encounteredBreakStatement; private boolean encounteredContinueStatement; private boolean encounteredInvalidReturnStatement; private boolean encounteredThrownCheckedException; private boolean encounteredNonEffectivelyFinalVars; private int returnCount = 0; @Override public boolean visit(BreakStatement node) { this.encounteredBreakStatement = true; return super.visit(node); } @Override public boolean visit(ContinueStatement node) { this.encounteredContinueStatement = true; return super.visit(node); } @Override public boolean visit(MethodInvocation node) { SimpleName name = node.getName(); IMethodBinding iMethodBinding = (IMethodBinding) name.resolveBinding(); System.out.println("name of method: "+name); System.out.println("This is IMethodinding: "+iMethodBinding); return super.visit(node); } @Override public boolean visit(ThrowStatement node) { this.encounteredThrownCheckedException = true; return super.visit(node); } /** * checking if returnStatement is boolean, not null and has only one return * * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.ReturnStatement) */ @Override public boolean visit(ReturnStatement node) { // one more return statement encountered. returnCount++; // examine what is being returned. ASTNode expression = node.getExpression(); // if there is a return statement, it must return a boolean literal. if (expression == null || !(expression instanceof BooleanLiteral)) { this.encounteredInvalidReturnStatement = true; } return super.visit(node); } public boolean containsBreak() { return this.encounteredBreakStatement; } public boolean containsContinue() { return encounteredContinueStatement; } public boolean containsInvalidReturn() { return encounteredInvalidReturnStatement; } public boolean containsMultipleReturn() { return returnCount > 1; } public boolean containsException() { return encounteredThrownCheckedException; } public boolean containsNEFS() { return encounteredNonEffectivelyFinalVars; } }
package edu.cuny.citytech.foreachlooptolambda.ui.visitors; import java.util.Arrays; import java.util.List; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.BooleanLiteral; import org.eclipse.jdt.core.dom.BreakStatement; import org.eclipse.jdt.core.dom.ContinueStatement; import org.eclipse.jdt.core.dom.EnhancedForStatement; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.ThrowStatement; import org.eclipse.jdt.core.dom.TryStatement; public class EnhancedForStatementVisitor extends ASTVisitor { private boolean encounteredBreakStatement; private boolean encounteredContinueStatement; private boolean encounteredInvalidReturnStatement; private boolean encounteredThrownCheckedException; private boolean encounteredNonEffectivelyFinalVars; private int returnCount = 0; /** * The enhanced for statement that will be visited. */ private EnhancedForStatement enhancedForStatement; /** * Create a new visitor. * * @param enhancedForStatement * The enhanced for statement that will be visited. */ public EnhancedForStatementVisitor(EnhancedForStatement enhancedForStatement) { this.enhancedForStatement = enhancedForStatement; } // finding the TryStatement node public static ASTNode findTryAncestor(ASTNode node) { if (node == null || node instanceof TryStatement) { return node; } return findTryAncestor(node); } @Override public boolean visit(BreakStatement node) { this.encounteredBreakStatement = true; return super.visit(node); } @Override public boolean visit(ContinueStatement node) { this.encounteredContinueStatement = true; return super.visit(node); } private void handleException(ASTNode nodeContaingException) { // gets the top node. If it returns // null, there is no other top. ASTNode parent = (nodeContaingException.getParent()).getParent(); System.out.println(parent); // findTryAncestor(parent); if (parent instanceof TryStatement) { List catchList = Arrays.asList((((TryStatement) parent).catchClauses())); System.out.println(catchList.size()); System.out.println(((TryStatement) parent).getFinally()); System.out.println(((TryStatement) parent).getFinally().getLength()); // if (catchList.size() >= 1 ) { // this.encounteredThrownCheckedException = true; if(((TryStatement) parent).getFinally().getLength() < 1){ } } else { this.encounteredThrownCheckedException = true; } } @Override public boolean visit(MethodInvocation node) { IMethodBinding iMethodBinding = node.resolveMethodBinding(); ITypeBinding[] exceptionTypes = iMethodBinding.getExceptionTypes(); // if there are exceptions if (exceptionTypes.length >= 1) { handleException(node); } return super.visit(node); } @Override public boolean visit(ThrowStatement node) { handleException(node); return super.visit(node); } /** * checking if returnStatement is boolean, not null and has only one return * * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.ReturnStatement) */ @Override public boolean visit(ReturnStatement node) { // one more return statement encountered. returnCount++; // examine what is being returned. ASTNode expression = node.getExpression(); // if there is a return statement, it must return a boolean literal. if (expression == null || !(expression instanceof BooleanLiteral)) { this.encounteredInvalidReturnStatement = true; } return super.visit(node); } public boolean containsBreak() { return this.encounteredBreakStatement; } public boolean containsContinue() { return encounteredContinueStatement; } public boolean containsInvalidReturn() { return encounteredInvalidReturnStatement; } public boolean containsMultipleReturn() { return returnCount > 1; } public boolean containsException() { return encounteredThrownCheckedException; } public boolean containsNEFS() { return encounteredNonEffectivelyFinalVars; } }
package org.elasticsearch.shield.authz.accesscontrol; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.NoMergePolicy; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.LeafCollector; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.Weight; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.Accountable; import org.apache.lucene.util.SparseFixedBitSet; import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.Index; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.analysis.AnalysisService; import org.elasticsearch.index.cache.bitset.BitsetFilterCache; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.internal.ParentFieldMapper; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.similarity.SimilarityService; import org.elasticsearch.indices.IndicesModule; import org.elasticsearch.indices.IndicesWarmer; import org.elasticsearch.search.aggregations.LeafBucketCollector; import org.elasticsearch.shield.authz.InternalAuthorizationService; import org.elasticsearch.shield.license.ShieldLicenseState; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.IndexSettingsModule; import org.elasticsearch.transport.TransportRequest; import org.junit.After; import org.junit.Before; import java.io.IOException; import java.util.Collections; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static java.util.Collections.singletonMap; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.shield.authz.accesscontrol.ShieldIndexSearcherWrapper.intersectScorerAndRoleBits; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ShieldIndexSearcherWrapperUnitTests extends ESTestCase { private TransportRequest request; private MapperService mapperService; private ShieldIndexSearcherWrapper shieldIndexSearcherWrapper; private ElasticsearchDirectoryReader esIn; private ShieldLicenseState licenseState; @Before public void before() throws Exception { Index index = new Index("_index"); IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, Settings.EMPTY); AnalysisService analysisService = new AnalysisService(indexSettings, Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap()); SimilarityService similarityService = new SimilarityService(indexSettings, Collections.emptyMap()); mapperService = new MapperService(indexSettings, analysisService, similarityService, new IndicesModule().getMapperRegistry(), () -> null); ShardId shardId = new ShardId(index, 0); licenseState = mock(ShieldLicenseState.class); when(licenseState.documentAndFieldLevelSecurityEnabled()).thenReturn(true); shieldIndexSearcherWrapper = new ShieldIndexSearcherWrapper(indexSettings, null, mapperService, null, licenseState); IndexShard indexShard = mock(IndexShard.class); when(indexShard.shardId()).thenReturn(shardId); request = new TransportRequest.Empty(); RequestContext.setCurrent(new RequestContext(request)); Directory directory = new RAMDirectory(); IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig()); writer.close(); DirectoryReader in = DirectoryReader.open(directory); // unfortunately DirectoryReader isn't mock friendly esIn = ElasticsearchDirectoryReader.wrap(in, shardId); } @After public void after() throws Exception { esIn.close(); } public void testUnkownOriginOfCurrentCall() { RequestContext.setCurrent(null); try { shieldIndexSearcherWrapper.wrap(esIn); fail("exception expected"); } catch (IllegalStateException e) { assertThat(e.getMessage(), equalTo("can't locate the origin of the current request")); } } public void testDefaultMetaFields() throws Exception { XContentBuilder mappingSource = jsonBuilder().startObject().startObject("type") .startObject("properties") .endObject() .endObject().endObject(); mapperService.merge("type", new CompressedXContent(mappingSource.string()), false, false); IndicesAccessControl.IndexAccessControl indexAccessControl = new IndicesAccessControl.IndexAccessControl(true, emptySet(), null); request.putInContext(InternalAuthorizationService.INDICES_PERMISSIONS_KEY, new IndicesAccessControl(true, singletonMap("_index", indexAccessControl))); FieldSubsetReader.FieldSubsetDirectoryReader result = (FieldSubsetReader.FieldSubsetDirectoryReader) shieldIndexSearcherWrapper.wrap(esIn); assertThat(result.getFieldNames().size(), equalTo(11)); assertThat(result.getFieldNames().contains("_uid"), is(true)); assertThat(result.getFieldNames().contains("_id"), is(true)); assertThat(result.getFieldNames().contains("_version"), is(true)); assertThat(result.getFieldNames().contains("_type"), is(true)); assertThat(result.getFieldNames().contains("_source"), is(true)); assertThat(result.getFieldNames().contains("_routing"), is(true)); assertThat(result.getFieldNames().contains("_parent"), is(true)); assertThat(result.getFieldNames().contains("_timestamp"), is(true)); assertThat(result.getFieldNames().contains("_ttl"), is(true)); assertThat(result.getFieldNames().contains("_size"), is(true)); assertThat(result.getFieldNames().contains("_index"), is(true)); assertThat(result.getFieldNames().contains("_all"), is(false)); // _all contains actual user data and therefor can't be included by default } public void testWrapReaderWhenFeatureDisabled() throws Exception { when(licenseState.documentAndFieldLevelSecurityEnabled()).thenReturn(false); DirectoryReader reader = shieldIndexSearcherWrapper.wrap(esIn); assertThat(reader, sameInstance(esIn)); } public void testWrapSearcherWhenFeatureDisabled() throws Exception { ShardId shardId = new ShardId("_index", 0); IndexSearcher indexSearcher = new IndexSearcher(esIn); IndexSearcher result = shieldIndexSearcherWrapper.wrap(indexSearcher); assertThat(result, sameInstance(indexSearcher)); } public void testWildcards() throws Exception { XContentBuilder mappingSource = jsonBuilder().startObject().startObject("type").startObject("properties") .startObject("field1_a").field("type", "string").endObject() .startObject("field1_b").field("type", "string").endObject() .startObject("field1_c").field("type", "string").endObject() .startObject("field2_a").field("type", "string").endObject() .startObject("field2_b").field("type", "string").endObject() .startObject("field2_c").field("type", "string").endObject() .endObject().endObject().endObject(); mapperService.merge("type", new CompressedXContent(mappingSource.string()), false, false); assertResolvedFields("field1*", "field1_a", "field1_b", "field1_c"); assertResolvedFields("field2*", "field2_a", "field2_b", "field2_c"); } public void testDotNotion() throws Exception { XContentBuilder mappingSource = jsonBuilder().startObject().startObject("type").startObject("properties") .startObject("foo") .field("type", "object") .startObject("properties") .startObject("bar").field("type", "string").endObject() .startObject("baz").field("type", "string").endObject() .endObject() .endObject() .startObject("bar") .field("type", "object") .startObject("properties") .startObject("foo").field("type", "string").endObject() .startObject("baz").field("type", "string").endObject() .endObject() .endObject() .startObject("baz") .field("type", "object") .startObject("properties") .startObject("bar").field("type", "string").endObject() .startObject("foo").field("type", "string").endObject() .endObject() .endObject() .endObject().endObject().endObject(); mapperService.merge("type", new CompressedXContent(mappingSource.string()), false, false); assertResolvedFields("foo.bar", "foo.bar"); assertResolvedFields("bar.baz", "bar.baz"); assertResolvedFields("foo.*", "foo.bar", "foo.baz"); assertResolvedFields("baz.*", "baz.bar", "baz.foo"); } public void testParentChild() throws Exception { XContentBuilder mappingSource = jsonBuilder().startObject().startObject("parent1") .startObject("properties") .startObject("field").field("type", "string").endObject() .endObject() .endObject().endObject(); mapperService.merge("parent1", new CompressedXContent(mappingSource.string()), false, false); mappingSource = jsonBuilder().startObject().startObject("child1") .startObject("properties") .startObject("field").field("type", "string").endObject() .endObject() .startObject("_parent") .field("type", "parent1") .endObject() .endObject().endObject(); mapperService.merge("child1", new CompressedXContent(mappingSource.string()), false, false); mappingSource = jsonBuilder().startObject().startObject("child2") .startObject("properties") .startObject("field").field("type", "string").endObject() .endObject() .startObject("_parent") .field("type", "parent1") .endObject() .endObject().endObject(); mapperService.merge("child2", new CompressedXContent(mappingSource.string()), false, false); mappingSource = jsonBuilder().startObject().startObject("parent2") .startObject("properties") .startObject("field").field("type", "string").endObject() .endObject() .endObject().endObject(); mapperService.merge("parent2", new CompressedXContent(mappingSource.string()), false, false); mappingSource = jsonBuilder().startObject().startObject("child3") .startObject("properties") .startObject("field").field("type", "string").endObject() .endObject() .startObject("_parent") .field("type", "parent2") .endObject() .endObject().endObject(); mapperService.merge("child3", new CompressedXContent(mappingSource.string()), false, false); assertResolvedFields("field1", "field1", ParentFieldMapper.joinField("parent1"), ParentFieldMapper.joinField("parent2")); } public void testDelegateSimilarity() throws Exception { ShardId shardId = new ShardId("_index", 0); IndexSettings settings = IndexSettingsModule.newIndexSettings(new Index("_index"), Settings.EMPTY); BitsetFilterCache bitsetFilterCache = new BitsetFilterCache(settings, new IndicesWarmer(settings.getSettings(), null), new BitsetFilterCache.Listener() { @Override public void onCache(ShardId shardId, Accountable accountable) { } @Override public void onRemoval(ShardId shardId, Accountable accountable) { } }); DirectoryReader directoryReader = DocumentSubsetReader.wrap(esIn, bitsetFilterCache, new MatchAllDocsQuery()); IndexSearcher indexSearcher = new IndexSearcher(directoryReader); IndexSearcher result = shieldIndexSearcherWrapper.wrap(indexSearcher); assertThat(result, not(sameInstance(indexSearcher))); assertThat(result.getSimilarity(true), sameInstance(indexSearcher.getSimilarity(true))); bitsetFilterCache.close(); } public void testIntersectScorerAndRoleBits() throws Exception { final Directory directory = newDirectory(); IndexWriter iw = new IndexWriter( directory, new IndexWriterConfig(new StandardAnalyzer()).setMergePolicy(NoMergePolicy.INSTANCE) ); Document document = new Document(); document.add(new StringField("field1", "value1", Field.Store.NO)); document.add(new StringField("field2", "value1", Field.Store.NO)); iw.addDocument(document); document = new Document(); document.add(new StringField("field1", "value2", Field.Store.NO)); document.add(new StringField("field2", "value1", Field.Store.NO)); iw.addDocument(document); document = new Document(); document.add(new StringField("field1", "value3", Field.Store.NO)); document.add(new StringField("field2", "value1", Field.Store.NO)); iw.addDocument(document); document = new Document(); document.add(new StringField("field1", "value4", Field.Store.NO)); document.add(new StringField("field2", "value1", Field.Store.NO)); iw.addDocument(document); iw.commit(); iw.deleteDocuments(new Term("field1", "value3")); iw.close(); DirectoryReader directoryReader = DirectoryReader.open(directory); IndexSearcher searcher = new IndexSearcher(directoryReader); Weight weight = searcher.createNormalizedWeight(new TermQuery(new Term("field2", "value1")), false); LeafReaderContext leaf = directoryReader.leaves().get(0); Scorer scorer = weight.scorer(leaf); SparseFixedBitSet sparseFixedBitSet = query(leaf, "field1", "value1"); LeafCollector leafCollector = new LeafBucketCollector() { @Override public void collect(int doc, long bucket) throws IOException { assertThat(doc, equalTo(0)); } }; intersectScorerAndRoleBits(scorer, sparseFixedBitSet, leafCollector, leaf.reader().getLiveDocs()); sparseFixedBitSet = query(leaf, "field1", "value2"); leafCollector = new LeafBucketCollector() { @Override public void collect(int doc, long bucket) throws IOException { assertThat(doc, equalTo(1)); } }; intersectScorerAndRoleBits(scorer, sparseFixedBitSet, leafCollector, leaf.reader().getLiveDocs()); sparseFixedBitSet = query(leaf, "field1", "value3"); leafCollector = new LeafBucketCollector() { @Override public void collect(int doc, long bucket) throws IOException { fail("docId [" + doc + "] should have been deleted"); } }; intersectScorerAndRoleBits(scorer, sparseFixedBitSet, leafCollector, leaf.reader().getLiveDocs()); sparseFixedBitSet = query(leaf, "field1", "value4"); leafCollector = new LeafBucketCollector() { @Override public void collect(int doc, long bucket) throws IOException { assertThat(doc, equalTo(3)); } }; intersectScorerAndRoleBits(scorer, sparseFixedBitSet, leafCollector, leaf.reader().getLiveDocs()); directoryReader.close(); directory.close(); } private SparseFixedBitSet query(LeafReaderContext leaf, String field, String value) throws IOException { SparseFixedBitSet sparseFixedBitSet = new SparseFixedBitSet(leaf.reader().maxDoc()); TermsEnum tenum = leaf.reader().terms(field).iterator(); while (tenum.next().utf8ToString().equals(value) == false) {} PostingsEnum penum = tenum.postings(null); sparseFixedBitSet.or(penum); return sparseFixedBitSet; } private void assertResolvedFields(String expression, String... expectedFields) { IndicesAccessControl.IndexAccessControl indexAccessControl = new IndicesAccessControl.IndexAccessControl(true, singleton(expression), null); request.putInContext(InternalAuthorizationService.INDICES_PERMISSIONS_KEY, new IndicesAccessControl(true, singletonMap("_index", indexAccessControl))); FieldSubsetReader.FieldSubsetDirectoryReader result = (FieldSubsetReader.FieldSubsetDirectoryReader) shieldIndexSearcherWrapper.wrap(esIn); assertThat(result.getFieldNames().size() - shieldIndexSearcherWrapper.getAllowedMetaFields().size(), equalTo(expectedFields.length)); for (String expectedField : expectedFields) { assertThat(result.getFieldNames().contains(expectedField), is(true)); } } }
package org.opensim.view.pub; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import java.util.Set; import java.util.Vector; import java.util.prefs.Preferences; import javax.swing.SwingUtilities; import javax.swing.undo.AbstractUndoableEdit; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import org.openide.awt.StatusDisplayer; import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; import org.openide.util.NbBundle; import org.openide.util.lookup.AbstractLookup; import org.openide.util.lookup.InstanceContent; import org.opensim.modeling.*; import org.opensim.view.experimentaldata.ModelForExperimentalData; import org.opensim.modeling.DisplayGeometry.DisplayPreference; import org.opensim.utils.Prefs; import org.opensim.utils.TheApp; import org.opensim.view.*; import org.opensim.view.experimentaldata.ExperimentalDataVisuals; import vtk.AxesActor; import vtk.FrameActor; import vtk.vtkActor; import vtk.vtkActor2D; import vtk.vtkAssembly; import vtk.vtkAssemblyNode; import vtk.vtkAssemblyPath; import vtk.vtkCamera; import vtk.vtkCaptionActor2D; import vtk.vtkFollower; import vtk.vtkMatrix4x4; import vtk.vtkPolyDataMapper; import vtk.vtkProp3D; import vtk.vtkProp3DCollection; import vtk.vtkProperty; import vtk.vtkTextActor; import vtk.vtkTextProperty; import vtk.vtkTransform; import vtk.vtkVectorText; /** * * @author Ayman Habib * * A Database of Displayed models, and displayed windows ModelWindowVTKTopComponents * Also keeps track of currently activated model window ModelWindowVTKTopComponent */ public final class ViewDB extends Observable implements Observer, LookupListener { // List of view windows currently displayed static ArrayList<ModelWindowVTKTopComponent> openWindows = new ArrayList<ModelWindowVTKTopComponent>(4); // List of models currently available in all views private static ArrayList<SingleModelVisuals> modelVisuals = new ArrayList<SingleModelVisuals>(4); private static ArrayList<Boolean> saveStatus = new ArrayList<Boolean>(4); // One single vtAssemby for the whole Scene private static vtkAssembly sceneAssembly; /** * @return the myLookup */ public static Lookup getLookup() { return myLookup; } // Map models to visuals private Hashtable<Model, SingleModelVisuals> mapModelsToVisuals = new Hashtable<Model, SingleModelVisuals>(); private Hashtable<Model, SingleModelGuiElements> mapModelsToGuiElements = new Hashtable<Model, SingleModelGuiElements>(); private Hashtable<Model, ModelSettingsSerializer> mapModelsToSettings = new Hashtable<Model, ModelSettingsSerializer>(); private Hashtable<Model, Double> modelOpacities = new Hashtable<Model, Double>(); static ViewDB instance=null; private static boolean graphicsAvailable = true; // Window currently designated as current. private static ModelWindowVTKTopComponent currentModelWindow=null; // Flag indicating whether new models are open in a new window or in the same window static boolean openModelInNewWindow=true; static boolean useImmediateModeRendering = false; // Use Render instead of paint private ArrayList<Selectable> selectedObjects = new ArrayList<Selectable>(0); private Hashtable<Selectable, vtkCaptionActor2D> selectedObjectsAnnotations = new Hashtable<Selectable, vtkCaptionActor2D>(0); private ArrayList<SelectionListener> selectionListeners = new ArrayList<SelectionListener>(0); private AxesActor axesAssembly=null; private boolean axesDisplayed=false; private vtkTextActor textActor=null; private boolean picking = false; private boolean query = false; private boolean dragging = false; private double draggingZ = 0.0; private double nonCurrentModelOpacity = 0.4; private double muscleDisplayRadius = 0.005; private double markerDisplayRadius = .01; private int debugLevel=1; private NumberFormat numFormat = NumberFormat.getInstance(); private final static InstanceContent lookupContents = new InstanceContent(); private final static Lookup myLookup = new AbstractLookup (lookupContents); Lookup.Result<OpenSimObject> r; /** Creates a new instance of ViewDB */ private ViewDB() { applyPreferences(); r = myLookup.lookupResult(OpenSimObject.class); } public void applyPreferences() { String debugLevelString="0"; String saved = Preferences.userNodeForPackage(TheApp.class).get("Debug", debugLevelString); // Parse saved to an int, use 0 (no debug) on failure if (saved.equalsIgnoreCase("Off")) saved="0"; debugLevel = Integer.parseInt(saved); } /** * Enforce a singleton pattern */ public static ViewDB getInstance() { if( instance==null ) instance = new ViewDB(); return instance; } public static void ViewDBGetInstanceRepaintAll( ) { ViewDB viewDBInstance = ViewDB.getInstance(); if( viewDBInstance != null ) viewDBInstance.repaintAll(); } public static void ViewDBGetInstanceRenderAll( ) { ViewDB viewDBInstance = ViewDB.getInstance(); if( viewDBInstance != null ) viewDBInstance.renderAll(); } // The setChanged() protected method must overridden to make it public public synchronized void setChanged() { super.setChanged(); } public static ModelWindowVTKTopComponent getCurrentModelWindow() { return currentModelWindow; } /** * Keep track of current view window so that dialogs are cenetred on top of it if necessary. * Just a handy window to use. */ public static void setCurrentModelWindow(ModelWindowVTKTopComponent aCurrentModelWindow) { currentModelWindow = aCurrentModelWindow; } /** * update Method is called whenever a model is added, removed and/or moved in the GUI * Observable should be of type OpenSimDB. */ public void update(Observable o, Object arg) { if (!isGraphicsAvailable()) return; if (o instanceof OpenSimDB){ if (arg instanceof ObjectsAddedEvent) { ObjectsAddedEvent ev = (ObjectsAddedEvent)arg; Vector<OpenSimObject> objs = ev.getObjects(); for (int i=0; i<objs.size(); i++) { if (objs.get(i) instanceof Model) { assert(false); } if (objs.get(i) instanceof Marker) { SingleModelVisuals vis = mapModelsToVisuals.get(ev.getModel()); vis.addMarkerGeometry((Marker)objs.get(i)); repaintAll(); } } } else if (arg instanceof ObjectSetCurrentEvent) { // Current model has changed. For view purposes this affects available commands // Changes in the Tree view are handled by the Explorer View. Because only // objects in the current model can be selected and manipulated, clear all // currently selected objects. clearSelectedObjects(); ObjectSetCurrentEvent ev = (ObjectSetCurrentEvent)arg; Vector<OpenSimObject> objs = ev.getObjects(); for (int i=0; i<objs.size(); i++) { if (objs.get(i) instanceof Model) { Model currentModel = (Model)objs.get(i); // Apply opacity to other models Enumeration<Model> models=mapModelsToVisuals.keys(); while(models.hasMoreElements()){ Model next = models.nextElement(); double nominalOpacity=modelOpacities.get(next); SingleModelVisuals vis = mapModelsToVisuals.get(next); if (next == currentModel){ setObjectOpacity(next, nominalOpacity); vis.setPickable(true); //displayText("Model Name:"+next.getName(),16); } else { setObjectOpacity(next, getNonCurrentModelOpacity()*nominalOpacity); vis.setPickable(false); } } break; } } } else if (arg instanceof ObjectsDeletedEvent) { handleObjectsDeletedEvent(arg); } else if (arg instanceof ObjectEnabledStateChangeEvent) { handleObjectsEnabledStateChangeEvent(arg); }else if (arg instanceof ObjectsRenamedEvent){ ObjectsRenamedEvent ev = (ObjectsRenamedEvent)arg; // The name change might be for one or more of the selected objects statusDisplaySelectedObjects(); repaintAll(); Vector<OpenSimObject> objs = ev.getObjects(); for (int i=0; i<objs.size(); i++) { // if an actuator changed names, update the list of names in the model gui elements if (objs.get(i) instanceof Actuator) { //Actuator act = (Actuator)ev.getObject(); //getModelGuiElements(act.getModel()).updateActuatorNames(); } else if (objs.get(i) instanceof Marker) { //Marker marker = (Marker)ev.getObject(); //getModelGuiElements(marker.getBody().get_model()).updateMarkerNames(); } } } else if (arg instanceof ModelEvent ) { ModelEvent ev = (ModelEvent)arg; // We need to detect if this the first time anything is loaded into the app // (or new project) if so we'll open a window, otherwise we will // display the new Model in existing views if (ev.getOperation()==ModelEvent.Operation.Open){ Model model = ev.getModel(); SingleModelGuiElements newModelGuiElements = new SingleModelGuiElements(model); processSavedSettings(model); mapModelsToGuiElements.put(model, newModelGuiElements); try { createNewViewWindowIfNeeded(); } catch(UnsatisfiedLinkError e){ setGraphicsAvailable(false); return; } // Create visuals for the model SingleModelVisuals newModelVisual = (model instanceof ModelForExperimentalData)? new ExperimentalDataVisuals(model): new SingleModelVisuals(model); // add to map from models to modelVisuals so that it's accesisble // thru tree picks mapModelsToVisuals.put(model, newModelVisual); modelOpacities.put(model, 1.0); addVisObjectToAllViews(); // Compute placement so that model does not intersect others vtkMatrix4x4 m= (model instanceof ModelForExperimentalData)? new vtkMatrix4x4(): getInitialTransform(newModelVisual); newModelVisual.getModelDisplayAssembly().SetUserMatrix(m); sceneAssembly.AddPart(newModelVisual.getModelDisplayAssembly()); // add to list of models getModelVisuals().add(newModelVisual); //Too late?? // Check if this refits scene into window // int rc = newModelVisual.getModelDisplayAssembly().GetReferenceCount(); if(OpenSimDB.getInstance().getNumModels()==1) { Iterator<ModelWindowVTKTopComponent> windowIter = openWindows.iterator(); double[] bnds = new double[6]; while(windowIter.hasNext()){ bnds = computeSceneBounds(); //createBBox(); ModelWindowVTKTopComponent nextWindow = windowIter.next(); // This line may need to be enclosed in a Lock /UnLock pair per vtkPanel lockDrawingSurfaces(true); nextWindow.getCanvas().GetRenderer().ResetCamera(bnds); lockDrawingSurfaces(false); } } //rc = newModelVisual.getModelDisplayAssembly().GetReferenceCount(); repaintAll(); //rc = newModelVisual.getModelDisplayAssembly().GetReferenceCount(); } else if (ev.getOperation()==ModelEvent.Operation.Close){ Model dModel = ev.getModel(); mapModelsToGuiElements.remove(dModel); mapModelsToSettings.remove(dModel); // Remove model-associated objects from selection list! removeObjectsBelongingToModelFromSelection(dModel); SingleModelVisuals visModel = mapModelsToVisuals.get(dModel); // Remove from display //int rc = visModel.getModelDisplayAssembly().GetReferenceCount(); if (visModel != null){ removeObjectFromScene(visModel.getModelDisplayAssembly()); //rc = visModel.getModelDisplayAssembly().GetReferenceCount(); // Remove from lists modelVisuals.remove(visModel); } removeAnnotationObjects(dModel); mapModelsToVisuals.remove(dModel); modelOpacities.remove(dModel); //rc = visModel.getModelDisplayAssembly().GetReferenceCount(); if (visModel != null) visModel.cleanup(); } else if (ev.getOperation()==ModelEvent.Operation.SetCurrent) { // Current model has changed. For view purposes this affects available commands // Changes in the Tree view are handled by the Explorer View // Apply opacity to other models Enumeration<Model> models=mapModelsToVisuals.keys(); while(models.hasMoreElements()){ Model next = models.nextElement(); double nominalOpacity=modelOpacities.get(next); SingleModelVisuals vis = mapModelsToVisuals.get(next); if (next==ev.getModel()){ setObjectOpacity(next, nominalOpacity); } else{ setObjectOpacity(next, getNonCurrentModelOpacity()*nominalOpacity); } } } else if (ev.getOperation()==ModelEvent.Operation.Save) { // If a model is saved then its document filename has changed and we should update the settings file accordingly updateSettingsSerializer(ev.getModel()); } } } } private void handleObjectsDeletedEvent(final Object arg) { ObjectsDeletedEvent ev = (ObjectsDeletedEvent)arg; Vector<OpenSimObject> objs = ev.getObjects(); boolean repaint = false; boolean selectedDeleted = false; for (int i=0; i<objs.size(); i++) { OpenSimObject obj = objs.get(i); int j = findObjectInSelectedList(obj); if (j >= 0) { selectedObjects.remove(j); selectedDeleted = true; } if (obj instanceof Model) { // TODO: do same stuff as ModelEvent.Operation.Close event } else if (obj instanceof PathActuator) { removeObjectsBelongingToMuscleFromSelection(obj); getModelVisuals(ev.getModel()).removeActuatorGeometry((Actuator)obj); repaint = true; } else if (obj instanceof Marker) { SingleModelVisuals vis = mapModelsToVisuals.get(ev.getModel()); vis.removeMarkerGeometry((Marker)obj); repaint = true; } } if (selectedDeleted) statusDisplaySelectedObjects(); if (repaint) repaintAll(); } private void addVisObjectToAllViews() { //From here on we're adding things to display so we better lock if (sceneAssembly==null){ createScene(); // Add assembly to all views Iterator<ModelWindowVTKTopComponent> windowIter = openWindows.iterator(); while(windowIter.hasNext()){ ModelWindowVTKTopComponent nextWindow = windowIter.next(); nextWindow.getCanvas().GetRenderer().AddViewProp(sceneAssembly); } //createXLabel(); } } public static ArrayList<SingleModelVisuals> getModelVisuals() { return modelVisuals; } public OpenSimObject pickObject(vtkAssemblyPath asmPath) { Iterator<SingleModelVisuals> iter = modelVisuals.iterator(); while(iter.hasNext()){ SingleModelVisuals nextModel = iter.next(); OpenSimObject obj = nextModel.pickObject(asmPath); if (obj != null){ // Find corresponding tree node return obj; } } return null; } /** * Get the object corresponding to selected vtkAssemblyPath **/ OpenSimObject getObjectForVtkRep(vtkAssembly prop) { Iterator<SingleModelVisuals> iter = modelVisuals.iterator(); while(iter.hasNext()){ SingleModelVisuals nextModel = iter.next(); OpenSimObject obj = nextModel.getObjectForVtkRep(prop); if (obj != null) return obj; } return null; } /** * Get the vtk object corresponding to passed in opensim object **/ public vtkProp3D getVtkRepForObject(OpenSimObject obj) { if (!isGraphicsAvailable()) return null; Iterator<SingleModelVisuals> iter = modelVisuals.iterator(); while(iter.hasNext()){ SingleModelVisuals nextModel = iter.next(); vtkProp3D objAssembly = nextModel.getVtkRepForObject(obj); if (objAssembly != null) return objAssembly; } return null; } /** * removeWindow removes the passed in window form the list of windows maintaiined * by ViewDB **/ public void removeWindow(ModelWindowVTKTopComponent modelWindowVTKTopComponent) { openWindows.remove(modelWindowVTKTopComponent); } /** * Add a new Viewing. window * This executes in the Swing thread. */ public void addViewWindow() { try { addViewWindow(null); } catch(UnsatisfiedLinkError e){ setGraphicsAvailable(false); } } public ModelWindowVTKTopComponent addViewWindow(String desiredName) { // Create the window final ModelWindowVTKTopComponent win = new ModelWindowVTKTopComponent(); // Fix name if (desiredName==null){ int ct=0; while(!ViewDB.getInstance().checkValidViewName(win.getDisplayName(), win)){ win.setTabDisplayName(NbBundle.getMessage( ModelWindowVTKTopComponent.class, "UnsavedModelNameFormat", new Object[] { new Integer(ct++) } )); }; } else win.setTabDisplayName(desiredName); if (getCurrentModelWindow()!=null){ // Copy camera from vtkCamera lastCamera=getCurrentModelWindow().getCanvas().GetRenderer().GetActiveCamera(); win.getCanvas().applyOrientation(lastCamera); getCurrentModelWindow().getCanvas().GetRenderer().AddActor2D(textActor); } if (SwingUtilities.isEventDispatchThread()){ win.open(); win.requestActive(); setCurrentModelWindow(win); // Open it and make it active openWindows.add(win); win.getCanvas().GetRenderer().AddViewProp(sceneAssembly); repaintAll(); } else { SwingUtilities.invokeLater(new Runnable(){ public void run() { win.open(); win.requestActive(); setCurrentModelWindow(win); // Open it and make it active openWindows.add(win); win.getCanvas().GetRenderer().AddViewProp(sceneAssembly); repaintAll(); }}); } // If the user manually added a new view, we won't need to automatically create a new one when model is loaded. openModelInNewWindow=false; return win; } /** * Helper function to implement model hide/show. * */ public void toggleModelDisplay(Model model, boolean onOff) { SingleModelVisuals modelVis = mapModelsToVisuals.get(model); if (!modelVis.isVisible() && onOff){ sceneAssembly.AddPart(modelVis.getModelDisplayAssembly()); modelVis.setVisible(true); } else if (modelVis.isVisible() && !onOff) { sceneAssembly.RemovePart(modelVis.getModelDisplayAssembly()); modelVis.setVisible(false); } repaintAll(); } /** * Decide if a new window is needed to be created. Right now this's done only first time the application * is started. This may need to be change when a new project is opened */ private void createNewViewWindowIfNeeded() { if (openModelInNewWindow){ boolean evt = SwingUtilities.isEventDispatchThread(); // The following line has the side effect of loading VTK libraries, can't move it to another thread' final ModelWindowVTKTopComponent win = new ModelWindowVTKTopComponent(); openWindows.add(win); openModelInNewWindow=false; setCurrentModelWindow(win); // open window later rather than now to avoid having a rectangular blank patch appearing over the GUI while // the model is loading and the scene is set up if (SwingUtilities.isEventDispatchThread()){ win.requestActive(); win.open(); } else { SwingUtilities.invokeLater(new Runnable(){ // Should change to WindowManager.getDefault().invokeWhenUIReady if/when we upgrade NB public void run(){ win.open(); win.requestActive(); }}); } } } /** * Add an arbirary Object to the scene (all views) */ public void addObjectToScene(vtkProp3D aProp) { sceneAssembly.AddPart(aProp); repaintAll(); } /** * Remove an arbirary Object from the scene (all views) */ public void removeObjectFromScene(vtkProp3D aProp) { sceneAssembly.RemovePart(aProp); repaintAll(); } /** * Return a flag indicating whether the model is currently shown or hidden */ public boolean getDisplayStatus(Model m) { return mapModelsToVisuals.get(m).isVisible(); } public static Model getCurrentModel() { return OpenSimDB.getInstance().getCurrentModel(); } /** * Cycle through displayed windows and repaint them */ public static void repaintAll() { Iterator<ModelWindowVTKTopComponent> windowIter = openWindows.iterator(); while( windowIter.hasNext() ){ if( useImmediateModeRendering ) windowIter.next().getCanvas().Render(); else windowIter.next().getCanvas().repaint(); } } public static void renderAll() { Iterator<ModelWindowVTKTopComponent> windowIter = openWindows.iterator(); while(windowIter.hasNext()){ windowIter.next().getCanvas().Render(); } } /** * Set the color of the passed in object. */ public void setObjectColor(OpenSimObject object, double[] colorComponents) { if(PathPoint.safeDownCast(object)!=null) { } else{ // should check for body here vtkProp3D asm = ViewDB.getInstance().getVtkRepForObject(object); /** make sure the object is not selected, if so change only in database */ if (ViewDB.getInstance().findObjectInSelectedList(object)!=-1){ //OpenSim211 if (object.getDisplayer()!=null) // object.getDisplayer().setColor(colorComponents); } else if(asm!=null) { applyColor(colorComponents, asm, true); if (object instanceof Body){ ((BodyDisplayer)asm).setColor(colorComponents); } else if (object instanceof DisplayGeometry) ((DisplayGeometry)object).setColor(colorComponents); } } renderAll(); } public static double[] getObjectRGBColorIn3DoublesWithRangeFrom0To1( OpenSimObject object ) { if( PathPoint.safeDownCast(object) != null ) return null; vtkProp3D asm = ViewDB.getInstance().getVtkRepForObject( object ); if( asm == null ) return null; if( object instanceof Body ) return ((BodyDisplayer)asm).GetColorOrReturnNull(); else if( object instanceof DisplayGeometry ) { double[] colorToReturn = {-1, -1, -1}; ((DisplayGeometry)object).getColor( colorToReturn ); return colorToReturn; } return null; } public static double[] getObjectRGBColorIn3DoublesWithRangeFrom0To1Deprecated( OpenSimObject object ) { double objectColor[] = { 1.0, 1.0, 1.0 }; if( object == null ) return objectColor; vtkProperty propertyToFillInformation = new vtkProperty(); ViewDB.getObjectProperties( object, propertyToFillInformation ); return propertyToFillInformation.GetColor(); // This seems to always return 1,1,1. // Currently this just returns White. May be due to VTK being bunches of pieces - and no real color available. } public void applyColor(final double[] colorComponents, final vtkProp3D asm, boolean allowUndo) { AbstractUndoableEdit auEdit = new AbstractUndoableEdit(){ public boolean canUndo() { return true; } public boolean canRedo() { return true; } public void undo() throws CannotUndoException { super.undo(); final double[] white=new double[]{1., 1., 1.}; applyColor(white, asm, false); } public void redo() throws CannotRedoException { super.redo(); applyColor(colorComponents, asm, true); } @Override public String getRedoPresentationName() { return "Redo Color change"; } @Override public String getUndoPresentationName() { return "Undo Color change"; } }; if (allowUndo) ExplorerTopComponent.addUndoableEdit(auEdit); ApplyFunctionToActors(asm, new ActorFunctionApplier() { public void apply(vtkActor actor) { if (!(actor instanceof FrameActor)){ actor.GetProperty().SetColor(colorComponents); actor.Modified(); } }}); renderAll(); } public void setNominalModelOpacity(OpenSimObject object, double newOpacity) { if (object instanceof Model){ modelOpacities.put((Model)object, newOpacity); double vtkOpacity= newOpacity; if (object.equals(getCurrentModel())){ } else { vtkOpacity *= getNonCurrentModelOpacity(); } setObjectOpacity(object, vtkOpacity); } } public double getNominalModelOpacity(Model modelObject) { return modelOpacities.get(modelObject); } /** * Set the Opacity of the passed in object to newOpacity */ public static void setObjectOpacity( OpenSimObject object, double newOpacity ) { vtkProp3D asm = ViewDB.getInstance().getVtkRepForObject(object); ViewDB.applyOpacity( newOpacity, asm ); if( asm instanceof BodyDisplayer ) ((BodyDisplayer) asm).setOpacity(newOpacity); else if (object instanceof DisplayGeometry) ((DisplayGeometry)object).setOpacity(newOpacity); } private static void applyOpacity( final double newOpacity, final vtkProp3D asm ) { ViewDB.ApplyFunctionToActors( asm, new ActorFunctionApplier() { public void apply(vtkActor actor) { actor.GetProperty().SetOpacity(newOpacity); }}); ViewDB.repaintAll(); } /** * Retrieve the display properties for the passed in object. */ public static void getObjectProperties(OpenSimObject object, final vtkProperty saveProperty) { vtkProp3D asm = ViewDB.getInstance().getVtkRepForObject(object); ApplyFunctionToActors(asm, new ActorFunctionApplier() { public void apply(vtkActor actor) { saveProperty.SetColor(actor.GetProperty().GetColor()); saveProperty.SetOpacity(actor.GetProperty().GetOpacity()); }}); } public static double getObjectOpacityInRangeFrom0To1( OpenSimObject object ) { if( object == null ) return 1; vtkProperty propertyToFillInformation = new vtkProperty(); ViewDB.getObjectProperties( object, propertyToFillInformation ); return propertyToFillInformation.GetOpacity(); } public void setObjectProperties(OpenSimObject object, vtkProperty saveProperty) { setObjectColor(object, saveProperty.GetColor()); setObjectOpacity(object, saveProperty.GetOpacity()); repaintAll(); } /** * Selection related functions */ /** * Remove items from selection list which belong to the given model */ private void removeObjectsBelongingToModelFromSelection(Model model) { boolean modified = false; for(int i=selectedObjects.size()-1; i>=0; i Model ownerModel = selectedObjects.get(i).getOwnerModel(); if(Model.getCPtr(model) == Model.getCPtr(ownerModel)) { markSelected(selectedObjects.get(i), false, false, false); selectedObjects.remove(i); modified = true; } } if(modified) { statusDisplaySelectedObjects(); repaintAll(); } } /** * Remove items from selection list which belong to the given model */ public void removeObjectsBelongingToMuscleFromSelection(OpenSimObject objectWithPath) { boolean modified = false; OpenSimObject pathObject = objectWithPath.getPropertyByName("GeometryPath").getValueAsObject(); GeometryPath gp = GeometryPath.safeDownCast(pathObject); for (int i=selectedObjects.size()-1; i>=0; i // First see if the selected object is a objectWithPath. // markSelected(selectedObjects.get(i), false, false, false); // selectedObjects.remove(i); // modified = true; // Now see if the selected object is a objectWithPath point. PathPoint mp = PathPoint.safeDownCast(selectedObjects.get(i).getOpenSimObject()); if (mp != null) { for (int j=0; j < gp.getPathPointSet().getSize(); j++) { if (PathPoint.getCPtr(mp) == PathPoint.getCPtr(gp.getPathPointSet().get(j))) { markSelected(selectedObjects.get(i), false, false, false); //System.out.println("removing " + mp.getName()); selectedObjects.remove(i); modified = true; break; } } } } if(modified) { statusDisplaySelectedObjects(); repaintAll(); } } /** * Mark an object as selected (on/off). * */ public void markSelected(Selectable selectedObject, boolean highlight, boolean sendEvent, boolean updateStatusDisplayAndRepaint) { selectedObject.markSelected(highlight); if (highlight) lookupContents.add(selectedObject.getOpenSimObject()); else lookupContents.remove(selectedObject.getOpenSimObject()); if (ViewDB.getInstance().isQuery()){ if (highlight){ // Add caption vtkCaptionActor2D theCaption = new vtkCaptionActor2D(); double[] bounds=selectedObject.getBounds(); theCaption.SetAttachmentPoint(new double[]{ (bounds[0]+bounds[1])/2.0, (bounds[2]+bounds[3])/2.0, (bounds[4]+bounds[5])/2.0, }); theCaption.GetTextActor().ScaledTextOn(); theCaption.SetHeight(.02); theCaption.BorderOff(); if (selectedObject.getOpenSimObject()!=null){ theCaption.SetCaption(selectedObject.getOpenSimObject().getName()); addAnnotationToViews(theCaption); selectedObjectsAnnotations.put(selectedObject,theCaption); } } else { // if annotationis on remove vtkCaptionActor2D annotation = getAnnotation(selectedObject); if (annotation!=null){ removeAnnotationFromViews(annotation); } } } if(updateStatusDisplayAndRepaint) { statusDisplaySelectedObjects(); repaintAll(); } if(sendEvent) { ObjectSelectedEvent evnt = new ObjectSelectedEvent(this, selectedObject, highlight); setChanged(); notifyObservers(evnt); } } public void addObjectAnnotationToViews(final vtkCaptionActor2D theCaption, OpenSimObject dObject) { addAnnotationToViews(theCaption); vtkProp3D prop=ViewDB.getInstance().getVtkRepForObject(dObject); theCaption.SetAttachmentPoint(prop.GetCenter()); selectedObjectsAnnotations.put(new SelectedObject(dObject),theCaption); } public void addAnnotationToViews(final vtkActor2D theCaption) { // Add caption to all windows Iterator<ModelWindowVTKTopComponent> windowIter = openWindows.iterator(); while(windowIter.hasNext()){ ModelWindowVTKTopComponent nextWindow = windowIter.next(); nextWindow.getCanvas().GetRenderer().AddActor2D(theCaption); } } public ArrayList<Selectable> getSelectedObjects() { return selectedObjects; } public void statusDisplaySelectedObjects() { String status=""; for(int i=0; i<selectedObjects.size(); i++) { if(i>0) status += ", "; status += selectedObjects.get(i).getStatusText(); } StatusDisplayer.getDefault().setStatusText(status); } public void setSelectedObject(OpenSimObject obj) { clearSelectedObjects(); if (obj != null) { SelectedObject selectedObject = new SelectedObject(obj); selectedObjects.add(selectedObject); markSelected(selectedObject, true, true, true); ExplorerTopComponent.getDefault().selectNodeForSelectedObject(selectedObject); } else { // this function should never be called with obj = null ClearSelectedObjectsEvent evnt = new ClearSelectedObjectsEvent(this); setChanged(); notifyObservers(evnt); } } private int findObjectInSelectedList(OpenSimObject obj) { for (int i = 0; i < selectedObjects.size(); i++) if (OpenSimObject.getCPtr(obj) == OpenSimObject.getCPtr(selectedObjects.get(i).getOpenSimObject())) return i; return -1; } public boolean removeObjectFromSelectedList(OpenSimObject obj) { int i = findObjectInSelectedList(obj); if(i >= 0) { // mark it as unselected markSelected(selectedObjects.get(i), false, true, false); // remove the object from the list of selected ones selectedObjects.remove(i); // markSelected can't properly update the statusDisplay because // the object is not removed from selectedObjects until after // markSelected is called. statusDisplaySelectedObjects(); repaintAll(); return true; } return false; } public void toggleAddSelectedObject(OpenSimObject obj) { // If the object is already in the list, remove it if (removeObjectFromSelectedList(obj) == false) { // If the object is not already in the list, add it SelectedObject selectedObject = new SelectedObject(obj); selectedObjects.add(selectedObject); // mark it as selected markSelected(selectedObject, true, true, true); } } public void replaceSelectedObject(OpenSimObject obj) { // If the object is already in the list of selected ones, do nothing (a la Illustrator) // If the object is not already in the list, make this object the only selected one if(!isSelected(obj)) setSelectedObject(obj); } public void clearSelectedObjects() { for (int i = 0; i < selectedObjects.size(); i++) { // mark it as unselected markSelected(selectedObjects.get(i), false, true, false); } selectedObjects.clear(); statusDisplaySelectedObjects(); repaintAll(); } public boolean isSelected(OpenSimObject obj) { return (findObjectInSelectedList(obj) >= 0); } /** * Check if the name passed in is a valid name for a display window (no duplicates * for now, until a more restricted naming is needed * * returns true if newName is a valid name for the passed in view, false otherwise */ public boolean checkValidViewName(String newName, ModelWindowVTKTopComponent view) { boolean valid = true; Iterator<ModelWindowVTKTopComponent> windowIter = openWindows.iterator(); while(windowIter.hasNext() && valid){ ModelWindowVTKTopComponent nextWindow = windowIter.next(); String nextWindowName = nextWindow.getDisplayName(); if(nextWindowName.equalsIgnoreCase(newName)){ valid = (view.equals(nextWindow)); } } return valid; } /** * Compute initial offset for a model when displayed. * To account for user prefs a property is made * just put the model somewhere so that it does not intersect other models. * * newModelVisual has not been added to the list yet. * * @todo should we allow for rotations as well? * */ private vtkMatrix4x4 getInitialTransform(SingleModelVisuals newModelVisual) { vtkMatrix4x4 m = new vtkMatrix4x4(); Iterator<SingleModelVisuals> iter = modelVisuals.iterator(); // modelBounds are -1 to 1 and updated only after drawing double modelBounds[] = newModelVisual.getBounds(); // If at least one model exists compute bounding box for the scene // and place the new model outside the box along z-axis. // This could be made into an option where models are placed along X, Y or Z // Also possible to define a default offset in any direction and reuse it. if (iter.hasNext()){ double bounds[]= computeSceneBounds(); String defaultOffsetDirection = NbBundle.getMessage(ViewDB.class,"CTL_DisplayOffsetDir"); defaultOffsetDirection=Preferences.userNodeForPackage(TheApp.class).get("DisplayOffsetDir", defaultOffsetDirection); if (defaultOffsetDirection == null) defaultOffsetDirection="Z"; if (defaultOffsetDirection.equalsIgnoreCase("X")) m.SetElement(0, 3, bounds[1]-modelBounds[0]); else if (defaultOffsetDirection.equalsIgnoreCase("Y")) m.SetElement(1, 3, bounds[3]-modelBounds[2]); else m.SetElement(2, 3, bounds[5]-modelBounds[4]); } return m; } /** * get method for the visualization transform (to place a model in a scene). */ public vtkMatrix4x4 getModelVisualsTransform(SingleModelVisuals aModelVisual) { return aModelVisual.getModelDisplayAssembly().GetUserMatrix(); } /** * set method for the visualization transform (to place a model in a scene). */ public void setModelVisualsTransform(SingleModelVisuals aModelVisual, vtkMatrix4x4 newTransform) { aModelVisual.getModelDisplayAssembly().SetUserMatrix(newTransform); updateAnnotationAnchors(); } /** * Get a box around the whole scene. Used to fill an intial guess of the bounds for the model display */ public double[] getSceneBounds() { double[] sceneBounds = new double[6]; sceneAssembly.GetBounds(sceneBounds); return sceneBounds; } public static double[] boundsUnion(double[] bounds1, double[] bounds2) { if(bounds1==null) return bounds2; else if(bounds2==null) return bounds1; else { double[] bounds = new double[6]; bounds[0]=(bounds1[0]<bounds2[0])?bounds1[0]:bounds2[0]; bounds[1]=(bounds1[1]>bounds2[1])?bounds1[1]:bounds2[1]; bounds[2]=(bounds1[2]<bounds2[2])?bounds1[2]:bounds2[2]; bounds[3]=(bounds1[3]>bounds2[3])?bounds1[3]:bounds2[3]; bounds[4]=(bounds1[4]<bounds2[4])?bounds1[4]:bounds2[4]; bounds[5]=(bounds1[5]>bounds2[5])?bounds1[5]:bounds2[5]; return bounds; } } public double[] getSelectedObjectBounds() { double[] bounds = null; for(int i=0; i<selectedObjects.size(); i++) bounds = boundsUnion(bounds, selectedObjects.get(i).getBounds()); return bounds; } // Don't include glyphs since they often also have glyphs at the origin which screws up the bounding box // Also don't include axes public double[] getSceneBoundsBodiesOnly() { double[] bounds = null; Iterator<SingleModelVisuals> iter = modelVisuals.iterator(); while(iter.hasNext()) bounds = boundsUnion(bounds, iter.next().getBoundsBodiesOnly()); return bounds; } /** * createScene is invoked once to create the assembly representing the scene * that models attach to. If all windows are closed then this function will not be called again. */ private void createScene() { sceneAssembly = new vtkAssembly(); axesAssembly = new AxesActor(); textActor= new vtkTextActor(); } public void showAxes(boolean trueFalse) { if (trueFalse) addObjectToScene(axesAssembly); else removeObjectFromScene(axesAssembly); setAxesDisplayed(trueFalse); } public void setTextCamera(vtkCamera camera) { if (isAxesDisplayed()){ axesAssembly.setCamera(camera); } } public boolean isAxesDisplayed() { return axesDisplayed; } public void setAxesDisplayed(boolean axesDisplayed) { this.axesDisplayed = axesDisplayed; } /** * Search the list of displayed models for the passed in model and if found return * its visuals, otherwise return null */ public SingleModelVisuals getModelVisuals(Model aModel) { return mapModelsToVisuals.get(aModel); } /** * Get gui elements for passed in model */ public SingleModelGuiElements getModelGuiElements(Model aModel) { return mapModelsToGuiElements.get(aModel); } public void applyTimeToViews(double time) { Iterator<ModelWindowVTKTopComponent> windowIter = openWindows.iterator(); while(windowIter.hasNext()){ ModelWindowVTKTopComponent nextWindow = windowIter.next(); nextWindow.getCanvas().applyTime(time); } } /** * This function is called from a timer thread that runs parallel to the simulation thread * Obviously should run as fast as possible. * We could get visModel from animationCallback using getModelVisuals(animationCallback.getModel()) * but that's another map search. */ public void updateModelDisplay(Model aModel) { updateModelDisplay(aModel, null); } /** * Update display of passed in model, optionally recreating display geometry and applying preferences * @param aModel * @param checkRecreateGeometry : whether to try to sync up geometry with OpenSim objects underneath * This excludes transforms since these are obtained from the system on the fly. */ public void updateModelDisplay(Model aModel, OpenSimObject specificObject) { if (!isGraphicsAvailable()) return; lockDrawingSurfaces(true); if (specificObject!=null) mapModelsToVisuals.get(aModel).updateObjectDisplay(specificObject); mapModelsToVisuals.get(aModel).updateModelDisplay(aModel); lockDrawingSurfaces(false); repaintAll(); } public void updateModelDisplayNoRepaint(Model aModel) { if (!isGraphicsAvailable()) return; lockDrawingSurfaces(true); mapModelsToVisuals.get(aModel).updateModelDisplay(aModel); lockDrawingSurfaces(false); } /** * For a single OpenSimObject, toggle display hide/show */ public void toggleObjectsDisplay(OpenSimObject openSimObject, boolean visible) { ObjectGroup group = ObjectGroup.safeDownCast(openSimObject); if (group != null) { ArrayObjPtr members = group.getMembers(); for (int i = 0; i < members.getSize(); i++) { toggleObjectDisplay(members.getitem(i), visible); } } else { toggleObjectDisplay(openSimObject, visible); } updateAnnotationAnchors(); // in case object had annotations } public void toggleObjectDisplay(OpenSimObject openSimObject, boolean visible) { // use VisibleObject to hold on/off status, and // do not repaint the windows or update any geometry because // this is now handled by the functions that call toggleObjectDisplay(). //System.out.println("Toggle object "+openSimObject.getName()+" "+ (visible?"On":"Off")); VisibleObject vo = openSimObject.getDisplayer(); if (vo != null) { DisplayPreference dp = vo.getDisplayPreference(); if (visible == true) vo.setDisplayPreference(DisplayPreference.GouraudShaded); // TODO: assumes gouraud is the default else vo.setDisplayPreference(DisplayPreference.None); } else if (openSimObject instanceof DisplayGeometry){ ((DisplayGeometry)openSimObject).setDisplayPreference(visible? DisplayPreference.GouraudShaded: DisplayPreference.None); // TODO: assumes gouraud is the default } Marker marker = Marker.safeDownCast(openSimObject); if (marker != null) { SingleModelVisuals vis = getModelVisuals(marker.getBody().getModel()); vis.setMarkerVisibility(marker, visible); updateAnnotationAnchors(); // in case object had annotations return; } Actuator act = Actuator.safeDownCast(openSimObject); if (act != null) { SingleModelVisuals vis = getModelVisuals(act.getModel()); vis.updateActuatorGeometry(act, visible); // call act.updateGeometry() if actuator is becoming visible updateAnnotationAnchors(); // in case object had annotations return; } Force f = Force.safeDownCast(openSimObject); if (f != null) { SingleModelVisuals vis = getModelVisuals(f.getModel()); vis.updateForceGeometry(f, visible); // call act.updateGeometry() if actuator is becoming visible updateAnnotationAnchors(); // in case object had annotations return; } if (openSimObject instanceof ObjectGroup){ ObjectGroup grp = (ObjectGroup) openSimObject; ArrayObjPtr members = grp.getMembers(); for(int i=0;i<members.getSize();i++) toggleObjectDisplay(members.getitem(i), visible); // Recur return; } // If the object is a vtkAssembly or vtkActor, sets its visibility that way too. final int vtkVisible = visible ? 1 : 0; vtkProp3D asm = ViewDB.getInstance().getVtkRepForObject(openSimObject); ApplyFunctionToActors(asm, new ActorFunctionApplier() { public void apply(vtkActor actor) { actor.SetVisibility(vtkVisible); actor.SetPickable(vtkVisible); }}); } /** * Return a flag indicating if an object is displayed or not **/ public static int getDisplayStatus(OpenSimObject openSimObject) { int visible = 0; ObjectGroup group = ObjectGroup.safeDownCast(openSimObject); if (group != null) { boolean foundHidden = false; boolean foundShown = false; ArrayObjPtr members = group.getMembers(); for (int i = 0; i < members.getSize(); i++) { VisibleObject vo = members.getitem(i).getDisplayer(); if (vo != null) { DisplayPreference dp = vo.getDisplayPreference(); if (dp == DisplayPreference.None) foundHidden = true; else foundShown = true; } } // If the group contains hidden members and shown members, return 2 (mixed). // If the group contains only hidden members, return 0 (hidden). // If the group contains only shown members, return 1 (shown). if (foundHidden == true && foundShown == true) return 2; else if (foundHidden == true) return 0; else return 1; } else { VisibleObject vo = openSimObject.getDisplayer(); if (openSimObject.hasProperty("display_preference")){ int pref = PropertyHelper.getValueInt(openSimObject.getPropertyByName("display_preference")); // 0 hidden){ if (pref!= 0) visible = 1; else visible = 0; } else if (vo != null) { DisplayPreference dp = vo.getDisplayPreference(); if (dp != DisplayPreference.None) visible = 1; } } return visible; } /** * Change representation of a visible object to the one passed in. * The encoding is from VTK and is defined as follows: * 0. Points * 1. Wireframe * 2. Surface * * Shading is defined similarly but only if representation is Surface(2) * 0. Flat * 1. Gouraud * 2. Phong * defined in vtkProperty.h */ public static void setObjectRepresentation(final OpenSimObject object, final int rep, final int newShading) { // Set new rep in model so that it's persistent.' DisplayGeometry.DisplayPreference newPref = DisplayGeometry.DisplayPreference.GouraudShaded; if (rep==1) newPref = DisplayGeometry.DisplayPreference.WireFrame; else if (rep==2 && newShading==0 ) newPref = DisplayGeometry.DisplayPreference.FlatShaded; if (object.getDisplayer()!=null){ final DisplayGeometry.DisplayPreference oldPref = object.getDisplayer().getDisplayPreference(); final DisplayGeometry.DisplayPreference finalNewPref = newPref; object.getDisplayer().setDisplayPreference(newPref); } else if (object instanceof DisplayGeometry) ((DisplayGeometry)object).setDisplayPreference(newPref); vtkProp3D asm = ViewDB.getInstance().getVtkRepForObject(object); ApplyFunctionToActors(asm, new ActorFunctionApplier() { public void apply(vtkActor actor) { actor.GetProperty().SetRepresentation(rep); if (rep==2){ // Surface shading actor.GetProperty().SetInterpolation(newShading); } }}); repaintAll(); } public boolean isPicking() { return picking; } public void setPicking(boolean picking) { this.picking = picking; if (picking) dragging = false; } public boolean isDragging() { return dragging; } public void setDragging(boolean dragging, OpenSimObject obj) { this.dragging = dragging; if (dragging) { // obj not currently used, but it points to the object that was // clicked on to initiate dragging picking = false; } } public void dragSelectedObjects(final OpenSimObject clickedObject, final double dragVector[]) { dragSelectedObjects(clickedObject, dragVector, true); } public void dragSelectedObjects(final OpenSimObject clickedObject, final double dragVector[], boolean supportUndo) { DragObjectsEvent evnt = new DragObjectsEvent(clickedObject, dragVector); //System.out.println("drg vec"+dragVector[0]+" "+dragVector[1]+" "+dragVector[2]); // undo is a drag in the opposite direction! AbstractUndoableEdit auEdit = new AbstractUndoableEdit(){ public boolean canUndo() { return true; } public boolean canRedo() { return true; } public void undo() throws CannotUndoException { super.undo(); final double[] negativeDrag=new double[3]; for(int i=0;i<3;i++) negativeDrag[i]=-dragVector[i]; dragSelectedObjects(clickedObject, negativeDrag, false); } public void redo() throws CannotRedoException { super.redo(); dragSelectedObjects(clickedObject, dragVector, true); } @Override public String getRedoPresentationName() { return "Redo Drag object(s)"; } @Override public String getUndoPresentationName() { return "Undo Drag object(s)"; } }; if (supportUndo) ExplorerTopComponent.addUndoableEdit(auEdit); setChanged(); notifyObservers(evnt); } private void lockDrawingSurfaces(boolean toLock) { Iterator<ModelWindowVTKTopComponent> windowIter = openWindows.iterator(); while(windowIter.hasNext()){ ModelWindowVTKTopComponent nextWindow = windowIter.next(); nextWindow.getCanvas().lockDrawingSurface(toLock); } } public OpenSimObject getSelectedGlyphObject(int cellId, vtkActor glyphActor) { Iterator<SingleModelVisuals> iter = modelVisuals.iterator(); while(iter.hasNext()){ SingleModelVisuals nextModel = iter.next(); OpenSimvtkGlyphCloud glyph = nextModel.getGlyphObjectForActor(glyphActor); if (glyph!=null) return glyph.getPickedObject(cellId); } return null; } /** * User Objects manipulation. Delegate to proper model. * * Use carfully as you're responsible for any cleanup. Selection management is not supported. */ public void addUserObjectToModel(Model model, vtkActor vtkActor) { SingleModelVisuals visModel = mapModelsToVisuals.get(model); visModel.addUserObject(vtkActor); } public void removeUserObjectFromModel(Model model, vtkActor vtkActor) { SingleModelVisuals visModel = mapModelsToVisuals.get(model); if (visModel != null){ visModel.removeUserObject(vtkActor); //removeAnnotationObjects(model); } } public void addUserObjectToCurrentView(vtkActor vtkActor) { getCurrentModelWindow().getCanvas().GetRenderer().AddActor(vtkActor); } /* * Functions to deal with saved "Settings" * processSavedSettings parses the [modelFileWithoutExtension]_settings.xml file */ private String getDefaultSettingsFileName(Model model) { String modelFileName = model.getInputFileName(); // TODO: should we use DocumentFileName or InputFileName? if(modelFileName==null || modelFileName.length()==0) return null; else return modelFileName.substring(0, modelFileName.lastIndexOf("."))+"_settings.xml"; } private void processSavedSettings(Model model) { // Read settings file if exist, should have file name = // [modelFileWithoutExtension]_settings.xml // Should make up a name, use it in emory and change it later per user request if needed. if (model.getFilePath().equalsIgnoreCase("")) return; ModelSettingsSerializer serializer = new ModelSettingsSerializer(getDefaultSettingsFileName(model), true); mapModelsToSettings.put(model, serializer); } private void updateSettingsSerializer(Model model) { ModelSettingsSerializer serializer = mapModelsToSettings.get(model); if(serializer != null) serializer.setFilename(getDefaultSettingsFileName(model)); } /** * Write ettings to an xml file [model-file]_settings.xml */ public void saveSettings(Model model) { mapModelsToSettings.get(model).confirmAndWrite(model); } public ModelSettingsSerializer getModelSavedSettings(Model model) { ModelSettingsSerializer exist = mapModelsToSettings.get(model); if (exist!=null) return exist; return null; } private double[] computeSceneBounds() { Iterator<SingleModelVisuals> iter = modelVisuals.iterator(); double[] bounds = new double[]{.1, -.1, .1, -.1, .1, -.1}; while(iter.hasNext()){ SingleModelVisuals nextModel = iter.next(); bounds = boundsUnion(bounds, nextModel.getBoundsBodiesOnly()); } return bounds; } @Override public void resultChanged(LookupEvent ev) { Lookup.Result r = (Lookup.Result) ev.getSource(); Collection c = r.allInstances(); if (!c.isEmpty()) { Object lup = c.iterator().next(); int x=0; } } /** * Utility: apply a function to given actor, or to all actors in assembly. */ interface ActorFunctionApplier { public void apply(vtkActor actor); } public static void ApplyFunctionToActors(vtkProp3D asm, ActorFunctionApplier functionApplier) { if (asm==null) return; if (asm instanceof vtkAssembly){ vtkProp3DCollection parts = ((vtkAssembly)asm).GetParts(); parts.InitTraversal(); for (;;) { vtkProp3D prop = parts.GetNextProp3D(); if (prop==null) break; else ApplyFunctionToActors(prop, functionApplier); // recur on prop (may be nested assembly?) } } else if (asm instanceof vtkActor){ functionApplier.apply((vtkActor)asm); } } public double getNonCurrentModelOpacity() { String nonCurrentModelOpacityStr = NbBundle.getMessage(ViewDB.class,"CTL_NonCurrentModelOpacity"); nonCurrentModelOpacityStr=Preferences.userNodeForPackage(TheApp.class).get("NonCurrentModelOpacity", nonCurrentModelOpacityStr); if (nonCurrentModelOpacityStr != null) setNonCurrentModelOpacity(Double.valueOf(nonCurrentModelOpacityStr)); return nonCurrentModelOpacity; } public void setNonCurrentModelOpacity(double nonCurrentModelOpacity) { this.nonCurrentModelOpacity = nonCurrentModelOpacity; Preferences.userNodeForPackage(TheApp.class).get("NonCurrentModelOpacity", String.valueOf(nonCurrentModelOpacity)); } /** * Show only the passed in model and hide all others. */ public void isolateModel(Model openSimModel) { Enumeration<Model> models=mapModelsToVisuals.keys(); while(models.hasMoreElements()){ Model next = models.nextElement(); SingleModelVisuals vis = mapModelsToVisuals.get(next); toggleModelDisplay(next, (openSimModel==next)); } repaintAll(); } public double[] getDefaultMarkersColor() { String markersColorStr = NbBundle.getMessage(ViewDB.class,"CTL_MarkersColorRGB"); double[] color = new double[]{1.0, 0.6, 0.8}; markersColorStr =Preferences.userNodeForPackage(TheApp.class).get("Markers Color", markersColorStr); if (markersColorStr != null) color = Prefs.parseColor(markersColorStr); return color; } public double[] getDefaultTextColor() { String textColorStr = NbBundle.getMessage(ViewDB.class,"CTL_TextColorRGB"); double[] color = new double[]{1.0, 1.0, 1.0}; textColorStr =Preferences.userNodeForPackage(TheApp.class).get("Text Color", textColorStr); if (textColorStr != null) color = Prefs.parseColor(textColorStr); return color; } public double getMuscleDisplayRadius() { String muscleDisplayRadiusStr = NbBundle.getMessage(ViewDB.class,"CTL_MuscleRadius"); muscleDisplayRadiusStr =Preferences.userNodeForPackage(TheApp.class).get("Muscle Display Radius", muscleDisplayRadiusStr); if (muscleDisplayRadiusStr != null) { try { muscleDisplayRadius = numFormat.parse(muscleDisplayRadiusStr).doubleValue(); } catch (ParseException ex) { muscleDisplayRadius = 0.01; } } return muscleDisplayRadius; } public void setMuscleDisplayRadius(double muscleDisplayRadius) { this.muscleDisplayRadius = muscleDisplayRadius; } public double getMarkerDisplayRadius() { String markerDisplayRadiusStr = NbBundle.getMessage(ViewDB.class,"CTL_MarkerRadius"); markerDisplayRadiusStr =Preferences.userNodeForPackage(TheApp.class).get("Marker Display Radius", markerDisplayRadiusStr); if (markerDisplayRadiusStr != null) { try { markerDisplayRadius = numFormat.parse(markerDisplayRadiusStr).doubleValue(); } catch (ParseException ex) { markerDisplayRadius = 0.01; } } return markerDisplayRadius; } public void setMarkerDisplayRadius(double markerDisplayRadius) { this.markerDisplayRadius = markerDisplayRadius; } public double getExperimentalMarkerDisplayScale() { String experimentalMarkerDisplayScaleStr="1.0"; String saved=Preferences.userNodeForPackage(TheApp.class).get("Experimental Marker Size", experimentalMarkerDisplayScaleStr); if (saved != null) return (Double.parseDouble(saved)); else return 1.0; } public Object[] getOpenWindows() { return openWindows.toArray(); } public void rebuild(ViewDBDescriptor desc) { // Create a new window per view and give it the specified name int restoredNumViews = desc.getViewNames().size(); if (restoredNumViews==0){ ViewDB.getInstance().removeWindow(getInstance().getCurrentModelWindow()); // Could return here or try to salvage cameras and offsets. return; } for(int viewnum=0; viewnum<restoredNumViews; viewnum++){ // Reuse window we create by default for first model final String nm = desc.getViewNames().get(viewnum); if (viewnum >0){ ModelWindowVTKTopComponent win = getInstance().addViewWindow(nm); win.applyCameraAttributes(desc.getCameraAttributes().get(viewnum)); } else { // We'll justrename existing view' final ModelWindowVTKTopComponent win = getInstance().getCurrentModelWindow(); if (win ==null) continue; if (desc.getCameraAttributes().size()==0) continue; win.applyCameraAttributes(desc.getCameraAttributes().get(viewnum)); SwingUtilities.invokeLater(new Runnable(){ public void run() { win.setTabDisplayName(nm); }}); } } // If no windows were opened just quit this part since loading of VTK symbols // happens only when openning a window if (getInstance().getCurrentModelWindow()==null) return; for(int i=0; i<desc.getOffsetsList().size();i++){ vtkMatrix4x4 m = new vtkMatrix4x4(); double[] savedOffset = desc.getOffsetsList().get(i); for(int j=0; j<3; j++) m.SetElement(j, 3, savedOffset[j]); if (i > modelVisuals.size()-1) break; // CNo need to throw exception for that. Would happen if a model didn't have a file' ViewDB.getInstance().setModelVisualsTransform(modelVisuals.get(i), m); } repaintAll(); } // Assume no display transform here public void addModelVisuals(Model model, SingleModelVisuals dataVisuals) { if (!modelVisuals.contains(dataVisuals)) modelVisuals.add(dataVisuals); mapModelsToVisuals.put(model, dataVisuals); sceneAssembly.AddPart(dataVisuals.getModelDisplayAssembly()); } public void displayText(String text, int forntSize){ textActor.SetInput(text); vtkTextProperty tprop = textActor.GetTextProperty(); tprop.SetFontFamilyToArial(); tprop.SetLineSpacing(1.0); tprop.SetFontSize(forntSize); //System.out.println("Text Color="+getDefaultTextColor()); tprop.SetColor(getDefaultTextColor()); textActor.SetDisplayPosition( 50, 50 ); Iterator<ModelWindowVTKTopComponent> windowIter = openWindows.iterator(); while(windowIter.hasNext()){ ModelWindowVTKTopComponent nextWindow = windowIter.next(); nextWindow.getCanvas().GetRenderer().AddActor2D(textActor); } } public vtkVectorText createText3D(String text, double[] position, double[] color){ vtkVectorText XText=new vtkVectorText(); XText.SetText(text); vtkPolyDataMapper XTextMapper=new vtkPolyDataMapper(); XTextMapper.SetInputConnection(XText.GetOutputPort()); vtkFollower XActor=new vtkFollower(); XActor.SetMapper(XTextMapper); XActor.SetScale(.05, .05, .05); XActor.SetPosition(position); XActor.GetProperty().SetColor(color); vtkCamera lastCamera=new vtkCamera(); if (getCurrentModelWindow()!=null) // need a camera for the follower! lastCamera=getCurrentModelWindow().getCanvas().GetRenderer().GetActiveCamera(); XActor.SetCamera(lastCamera); sceneAssembly.AddPart(XActor); return XText; } /* // Test function to show text billboarding private void createXLabel() { vtkVectorText XText=new vtkVectorText(); XText.SetText("X"); vtkPolyDataMapper XTextMapper=new vtkPolyDataMapper(); XTextMapper.SetInputConnection(XText.GetOutputPort()); vtkFollower XActor=new vtkFollower(); XActor.SetMapper(XTextMapper); XActor.SetScale(.5, .5, .5); XActor.SetPosition(0.1, .2, .3); XActor.GetProperty().SetColor(.1, .2, .3); vtkCamera lastCamera=new vtkCamera(); if (currentModelWindow!=null) // need a camera for the follower! lastCamera=currentModelWindow.getCanvas().GetRenderer().GetActiveCamera(); XActor.SetCamera(lastCamera); sceneAssembly.AddPart(XActor); }*/ public void setQuery(boolean enabled) { query=enabled; //System.out.println("Annotation "+(enabled?"On":"Off")); // remove captions if disabling if (!enabled){ Iterator<vtkCaptionActor2D> captions=selectedObjectsAnnotations.values().iterator(); vtkCaptionActor2D nextCaption; while (captions.hasNext()){ nextCaption = captions.next(); removeAnnotationFromViews(nextCaption); } selectedObjectsAnnotations.clear(); getInstance().repaintAll(); } } public void removeAnnotationFromViews(final vtkActor2D nextCaption) { Iterator<ModelWindowVTKTopComponent> windowIter = openWindows.iterator(); while(windowIter.hasNext()){ ModelWindowVTKTopComponent nextWindow = windowIter.next(); nextWindow.getCanvas().GetRenderer().RemoveActor2D(nextCaption); } } public boolean isQuery() { return query; } /* * Delegate the call to pick to whoever registered as a SelectionListener */ public void pickUserObject(vtkAssemblyPath asmPath, int cellId) { if (asmPath != null) { // User objects are on their own, use their selectionListeners. // Registered with the View User objects know how to select/deselect/anotate themselves vtkAssemblyNode pickedAsm = asmPath.GetLastNode(); for(SelectionListener nextListener:selectionListeners) nextListener.pickUserObject(asmPath, cellId); } return; } public void addSelectionListener(SelectionListener selectionListener) { if (!selectionListeners.contains(selectionListener)) selectionListeners.add(selectionListener); } public void removeSelectionListener(SelectionListener selectionListener) { selectionListeners.remove(selectionListener); } public void updateAnnotationAnchors() { // For each Anotated object, update anchor point as needed Set<Selectable> annotated = selectedObjectsAnnotations.keySet(); for(Selectable nextSelected:annotated){ OpenSimObject dObject = nextSelected.getOpenSimObject(); nextSelected.updateAnchor(selectedObjectsAnnotations.get(nextSelected)); } } public void setOrientation(Model model, double[] d) { SingleModelVisuals visuals = getModelVisuals(model); vtkMatrix4x4 currenTransform=getModelVisualsTransform(visuals); // keep only translation for(int i=0; i<3; i++) for(int j=0; j<3; j++) currenTransform.SetElement(i, j, (i==j)?1.0:0.); vtkTransform newDisplayTransfrom = new vtkTransform(); //Identity newDisplayTransfrom.RotateX(d[0]); newDisplayTransfrom.RotateY(d[1]); newDisplayTransfrom.RotateZ(d[2]); newDisplayTransfrom.Concatenate(currenTransform); getInstance().setModelVisualsTransform(visuals, newDisplayTransfrom.GetMatrix()); } private void removeAnnotationObjects(Model dModel) { Iterator<Selectable> selectedObjsIter = selectedObjectsAnnotations.keySet().iterator(); while(selectedObjsIter.hasNext()){ Selectable nextObject= selectedObjsIter.next(); if (nextObject.getOwnerModel().equals(dModel)){ vtkCaptionActor2D caption=selectedObjectsAnnotations.get(nextObject); getCurrentModelWindow().getCanvas().GetRenderer().RemoveActor2D(caption); selectedObjsIter.remove(); } } } private vtkCaptionActor2D getAnnotation(Selectable selectedObject) { Iterator<Selectable> selectedObjsIter = selectedObjectsAnnotations.keySet().iterator(); while(selectedObjsIter.hasNext()){ Selectable nextObject= selectedObjsIter.next(); if (nextObject==selectedObject) return selectedObjectsAnnotations.get(selectedObject); } return null; } /** Debugging */ public int getDebugLevel() { return debugLevel; } public void setDebugLevel(int debugLevel) { this.debugLevel = debugLevel; } // This handles disablement/enablement private void handleObjectsEnabledStateChangeEvent(Object arg) { ObjectEnabledStateChangeEvent ev = (ObjectEnabledStateChangeEvent)arg; Vector<OpenSimObject> objs = ev.getObjects(); boolean repaint = false; boolean selectedDeleted = false; for (int i=0; i<objs.size(); i++) { OpenSimObject obj = objs.get(i); int j = findObjectInSelectedList(obj); if (j >= 0) { selectedObjects.remove(j); selectedDeleted = true; } // Forces now if (obj instanceof Force){ Force f = Force.safeDownCast(obj); boolean newState = f.get_isDisabled(); if (f instanceof Muscle) { PathActuator m = PathActuator.safeDownCast(f); if (!newState){ getModelVisuals(m.getModel()).addPathActuatorGeometry(m, true); toggleObjectsDisplay(m, true); } else{ // turning off removeObjectsBelongingToMuscleFromSelection(obj); getModelVisuals(ev.getModel()).removeGeometry(obj); } repaint = true; } else { // Other forces if (!newState){ // turn on f.getDisplayer().setDisplayPreference(DisplayPreference.GouraudShaded); getModelVisuals(ev.getModel()).updateForceGeometry(ev.getModel()); } else { // turning off getModelVisuals(ev.getModel()).removeGeometry(obj); } repaint = true; } } } if (repaint) repaintAll(); } public void removeObjectAnnotationFromViews(vtkCaptionActor2D caption) { // Cycle thru array and remove Caption if warranted Iterator<vtkCaptionActor2D> captions=selectedObjectsAnnotations.values().iterator(); vtkCaptionActor2D nextCaption; while (captions.hasNext()){ nextCaption = captions.next(); if (nextCaption.equals(caption)) removeAnnotationFromViews(nextCaption); } } public static boolean isGraphicsAvailable() { return graphicsAvailable; } public static void setGraphicsAvailable(boolean aGraphicsAvailable) { graphicsAvailable = aGraphicsAvailable; } public static void printBounds(String name, double[] bodyBounds) { System.out.print("Bounds for "+name+" are:["); for(int i=0; i<6; i++) System.out.print(bodyBounds[i]+" "); System.out.println("\n============"); } }
package Ordered_Jobs.solution1; import org.jetbrains.annotations.NotNull; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import static org.testng.AssertJUnit.assertEquals; public class OrderedJobsTest { private OrderedJobs jobs; @Before public void setUp() throws Exception { jobs = new OrderedJobsImpl(); } @Test public void givenNull_sortReturnsEmptyString() throws Exception { assertEquals("", jobs.sort()); } @Test public void givenRegisterA_sortReturnsA() throws Exception { jobs.register('A'); assertEquals("A", jobs.sort()); } @Test public void givenMultipleRegistrationsOfA_sortReturnsA() throws Exception { jobs.register('A'); jobs.register('A'); jobs.register('A'); assertEquals("A", jobs.sort()); } @Test public void givenRegisterBDependentOnA_sortReturnsAB() throws Exception { jobs.register('B', 'A'); assertEquals("AB", jobs.sort()); } @Test public void integrationABC() throws Exception { jobs.register('C'); jobs.register('B', 'A'); jobs.register('C', 'B'); assertEquals("ABC", jobs.sort()); } private class OrderedJobsImpl implements OrderedJobs { final ArrayList<Job> jobs = new ArrayList<>(); @Override public void register(char dependentJob, char independentJob) { register(dependentJob); addDependency(dependentJob, independentJob); } private void addDependency(char dependentJob, char independentJob) { register(independentJob); Job dependency = this.getJob(independentJob); jobs.get(getIndex(dependentJob)).addDependency(dependency); } private Job getJob(char jobID) { return jobs.get(getIndex(jobID)); } @Override public void register(char jobID) { Job job = new Job(jobID); if (!isIDRegenerated(jobID)) { jobs.add(job); } } private boolean isIDRegenerated(char jobID) { return getIndex(jobID) >= 0; } private int getIndex(char jobID) { for (int i = 0; i < jobs.size(); i++) { if (jobs.get(i).jobID == jobID) return i; } return -1; } @Override public String sort() { jobs.sort((o1, o2) -> o1.dependencies.size() - o2.dependencies.size()); return jobsToString(); } @NotNull private String jobsToString() { String out = ""; for (Job job : jobs) { out += job.jobID; } return out; } private class Job { private ArrayList<Job> dependencies = new ArrayList<>(); private char jobID; private Job(char jobID) { this.jobID = jobID; } void addDependency(Job dependency) { this.dependencies.add(dependency); } } } }
package org.postgresql; import java.io.*; import java.net.*; import java.sql.*; import java.util.*; import org.postgresql.Field; import org.postgresql.fastpath.*; import org.postgresql.largeobject.*; import org.postgresql.util.*; import org.postgresql.core.*; /** * $Id: Connection.java,v 1.31 2001/10/16 20:05:22 barry Exp $ * * This abstract class is used by org.postgresql.Driver to open either the JDBC1 or * JDBC2 versions of the Connection class. * */ public abstract class Connection { // This is the network stream associated with this connection public PG_Stream pg_stream; private String PG_HOST; private int PG_PORT; private String PG_USER; private String PG_PASSWORD; private String PG_DATABASE; private boolean PG_STATUS; private String compatible; /** * The encoding to use for this connection. */ private Encoding encoding = Encoding.defaultEncoding(); private String dbVersionNumber; public boolean CONNECTION_OK = true; public boolean CONNECTION_BAD = false; public boolean autoCommit = true; public boolean readOnly = false; public Driver this_driver; private String this_url; private String cursor = null; // The positioned update cursor name // These are new for v6.3, they determine the current protocol versions // supported by this version of the driver. They are defined in // src/include/libpq/pqcomm.h protected static final int PG_PROTOCOL_LATEST_MAJOR = 2; protected static final int PG_PROTOCOL_LATEST_MINOR = 0; private static final int SM_DATABASE = 64; private static final int SM_USER = 32; private static final int SM_OPTIONS = 64; private static final int SM_UNUSED = 64; private static final int SM_TTY = 64; private static final int AUTH_REQ_OK = 0; private static final int AUTH_REQ_KRB4 = 1; private static final int AUTH_REQ_KRB5 = 2; private static final int AUTH_REQ_PASSWORD = 3; private static final int AUTH_REQ_CRYPT = 4; // New for 6.3, salt value for crypt authorisation private String salt; // These are used to cache oids, PGTypes and SQLTypes private static Hashtable sqlTypeCache = new Hashtable(); // oid -> SQLType private static Hashtable pgTypeCache = new Hashtable(); // oid -> PGType private static Hashtable typeOidCache = new Hashtable(); //PGType -> oid // Now handle notices as warnings, so things like "show" now work public SQLWarning firstWarning = null; /** * Cache of the current isolation level */ private int isolationLevel = java.sql.Connection.TRANSACTION_READ_COMMITTED; // The PID an cancellation key we get from the backend process public int pid; public int ckey; /** * This is called by Class.forName() from within org.postgresql.Driver */ public Connection() { } /** * This method actually opens the connection. It is called by Driver. * * @param host the hostname of the database back end * @param port the port number of the postmaster process * @param info a Properties[] thing of the user and password * @param database the database to connect to * @param u the URL of the connection * @param d the Driver instantation of the connection * @return a valid connection profile * @exception SQLException if a database access error occurs */ protected void openConnection(String host, int port, Properties info, String database, String url, Driver d) throws SQLException { // Throw an exception if the user or password properties are missing // This occasionally occurs when the client uses the properties version // of getConnection(), and is a common question on the email lists if(info.getProperty("user")==null) throw new PSQLException("postgresql.con.user"); if(info.getProperty("password")==null) throw new PSQLException("postgresql.con.pass"); this_driver = d; this_url = url; PG_DATABASE = database; PG_PASSWORD = info.getProperty("password"); PG_USER = info.getProperty("user"); PG_PORT = port; PG_HOST = host; PG_STATUS = CONNECTION_BAD; if(info.getProperty("compatible")==null) { compatible = d.getMajorVersion() + "." + d.getMinorVersion(); } else { compatible = info.getProperty("compatible"); } // Now make the initial connection try { pg_stream = new PG_Stream(host, port); } catch (ConnectException cex) { // Added by Peter Mount <peter@retep.org.uk> // ConnectException is thrown when the connection cannot be made. // we trap this an return a more meaningful message for the end user throw new PSQLException ("postgresql.con.refused"); } catch (IOException e) { throw new PSQLException ("postgresql.con.failed",e); } // Now we need to construct and send a startup packet try { // Ver 6.3 code pg_stream.SendInteger(4+4+SM_DATABASE+SM_USER+SM_OPTIONS+SM_UNUSED+SM_TTY,4); pg_stream.SendInteger(PG_PROTOCOL_LATEST_MAJOR,2); pg_stream.SendInteger(PG_PROTOCOL_LATEST_MINOR,2); pg_stream.Send(database.getBytes(),SM_DATABASE); // This last send includes the unused fields pg_stream.Send(PG_USER.getBytes(),SM_USER+SM_OPTIONS+SM_UNUSED+SM_TTY); // now flush the startup packets to the backend pg_stream.flush(); // Now get the response from the backend, either an error message // or an authentication request int areq = -1; // must have a value here do { int beresp = pg_stream.ReceiveChar(); switch(beresp) { case 'E': // An error occured, so pass the error message to the // user. // The most common one to be thrown here is: // "User authentication failed" throw new SQLException(pg_stream.ReceiveString(encoding)); case 'R': // Get the type of request areq = pg_stream.ReceiveIntegerR(4); // Get the password salt if there is one if(areq == AUTH_REQ_CRYPT) { byte[] rst = new byte[2]; rst[0] = (byte)pg_stream.ReceiveChar(); rst[1] = (byte)pg_stream.ReceiveChar(); salt = new String(rst,0,2); DriverManager.println("Salt="+salt); } // now send the auth packet switch(areq) { case AUTH_REQ_OK: break; case AUTH_REQ_KRB4: DriverManager.println("postgresql: KRB4"); throw new PSQLException("postgresql.con.kerb4"); case AUTH_REQ_KRB5: DriverManager.println("postgresql: KRB5"); throw new PSQLException("postgresql.con.kerb5"); case AUTH_REQ_PASSWORD: DriverManager.println("postgresql: PASSWORD"); pg_stream.SendInteger(5+PG_PASSWORD.length(),4); pg_stream.Send(PG_PASSWORD.getBytes()); pg_stream.SendInteger(0,1); pg_stream.flush(); break; case AUTH_REQ_CRYPT: DriverManager.println("postgresql: CRYPT"); String crypted = UnixCrypt.crypt(salt,PG_PASSWORD); pg_stream.SendInteger(5+crypted.length(),4); pg_stream.Send(crypted.getBytes()); pg_stream.SendInteger(0,1); pg_stream.flush(); break; default: throw new PSQLException("postgresql.con.auth",new Integer(areq)); } break; default: throw new PSQLException("postgresql.con.authfail"); } } while(areq != AUTH_REQ_OK); } catch (IOException e) { throw new PSQLException("postgresql.con.failed",e); } // As of protocol version 2.0, we should now receive the cancellation key and the pid int beresp = pg_stream.ReceiveChar(); switch(beresp) { case 'K': pid = pg_stream.ReceiveInteger(4); ckey = pg_stream.ReceiveInteger(4); break; case 'E': case 'N': throw new SQLException(pg_stream.ReceiveString(encoding)); default: throw new PSQLException("postgresql.con.setup"); } // Expect ReadyForQuery packet beresp = pg_stream.ReceiveChar(); switch(beresp) { case 'Z': break; case 'E': case 'N': throw new SQLException(pg_stream.ReceiveString(encoding)); default: throw new PSQLException("postgresql.con.setup"); } firstWarning = null; // "pg_encoding_to_char(1)" will return 'EUC_JP' for a backend compiled with multibyte, // otherwise it's hardcoded to 'SQL_ASCII'. // If the backend doesn't know about multibyte we can't assume anything about the encoding // used, so we denote this with 'UNKNOWN'. //Note: begining with 7.2 we should be using pg_client_encoding() which //is new in 7.2. However it isn't easy to conditionally call this new //function, since we don't yet have the information as to what server //version we are talking to. Thus we will continue to call //getdatabaseencoding() until we drop support for 7.1 and older versions //or until someone comes up with a conditional way to run one or //the other function depending on server version that doesn't require //two round trips to the server per connection final String encodingQuery = "case when pg_encoding_to_char(1) = 'SQL_ASCII' then 'UNKNOWN' else getdatabaseencoding() end"; // Set datestyle and fetch db encoding in a single call, to avoid making // more than one round trip to the backend during connection startup. java.sql.ResultSet resultSet = ExecSQL("set datestyle to 'ISO'; select version(), " + encodingQuery + ";"); if (! resultSet.next()) { throw new PSQLException("postgresql.con.failed", "failed getting backend encoding"); } String version = resultSet.getString(1); dbVersionNumber = extractVersionNumber(version); String dbEncoding = resultSet.getString(2); encoding = Encoding.getEncoding(dbEncoding, info.getProperty("charSet")); // Initialise object handling initObjectTypes(); // Mark the connection as ok, and cleanup firstWarning = null; PG_STATUS = CONNECTION_OK; } // These methods used to be in the main Connection implementation. As they // are common to all implementations (JDBC1 or 2), they are placed here. // This should make it easy to maintain the two specifications. /** * This adds a warning to the warning chain. * @param msg message to add */ public void addWarning(String msg) { DriverManager.println(msg); // Add the warning to the chain if(firstWarning!=null) firstWarning.setNextWarning(new SQLWarning(msg)); else firstWarning = new SQLWarning(msg); // Now check for some specific messages // This is obsolete in 6.5, but I've left it in here so if we need to use this // technique again, we'll know where to place it. // This is generated by the SQL "show datestyle" //if(msg.startsWith("NOTICE:") && msg.indexOf("DateStyle")>0) { //// 13 is the length off "DateStyle is " //msg = msg.substring(msg.indexOf("DateStyle is ")+13); //for(int i=0;i<dateStyles.length;i+=2) //if(msg.startsWith(dateStyles[i])) //currentDateStyle=i+1; // this is the index of the format } /** * Send a query to the backend. Returns one of the ResultSet * objects. * * <B>Note:</B> there does not seem to be any method currently * in existance to return the update count. * * @param sql the SQL statement to be executed * @return a ResultSet holding the results * @exception SQLException if a database error occurs */ public java.sql.ResultSet ExecSQL(String sql) throws SQLException { return ExecSQL(sql,null); } /** * Send a query to the backend. Returns one of the ResultSet * objects. * * <B>Note:</B> there does not seem to be any method currently * in existance to return the update count. * * @param sql the SQL statement to be executed * @param stat The Statement associated with this query (may be null) * @return a ResultSet holding the results * @exception SQLException if a database error occurs */ public java.sql.ResultSet ExecSQL(String sql, java.sql.Statement stat) throws SQLException { return new QueryExecutor(sql, stat, pg_stream, this).execute(); } /** * In SQL, a result table can be retrieved through a cursor that * is named. The current row of a result can be updated or deleted * using a positioned update/delete statement that references the * cursor name. * * We support one cursor per connection. * * setCursorName sets the cursor name. * * @param cursor the cursor name * @exception SQLException if a database access error occurs */ public void setCursorName(String cursor) throws SQLException { this.cursor = cursor; } /** * getCursorName gets the cursor name. * * @return the current cursor name * @exception SQLException if a database access error occurs */ public String getCursorName() throws SQLException { return cursor; } /** * We are required to bring back certain information by * the DatabaseMetaData class. These functions do that. * * Method getURL() brings back the URL (good job we saved it) * * @return the url * @exception SQLException just in case... */ public String getURL() throws SQLException { return this_url; } /** * Method getUserName() brings back the User Name (again, we * saved it) * * @return the user name * @exception SQLException just in case... */ public String getUserName() throws SQLException { return PG_USER; } /** * Get the character encoding to use for this connection. */ public Encoding getEncoding() throws SQLException { return encoding; } /** * This returns the Fastpath API for the current connection. * * <p><b>NOTE:</b> This is not part of JDBC, but allows access to * functions on the org.postgresql backend itself. * * <p>It is primarily used by the LargeObject API * * <p>The best way to use this is as follows: * * <p><pre> * import org.postgresql.fastpath.*; * ... * Fastpath fp = ((org.postgresql.Connection)myconn).getFastpathAPI(); * </pre> * * <p>where myconn is an open Connection to org.postgresql. * * @return Fastpath object allowing access to functions on the org.postgresql * backend. * @exception SQLException by Fastpath when initialising for first time */ public Fastpath getFastpathAPI() throws SQLException { if(fastpath==null) fastpath = new Fastpath(this,pg_stream); return fastpath; } // This holds a reference to the Fastpath API if already open private Fastpath fastpath = null; /** * This returns the LargeObject API for the current connection. * * <p><b>NOTE:</b> This is not part of JDBC, but allows access to * functions on the org.postgresql backend itself. * * <p>The best way to use this is as follows: * * <p><pre> * import org.postgresql.largeobject.*; * ... * LargeObjectManager lo = ((org.postgresql.Connection)myconn).getLargeObjectAPI(); * </pre> * * <p>where myconn is an open Connection to org.postgresql. * * @return LargeObject object that implements the API * @exception SQLException by LargeObject when initialising for first time */ public LargeObjectManager getLargeObjectAPI() throws SQLException { if(largeobject==null) largeobject = new LargeObjectManager(this); return largeobject; } // This holds a reference to the LargeObject API if already open private LargeObjectManager largeobject = null; /** * This method is used internally to return an object based around * org.postgresql's more unique data types. * * <p>It uses an internal Hashtable to get the handling class. If the * type is not supported, then an instance of org.postgresql.util.PGobject * is returned. * * You can use the getValue() or setValue() methods to handle the returned * object. Custom objects can have their own methods. * * In 6.4, this is extended to use the org.postgresql.util.Serialize class to * allow the Serialization of Java Objects into the database without using * Blobs. Refer to that class for details on how this new feature works. * * @return PGobject for this type, and set to value * @exception SQLException if value is not correct for this type * @see org.postgresql.util.Serialize */ public Object getObject(String type,String value) throws SQLException { try { Object o = objectTypes.get(type); // If o is null, then the type is unknown, so check to see if type // is an actual table name. If it does, see if a Class is known that // can handle it if(o == null) { Serialize ser = new Serialize(this,type); objectTypes.put(type,ser); return ser.fetch(Integer.parseInt(value)); } // If o is not null, and it is a String, then its a class name that // extends PGobject. // This is used to implement the org.postgresql unique types (like lseg, // point, etc). if(o instanceof String) { // 6.3 style extending PG_Object PGobject obj = null; obj = (PGobject)(Class.forName((String)o).newInstance()); obj.setType(type); obj.setValue(value); return (Object)obj; } else { // If it's an object, it should be an instance of our Serialize class // If so, then call it's fetch method. if(o instanceof Serialize) return ((Serialize)o).fetch(Integer.parseInt(value)); } } catch(SQLException sx) { // rethrow the exception. Done because we capture any others next sx.fillInStackTrace(); throw sx; } catch(Exception ex) { throw new PSQLException("postgresql.con.creobj",type,ex); } // should never be reached return null; } /** * This stores an object into the database. * @param o Object to store * @return OID of the new rectord * @exception SQLException if value is not correct for this type * @see org.postgresql.util.Serialize */ public int putObject(Object o) throws SQLException { try { String type = o.getClass().getName(); Object x = objectTypes.get(type); // If x is null, then the type is unknown, so check to see if type // is an actual table name. If it does, see if a Class is known that // can handle it if(x == null) { Serialize ser = new Serialize(this,type); objectTypes.put(type,ser); return ser.store(o); } // If it's an object, it should be an instance of our Serialize class // If so, then call it's fetch method. if(x instanceof Serialize) return ((Serialize)x).store(o); // Thow an exception because the type is unknown throw new PSQLException("postgresql.con.strobj"); } catch(SQLException sx) { // rethrow the exception. Done because we capture any others next sx.fillInStackTrace(); throw sx; } catch(Exception ex) { throw new PSQLException("postgresql.con.strobjex",ex); } } /** * This allows client code to add a handler for one of org.postgresql's * more unique data types. * * <p><b>NOTE:</b> This is not part of JDBC, but an extension. * * <p>The best way to use this is as follows: * * <p><pre> * ... * ((org.postgresql.Connection)myconn).addDataType("mytype","my.class.name"); * ... * </pre> * * <p>where myconn is an open Connection to org.postgresql. * * <p>The handling class must extend org.postgresql.util.PGobject * * @see org.postgresql.util.PGobject */ public void addDataType(String type,String name) { objectTypes.put(type,name); } // This holds the available types private Hashtable objectTypes = new Hashtable(); // This array contains the types that are supported as standard. // The first entry is the types name on the database, the second // the full class name of the handling class. private static final String defaultObjectTypes[][] = { {"box", "org.postgresql.geometric.PGbox"}, {"circle", "org.postgresql.geometric.PGcircle"}, {"line", "org.postgresql.geometric.PGline"}, {"lseg", "org.postgresql.geometric.PGlseg"}, {"path", "org.postgresql.geometric.PGpath"}, {"point", "org.postgresql.geometric.PGpoint"}, {"polygon", "org.postgresql.geometric.PGpolygon"}, {"money", "org.postgresql.util.PGmoney"} }; // This initialises the objectTypes hashtable private void initObjectTypes() { for(int i=0;i<defaultObjectTypes.length;i++) objectTypes.put(defaultObjectTypes[i][0],defaultObjectTypes[i][1]); } // These are required by other common classes public abstract java.sql.Statement createStatement() throws SQLException; /** * This returns a resultset. It must be overridden, so that the correct * version (from jdbc1 or jdbc2) are returned. */ public abstract java.sql.ResultSet getResultSet(org.postgresql.Connection conn,java.sql.Statement stat, Field[] fields, Vector tuples, String status, int updateCount,int insertOID, boolean binaryCursor) throws SQLException; /** * In some cases, it is desirable to immediately release a Connection's * database and JDBC resources instead of waiting for them to be * automatically released (cant think why off the top of my head) * * <B>Note:</B> A Connection is automatically closed when it is * garbage collected. Certain fatal errors also result in a closed * connection. * * @exception SQLException if a database access error occurs */ public void close() throws SQLException { if (pg_stream != null) { try { pg_stream.SendChar('X'); pg_stream.flush(); pg_stream.close(); } catch (IOException e) {} pg_stream = null; } } /** * A driver may convert the JDBC sql grammar into its system's * native SQL grammar prior to sending it; nativeSQL returns the * native form of the statement that the driver would have sent. * * @param sql a SQL statement that may contain one or more '?' * parameter placeholders * @return the native form of this statement * @exception SQLException if a database access error occurs */ public String nativeSQL(String sql) throws SQLException { return sql; } /** * The first warning reported by calls on this Connection is * returned. * * <B>Note:</B> Sebsequent warnings will be changed to this * SQLWarning * * @return the first SQLWarning or null * @exception SQLException if a database access error occurs */ public SQLWarning getWarnings() throws SQLException { return firstWarning; } /** * After this call, getWarnings returns null until a new warning * is reported for this connection. * * @exception SQLException if a database access error occurs */ public void clearWarnings() throws SQLException { firstWarning = null; } /** * You can put a connection in read-only mode as a hunt to enable * database optimizations * * <B>Note:</B> setReadOnly cannot be called while in the middle * of a transaction * * @param readOnly - true enables read-only mode; false disables it * @exception SQLException if a database access error occurs */ public void setReadOnly(boolean readOnly) throws SQLException { this.readOnly = readOnly; } /** * Tests to see if the connection is in Read Only Mode. Note that * we cannot really put the database in read only mode, but we pretend * we can by returning the value of the readOnly flag * * @return true if the connection is read only * @exception SQLException if a database access error occurs */ public boolean isReadOnly() throws SQLException { return readOnly; } /** * If a connection is in auto-commit mode, than all its SQL * statements will be executed and committed as individual * transactions. Otherwise, its SQL statements are grouped * into transactions that are terminated by either commit() * or rollback(). By default, new connections are in auto- * commit mode. The commit occurs when the statement completes * or the next execute occurs, whichever comes first. In the * case of statements returning a ResultSet, the statement * completes when the last row of the ResultSet has been retrieved * or the ResultSet has been closed. In advanced cases, a single * statement may return multiple results as well as output parameter * values. Here the commit occurs when all results and output param * values have been retrieved. * * @param autoCommit - true enables auto-commit; false disables it * @exception SQLException if a database access error occurs */ public void setAutoCommit(boolean autoCommit) throws SQLException { if (this.autoCommit == autoCommit) return; if (autoCommit) ExecSQL("end"); else { if (haveMinimumServerVersion("7.1")){ ExecSQL("begin;"+getIsolationLevelSQL()); }else{ ExecSQL("begin"); ExecSQL(getIsolationLevelSQL()); } } this.autoCommit = autoCommit; } /** * gets the current auto-commit state * * @return Current state of the auto-commit mode * @exception SQLException (why?) * @see setAutoCommit */ public boolean getAutoCommit() throws SQLException { return this.autoCommit; } /** * The method commit() makes all changes made since the previous * commit/rollback permanent and releases any database locks currently * held by the Connection. This method should only be used when * auto-commit has been disabled. (If autoCommit == true, then we * just return anyhow) * * @exception SQLException if a database access error occurs * @see setAutoCommit */ public void commit() throws SQLException { if (autoCommit) return; if (haveMinimumServerVersion("7.1")){ ExecSQL("commit;begin;"+getIsolationLevelSQL()); }else{ ExecSQL("commit"); ExecSQL("begin"); ExecSQL(getIsolationLevelSQL()); } } /** * The method rollback() drops all changes made since the previous * commit/rollback and releases any database locks currently held by * the Connection. * * @exception SQLException if a database access error occurs * @see commit */ public void rollback() throws SQLException { if (autoCommit) return; if (haveMinimumServerVersion("7.1")){ ExecSQL("rollback; begin;"+getIsolationLevelSQL()); }else{ ExecSQL("rollback"); ExecSQL("begin"); ExecSQL(getIsolationLevelSQL()); } } /** * Get this Connection's current transaction isolation mode. * * @return the current TRANSACTION_* mode value * @exception SQLException if a database access error occurs */ public int getTransactionIsolation() throws SQLException { clearWarnings(); ExecSQL("show xactisolevel"); SQLWarning warning = getWarnings(); if (warning != null) { String message = warning.getMessage(); clearWarnings(); if (message.indexOf("READ COMMITTED") != -1) return java.sql.Connection.TRANSACTION_READ_COMMITTED; else if (message.indexOf("READ UNCOMMITTED") != -1) return java.sql.Connection.TRANSACTION_READ_UNCOMMITTED; else if (message.indexOf("REPEATABLE READ") != -1) return java.sql.Connection.TRANSACTION_REPEATABLE_READ; else if (message.indexOf("SERIALIZABLE") != -1) return java.sql.Connection.TRANSACTION_SERIALIZABLE; } return java.sql.Connection.TRANSACTION_READ_COMMITTED; } /** * You can call this method to try to change the transaction * isolation level using one of the TRANSACTION_* values. * * <B>Note:</B> setTransactionIsolation cannot be called while * in the middle of a transaction * * @param level one of the TRANSACTION_* isolation values with * the exception of TRANSACTION_NONE; some databases may * not support other values * @exception SQLException if a database access error occurs * @see java.sql.DatabaseMetaData#supportsTransactionIsolationLevel */ public void setTransactionIsolation(int level) throws SQLException { //In 7.1 and later versions of the server it is possible using //the "set session" command to set this once for all future txns //however in 7.0 and prior versions it is necessary to set it in //each transaction, thus adding complexity below. //When we decide to drop support for servers older than 7.1 //this can be simplified isolationLevel = level; String isolationLevelSQL; if (!haveMinimumServerVersion("7.1")) { isolationLevelSQL = getIsolationLevelSQL(); } else { isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL "; switch(isolationLevel) { case java.sql.Connection.TRANSACTION_READ_COMMITTED: isolationLevelSQL += "READ COMMITTED"; break; case java.sql.Connection.TRANSACTION_SERIALIZABLE: isolationLevelSQL += "SERIALIZABLE"; break; default: throw new PSQLException("postgresql.con.isolevel", new Integer(isolationLevel)); } } ExecSQL(isolationLevelSQL); } /** * Helper method used by setTransactionIsolation(), commit(), rollback() * and setAutoCommit(). This returns the SQL string needed to * set the isolation level for a transaction. In 7.1 and later it * is possible to set a default isolation level that applies to all * future transactions, this method is only necesary for 7.0 and older * servers, and should be removed when support for these older * servers are dropped */ protected String getIsolationLevelSQL() throws SQLException { //7.1 and higher servers have a default specified so //no additional SQL is required to set the isolation level if (haveMinimumServerVersion("7.1")) { return ""; } StringBuffer sb = new StringBuffer("SET TRANSACTION ISOLATION LEVEL"); switch(isolationLevel) { case java.sql.Connection.TRANSACTION_READ_COMMITTED: sb.append(" READ COMMITTED"); break; case java.sql.Connection.TRANSACTION_SERIALIZABLE: sb.append(" SERIALIZABLE"); break; default: throw new PSQLException("postgresql.con.isolevel",new Integer(isolationLevel)); } return sb.toString(); } /** * A sub-space of this Connection's database may be selected by * setting a catalog name. If the driver does not support catalogs, * it will silently ignore this request * * @exception SQLException if a database access error occurs */ public void setCatalog(String catalog) throws SQLException { //no-op } /** * Return the connections current catalog name, or null if no * catalog name is set, or we dont support catalogs. * * @return the current catalog name or null * @exception SQLException if a database access error occurs */ public String getCatalog() throws SQLException { return PG_DATABASE; } /** * Overides finalize(). If called, it closes the connection. * * This was done at the request of Rachel Greenham * <rachel@enlarion.demon.co.uk> who hit a problem where multiple * clients didn't close the connection, and once a fortnight enough * clients were open to kill the org.postgres server. */ public void finalize() throws Throwable { close(); } private static String extractVersionNumber(String fullVersionString) { StringTokenizer versionParts = new StringTokenizer(fullVersionString); versionParts.nextToken(); /* "PostgreSQL" */ return versionParts.nextToken(); /* "X.Y.Z" */ } /** * Get server version number */ public String getDBVersionNumber() { return dbVersionNumber; } public boolean haveMinimumServerVersion(String ver) throws SQLException { return (getDBVersionNumber().compareTo(ver) >= 0); } /** * This method returns true if the compatible level set in the connection * (which can be passed into the connection or specified in the URL) * is at least the value passed to this method. This is used to toggle * between different functionality as it changes across different releases * of the jdbc driver code. The values here are versions of the jdbc client * and not server versions. For example in 7.1 get/setBytes worked on * LargeObject values, in 7.2 these methods were changed to work on bytea * values. This change in functionality could be disabled by setting the * "compatible" level to be 7.1, in which case the driver will revert to * the 7.1 functionality. */ public boolean haveMinimumCompatibleVersion(String ver) throws SQLException { return (compatible.compareTo(ver) >= 0); } /** * This returns the java.sql.Types type for a PG type oid * * @param oid PostgreSQL type oid * @return the java.sql.Types type * @exception SQLException if a database access error occurs */ public int getSQLType(int oid) throws SQLException { Integer sqlType = (Integer)typeOidCache.get(new Integer(oid)); // it's not in the cache, so perform a query, and add the result to the cache if(sqlType==null) { ResultSet result = (org.postgresql.ResultSet)ExecSQL("select typname from pg_type where oid = " + oid); if (result.getColumnCount() != 1 || result.getTupleCount() != 1) throw new PSQLException("postgresql.unexpected"); result.next(); String pgType = result.getString(1); Integer iOid = new Integer(oid); sqlType = new Integer(getSQLType(result.getString(1))); sqlTypeCache.put(iOid,sqlType); pgTypeCache.put(iOid,pgType); result.close(); } return sqlType.intValue(); } /** * This returns the java.sql.Types type for a PG type * * @param pgTypeName PostgreSQL type name * @return the java.sql.Types type */ public abstract int getSQLType(String pgTypeName); /** * This returns the oid for a given PG data type * @param typeName PostgreSQL type name * @return PostgreSQL oid value for a field of this type */ public int getOID(String typeName) throws SQLException { int oid = -1; if(typeName != null) { Integer oidValue = (Integer) typeOidCache.get(typeName); if(oidValue != null) { oid = oidValue.intValue(); } else { // it's not in the cache, so perform a query, and add the result to the cache ResultSet result = (org.postgresql.ResultSet)ExecSQL("select oid from pg_type where typname='" + typeName + "'"); if (result.getColumnCount() != 1 || result.getTupleCount() != 1) throw new PSQLException("postgresql.unexpected"); result.next(); oid = Integer.parseInt(result.getString(1)); typeOidCache.put(typeName, new Integer(oid)); result.close(); } } return oid; } /** * We also need to get the PG type name as returned by the back end. * * @return the String representation of the type of this field * @exception SQLException if a database access error occurs */ public String getPGType(int oid) throws SQLException { String pgType = (String) pgTypeCache.get(new Integer(oid)); if(pgType == null) { getSQLType(oid); pgType = (String) pgTypeCache.get(new Integer(oid)); } return pgType; } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import java.util.concurrent.ExecutionException; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout(5, 5)); JTextArea area = new JTextArea(); area.setEditable(false); ProgressMonitor dmy = new ProgressMonitor(null, "message dummy", "note", 0, 100); SpinnerNumberModel millisToDecide = new SpinnerNumberModel(dmy.getMillisToDecideToPopup(), 0, 5 * 1000, 100); SpinnerNumberModel millisToPopup = new SpinnerNumberModel(dmy.getMillisToPopup(), 0, 5 * 1000, 100); JButton runButton = new JButton("run"); runButton.addActionListener(e -> { Window w = SwingUtilities.getWindowAncestor(runButton); int toDecideToPopup = millisToDecide.getNumber().intValue(); int toPopup = millisToPopup.getNumber().intValue(); ProgressMonitor monitor = new ProgressMonitor(w, "message", "note", 0, 100); monitor.setMillisToDecideToPopup(toDecideToPopup); monitor.setMillisToPopup(toPopup); // System.out.println(monitor.getMillisToDecideToPopup()); // System.out.println(monitor.getMillisToPopup()); int lengthOfTask = Math.max(10_000, toDecideToPopup * 5); runButton.setEnabled(false); executeWorker(monitor, lengthOfTask, runButton, area); }); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.insets = new Insets(5, 5, 5, 0); c.anchor = GridBagConstraints.LINE_END; JPanel p = new JPanel(new GridBagLayout()); p.add(new JLabel("MillisToDecideToPopup:"), c); p.add(new JLabel("MillisToPopup:"), c); c.gridx = 1; c.weightx = 1d; c.fill = GridBagConstraints.HORIZONTAL; p.add(new JSpinner(millisToDecide), c); p.add(new JSpinner(millisToPopup), c); Box box = Box.createHorizontalBox(); box.add(Box.createHorizontalGlue()); box.add(runButton); add(new JScrollPane(area)); add(p, BorderLayout.NORTH); add(box, BorderLayout.SOUTH); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setPreferredSize(new Dimension(320, 240)); } private void executeWorker(ProgressMonitor monitor, int lengthOfTask, JButton button, JTextArea area) { SwingWorker<String, String> worker = new BackgroundTask(lengthOfTask) { @Override protected void process(List<String> chunks) { if (isCancelled()) { return; } if (!isDisplayable()) { System.out.println("process: DISPOSE_ON_CLOSE"); cancel(true); return; } for (String message: chunks) { monitor.setNote(message); } } @Override public void done() { if (!isDisplayable()) { System.out.println("done: DISPOSE_ON_CLOSE"); cancel(true); return; } button.setEnabled(true); monitor.close(); if (isCancelled()) { area.append("Cancelled\n"); } else { try { String text = get(); area.append(text + "\n"); } catch (InterruptedException ex) { area.append("Interrupted\n"); } catch (ExecutionException ex) { ex.printStackTrace(); area.append(String.format("Error: %s%n", ex.getMessage())); } } area.setCaretPosition(area.getDocument().getLength()); } }; worker.addPropertyChangeListener(new ProgressListener(monitor)); worker.execute(); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGui(); } }); } public static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class BackgroundTask extends SwingWorker<String, String> { private final int lengthOfTask; protected BackgroundTask(int lengthOfTask) { super(); this.lengthOfTask = lengthOfTask; } @Override public String doInBackground() { int current = 0; while (current < lengthOfTask && !isCancelled()) { if (current % 10 == 0) { try { Thread.sleep(5); } catch (InterruptedException ex) { return "Interrupted"; } } int v = 100 * current / lengthOfTask; setProgress(v); publish(String.format("%d%%", v)); current++; } return "Done"; } } class ProgressListener implements PropertyChangeListener { private final ProgressMonitor monitor; protected ProgressListener(ProgressMonitor monitor) { this.monitor = monitor; this.monitor.setProgress(0); } @Override public void propertyChange(PropertyChangeEvent e) { String strPropertyName = e.getPropertyName(); if ("progress".equals(strPropertyName)) { monitor.setProgress((Integer) e.getNewValue()); Object o = e.getSource(); if (o instanceof SwingWorker) { SwingWorker<?, ?> task = (SwingWorker<?, ?>) o; if (task.isDone() || monitor.isCanceled()) { task.cancel(true); } } } } }
/* * $Id: LockssTestCase.java,v 1.40 2003-11-07 00:50:11 troberts Exp $ */ package org.lockss.test; import java.util.*; import java.io.*; import java.net.*; import org.lockss.util.*; import org.lockss.daemon.Configuration; import org.lockss.daemon.ConfigManager; import junit.framework.TestCase; import junit.framework.TestResult; public class LockssTestCase extends TestCase { protected static Logger log = Logger.getLogger("LockssTest", Logger.getInitialDefaultLevel()); /** Timeout duration for timeouts that are expected to time out. Setting * this higher makes normal tests take longer, setting it too low might * cause failing tests to erroneously succeed on slow or busy * machines. */ public static int TIMEOUT_SHOULD = 300; /** Timeout duration for timeouts that are expected not to time out. * This should be set high to ensure catching failures. */ public static final int DEFAULT_TIMEOUT_SHOULDNT = 2000; public static int TIMEOUT_SHOULDNT = DEFAULT_TIMEOUT_SHOULDNT; List tmpDirs; List doLaters; public LockssTestCase(String msg) { this(); setName(msg); } public LockssTestCase() { super(); Integer timeout = Integer.getInteger("org.lockss.test.timeout.shouldnt"); if (timeout != null) { TIMEOUT_SHOULDNT = timeout.intValue(); } } /** * Create and return the name of a temp dir. The dir is created within * the default temp file dir. * It will be deleted following the test, by tearDown(). (So if you * override tearDown(), be sure to call <code>super.tearDown()</code>.) * @return The newly created directory * @throws IOException */ public File getTempDir() throws IOException { File tmpdir = FileTestUtil.createTempDir("locksstest", null); if (tmpdir != null) { if (tmpDirs == null) { tmpDirs = new LinkedList(); } tmpDirs.add(tmpdir); } return tmpdir; } /** Create a fresh config manager */ protected void setUp() throws Exception { super.setUp(); ConfigManager.makeConfigManager(); } /** * Remove any temp dirs, cancel any outstanding {@link LockssTestCase.DoLater}s * @throws Exception */ protected void tearDown() throws Exception { if (doLaters != null) { List copy = new ArrayList(doLaters); for (Iterator iter = copy.iterator(); iter.hasNext(); ) { DoLater doer = (DoLater)iter.next(); doer.cancel(); } // do NOT set doLaters to null here. It may be referenced by // exiting DoLaters. It won't hurt anything because the next test // will create a new instance of the test case, and get a different // doLaters list } // XXX this should be folded into LockssDaemon shutdown ConfigManager cfg = ConfigManager.getConfigManager(); if (cfg != null) { cfg.stopService(); } TimerQueue.stopTimerQueue(); // delete temp dirs boolean leave = Boolean.getBoolean("org.lockss.keepTempFiles"); if (tmpDirs != null && !leave) { for (ListIterator iter = tmpDirs.listIterator(); iter.hasNext(); ) { File dir = (File)iter.next(); if (FileTestUtil.delTree(dir)) { log.debug2("deltree(" + dir + ") = true"); iter.remove(); } else { log.debug2("deltree(" + dir + ") = false"); } } } super.tearDown(); if (Boolean.getBoolean("org.lockss.test.threadDump")) { DebugUtils.getInstance().threadDump(); TimerUtil.guaranteedSleep(1000); } } double successRate; int successMaxRepetitions; int successMaxFailures; /** Causes the current test case to be repeated if it fails, ultimately * succeeding if the success rate is sufficiently high. If a test is * repeated, a message will be written to System.err. Repetitions are * not reflected in test statistics. * @param rate the minimum success rate between 0 and 1 (successes / * attempts) necessary for the test ultimately to succeed. * @param maxRepetitions the maximum number of times the test will be * repeated in an attempt to achieve the specified success rate. * @see #successRateSetUp() * @see #successRateTearDown() */ protected void assertSuccessRate(double rate, int maxRepetitions) { if (successMaxFailures == 0) { successRate = rate; successMaxRepetitions = maxRepetitions; successMaxFailures = maxRepetitions - ((int)(rate * maxRepetitions)); } } /** * Runs the bare test sequence, repeating if necessary to achieve the * specified success rate. * @see #assertSuccessRate * @exception Throwable if any exception is thrown */ public void runBare() throws Throwable { int rpt = 0; int failures = 0; successRateSetUp(); try { while (true) { try { super.runBare(); } catch (Throwable e) { if (++failures > successMaxFailures) { rpt++; throw e; } } if (++rpt >= successMaxRepetitions) { break; } if ((((double)(rpt - failures)) / ((double)rpt)) > successRate) { break; } } } finally { if (successMaxFailures > 0 && failures > 0) { System.err.println(getName() + " failed " + failures + " of " + rpt + " tries, " + ((failures > successMaxFailures) ? "not " : "") + "achieving a " + successRate + " success rate."); } successRateTearDown(); } } /** Called once (before setUp()) before a set of repetitions of a test * case that uses assertSuccessRate(). (setUp() is called before each * repetition.) */ protected void successRateSetUp() { successMaxFailures = 0; } /** Called once (after tearDown()) after a set of repetitions of a test * case that uses assertSuccessRate(). (tearDown() is called after each * repetition.) */ protected void successRateTearDown() { } /** * Asserts that two Maps are equal (contain the same mappings). * If they are not an AssertionFailedError is thrown. * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ static public void assertEqual(String message, Map expected, Map actual) { if (expected == null && actual == null) { return; } if (expected != null && expected.equals(actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that two Maps are equal (contain the same mappings). * If they are not an AssertionFailedError is thrown. * @param expected the expected value * @param actual the actual value */ static public void assertEqual(Map expected, Map actual) { assertEqual(null, expected, actual); } /** * Asserts that two collections are isomorphic. If they are not * an AssertionFailedError is thrown. * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ static public void assertIsomorphic(String message, Collection expected, Collection actual) { if (CollectionUtil.isIsomorphic(expected, actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that two collections are isomorphic. If they are not * an AssertionFailedError is thrown. * @param expected the expected value * @param actual the actual value */ static public void assertIsomorphic(Collection expected, Collection actual) { assertIsomorphic(null, expected, actual); } /** * Asserts that the array is isomorphic with the collection. If not * an AssertionFailedError is thrown. * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ static public void assertIsomorphic(String message, Object expected[], Collection actual) { if (CollectionUtil.isIsomorphic(expected, actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that the array is isomorphic with the collection. If not * an AssertionFailedError is thrown. * @param expected the expected value * @param actual the actual value */ static public void assertIsomorphic(Object expected[], Collection actual) { assertIsomorphic(null, expected, actual); } /** * Asserts that the array is isomorphic with the collection behind the * iterator. If not an AssertionFailedError is thrown. * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ static public void assertIsomorphic(String message, Object expected[], Iterator actual) { if (CollectionUtil.isIsomorphic(new ArrayIterator(expected), actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that the array is isomorphic with the collection behind the * iterator. If not an AssertionFailedError is thrown. * @param expected the expected value * @param actual the actual value */ static public void assertIsomorphic(Object expected[], Iterator actual) { assertIsomorphic(null, expected, actual); } /** * Asserts that the two boolean arrays have equal contents * @param expected the expected value * @param actual the actual value */ public static void assertEquals(boolean[] expected, boolean[] actual) { assertEquals(null, expected, actual); } /** * Asserts that the two boolean arrays have equal contents * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ public static void assertEquals(String message, boolean[] expected, boolean[] actual) { if (Arrays.equals(expected, actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that the two byte arrays have equal contents * @param expected the expected value * @param actual the actual value */ public static void assertEquals(byte[] expected, byte[] actual) { assertEquals(null, expected, actual); } /** * Asserts that the two byte arrays have equal contents * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ public static void assertEquals(String message, byte[] expected, byte[] actual) { if (Arrays.equals(expected, actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that the two char arrays have equal contents * @param expected the expected value * @param actual the actual value */ public static void assertEquals(char[] expected, char[] actual) { assertEquals(null, expected, actual); } /** * Asserts that the two char arrays have equal contents * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ public static void assertEquals(String message, char[] expected, char[] actual) { if (Arrays.equals(expected, actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that the two double arrays have equal contents * @param expected the expected value * @param actual the actual value */ public static void assertEquals(double[] expected, double[] actual) { assertEquals(null, expected, actual); } /** * Asserts that the two double arrays have equal contents * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ public static void assertEquals(String message, double[] expected, double[] actual) { if (Arrays.equals(expected, actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that the two float arrays have equal contents * @param expected the expected value * @param actual the actual value */ public static void assertEquals(float[] expected, float[] actual) { assertEquals(null, expected, actual); } /** * Asserts that the two float arrays have equal contents * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ public static void assertEquals(String message, float[] expected, float[] actual) { if (Arrays.equals(expected, actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that the two int arrays have equal contents * @param expected the expected value * @param actual the actual value */ public static void assertEquals(int[] expected, int[] actual) { assertEquals(null, expected, actual); } /** * Asserts that the two int arrays have equal contents * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ public static void assertEquals(String message, int[] expected, int[] actual) { if (Arrays.equals(expected, actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that the two short arrays have equal contents * @param expected the expected value * @param actual the actual value */ public static void assertEquals(short[] expected, short[] actual) { assertEquals(null, expected, actual); } /** * Asserts that the two short arrays have equal contents * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ public static void assertEquals(String message, short[] expected, short[] actual) { if (Arrays.equals(expected, actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that the two long arrays have equal contents * @param expected the expected value * @param actual the actual value */ public static void assertEquals(long[] expected, long[] actual) { assertEquals(null, expected, actual); } /** * Asserts that the two long arrays have equal contents * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ public static void assertEquals(String message, long[] expected, long[] actual) { if (Arrays.equals(expected, actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that the two Object arrays have equal contents * @param expected the expected value * @param actual the actual value */ public static void assertEquals(Object[] expected, Object[] actual) { assertEquals(null, expected, actual); } /** * Asserts that the two Object arrays have equal contents * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ public static void assertEquals(String message, Object[] expected, Object[] actual) { if (Arrays.equals(expected, actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that two objects are not equal. If they are not * an AssertionFailedError is thrown with the given message. * @param message the message to give on failure * @param expected the expected value * @param actual the actual value */ public static void assertNotEquals(String message, Object expected, Object actual) { if ((expected == null && actual == null) || (expected != null && expected.equals(actual))) { failEquals(message, expected, actual); } } /** * Asserts that two objects are not equal. If they are not * an AssertionFailedError is thrown with the given message. * @param expected the expected value * @param actual the actual value */ public static void assertNotEquals(Object expected, Object actual) { assertNotEquals(null, expected, actual); } public static void assertNotEquals(long expected, long actual) { assertNotEquals(null, expected, actual); } public static void assertNotEquals(String message, long expected, long actual) { assertNotEquals(message, new Long(expected), new Long(actual)); } public static void assertNotEquals(int expected, int actual) { assertNotEquals(null, expected, actual); } public static void assertNotEquals(String message, int expected, int actual) { assertNotEquals(message, new Integer(expected), new Integer(actual)); } public static void assertNotEquals(short expected, short actual) { assertNotEquals(null, expected, actual); } public static void assertNotEquals(String message, short expected, short actual) { assertNotEquals(message, new Short(expected), new Short(actual)); } public static void assertNotEquals(byte expected, byte actual) { assertNotEquals(null, expected, actual); } public static void assertNotEquals(String message, byte expected, byte actual) { assertNotEquals(message, new Byte(expected), new Byte(actual)); } public static void assertNotEquals(char expected, char actual) { assertNotEquals(null, expected, actual); } public static void assertNotEquals(String message, char expected, char actual) { assertNotEquals(message, new Character(expected), new Character(actual)); } public static void assertNotEquals(boolean expected, boolean actual) { assertNotEquals(null, expected, actual); } public static void assertNotEquals(String message, boolean expected, boolean actual) { assertNotEquals(message, new Boolean(expected), new Boolean(actual)); } public static void assertNotEquals(double expected, double actual, double delta) { assertNotEquals(null, expected, actual, delta); } public static void assertNotEquals(String message, double expected, double actual, double delta) { // handle infinity specially since subtracting to infinite //values gives NaN and the the following test fails if (Double.isInfinite(expected)) { if (expected == actual){ failEquals(message, new Double(expected), new Double(actual)); } } else if ((Math.abs(expected-actual) <= delta)) { // Because comparison with NaN always returns false failEquals(message, new Double(expected), new Double(actual)); } } public static void assertNotEquals(float expected, float actual, float delta) { assertNotEquals(null, expected, actual, delta); } public static void assertNotEquals(String message, float expected, float actual, float delta) { // handle infinity specially since subtracting to infinite //values gives NaN and the the following test fails if (Double.isInfinite(expected)) { if (expected == actual){ failEquals(message, new Float(expected), new Float(actual)); } } else if ((Math.abs(expected-actual) <= delta)) { // Because comparison with NaN always returns false failEquals(message, new Float(expected), new Float(actual)); } } public static void assertEmpty(Collection coll) { assertEmpty(null, coll); } public static void assertEmpty(String message, Collection coll) { if (coll.size() > 0) { StringBuffer sb = new StringBuffer(); if (message != null) { sb.append(message); sb.append(" "); } sb.append("Expected empty Collection, but containted "); sb.append(coll); fail(sb.toString()); } } private static void failEquals(String message, Object expected, Object actual) { StringBuffer sb = new StringBuffer(); if (message != null) { sb.append(message); sb.append(" "); } sb.append("expected not equals, but both were "); sb.append(expected); fail(sb.toString()); } // tk do a better job of printing collections static private void failNotEquals(String message, Object expected, Object actual) { String formatted= ""; if (message != null) formatted= message+" "; fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); } static private void failNotEquals(String message, int[] expected, int[] actual) { String formatted= ""; if (message != null) formatted= message+" "; fail(formatted+"expected:<"+arrayString(expected)+ "> but was:<"+arrayString(actual)+">"); } static protected Object[] objArray(int[] a) { Object[] o = new Object[a.length]; for (int ix = 0; ix < a.length; ix++) { o[ix] = new Integer(a[ix]); } return o; } static protected String arrayString(int[] a) { return StringUtil.separatedString(objArray(a), ", "); } static private void failNotEquals(String message, long[] expected, long[] actual) { String formatted= ""; if (message != null) formatted= message+" "; fail(formatted+"expected:<"+arrayString(expected)+ "> but was:<"+arrayString(actual)+">"); } static protected Object[] objArray(long[] a) { Object[] o = new Object[a.length]; for (int ix = 0; ix < a.length; ix++) { o[ix] = new Long(a[ix]); } return o; } static protected String arrayString(long[] a) { return StringUtil.separatedString(objArray(a), ", "); } static private void failNotEquals(String message, byte[] expected, byte[] actual) { String formatted= ""; if (message != null) formatted= message+" "; fail(formatted+"expected:<"+ByteArray.toHexString(expected)+ "> but was:<"+ByteArray.toHexString(actual)+">"); // fail(formatted+"expected:<"+arrayString(expected)+ // "> but was:<"+arrayString(actual)+">"); } static protected Object[] objArray(byte[] a) { Object[] o = new Object[a.length]; for (int ix = 0; ix < a.length; ix++) { o[ix] = new Integer(a[ix]); } return o; } static protected String arrayString(byte[] a) { return StringUtil.separatedString(objArray(a), ", "); } static private void failNotEquals(String message, Object[] expected, Object actual) { failNotEquals(message, "[" + StringUtil.separatedString(expected, ", ") + "]", actual); } /** * Asserts that the two DatagramPackets have equal contents * @param expected the expected value * @param actual the actual value */ public static void assertEquals(DatagramPacket expected, DatagramPacket actual) { assertEquals(expected.getAddress(), actual.getAddress()); assertEquals(expected.getPort(), actual.getPort()); assertEquals(expected.getLength(), actual.getLength()); assertEquals(expected.getOffset(), actual.getOffset()); assertTrue(Arrays.equals(expected.getData(), actual.getData())); } /** * Asserts that two collections have all the same elements of the same * cardinality; tries to give useful output if it fails */ public static void assertSameElements(Collection expected, Collection actual) { assertTrue("Expected "+expected+" but was "+actual, org.apache.commons.collections. CollectionUtils.isEqualCollection(expected, actual)); } /** * Asserts that a string matches the content of a reader */ public static void assertReaderMatchesString(String expected, Reader reader) throws IOException{ StringBuffer actual = new StringBuffer(expected.length()); int kar; while ((kar = reader.read()) != -1) { actual.append((char)kar); } assertEquals(expected, actual.toString()); } /** Abstraction to do something in another thread, after a delay, * unless cancelled. If the sceduled activity is still pending when the * test completes, it is cancelled by tearDown(). * <br>For one-off use:<pre> * final Object obj = ...; * DoLater doer = new DoLater(1000) { * protected void doit() { * obj.method(...); * } * }; * doer.start();</pre> * * Or, for convenient repeated use of a particular delayed operation, * define a class that extends <code>DoLater</code>, * with a constructor that calls * <code>super(wait)</code> and stores any other necessary args into * instance vars, and a <code>doit()</code> method that does whatever needs * to be done. And a convenience method to create and start it. * For example, <code>Interrupter</code> is defined as:<pre> * public class Interrupter extends DoLater { * private Thread thread; * Interrupter(long waitMs, Thread thread) { * super(waitMs); * this.thread = thread; * } * * protected void doit() { * thread.interrupt(); * } * } * * public Interrupter interruptMeIn(long ms) { * Interrupter i = new Interrupter(ms, Thread.currentThread()); * i.start(); * return i; * }</pre> * * Then, to protect a test with a timeout:<pre> * Interrupter intr = null; * try { * intr = interruptMeIn(1000); * // perform a test that should complete in less than one second * intr.cancel(); * } finally { * if (intr.did()) { * fail("operation failed to complete in one second"); * } * }</pre> * The <code>cancel()</code> ensures that the interrupt will not * happen after the try block completes. (This is not necessary at the * end of a test case, as any pending interrupters will be cancelled * by tearDown.) */ protected abstract class DoLater extends Thread { private long wait; private boolean want = true; private boolean did = false; protected DoLater(long waitMs) { wait = waitMs; } /** Must override this to perform desired action */ protected abstract void doit(); /** * Return true iff action was taken * @returns true iff taken */ public boolean did() { return did; } /** Cancel the action iff it hasn't already started. If it has started, * wait until it completes. (Thus when <code>cancel()</code> returns, it * is safe to destroy any environment on which the action relies.) */ public synchronized void cancel() { if (want) { want = false; this.interrupt(); } } public final void run() { try { synchronized (LockssTestCase.this) { if (doLaters == null) { doLaters = Collections.synchronizedList(new LinkedList()); } } doLaters.add(this); if (wait != 0) { TimerUtil.sleep(wait); } synchronized (this) { if (want) { want = false; did = true; doit(); } } } catch (InterruptedException e) { // exit thread } finally { doLaters.remove(this); } } } /** Interrupter interrupts a thread in a while */ public class Interrupter extends DoLater { private Thread thread; private boolean threadDump = false; Interrupter(long waitMs, Thread thread) { super(waitMs); this.thread = thread; } /** Interrupt the thread */ protected void doit() { if (threadDump) { try { DebugUtils.getInstance().threadDump(); TimerUtil.guaranteedSleep(1000); } catch (Exception e) { } } thread.interrupt(); } /** Interrupt the thread */ public void setThreadDump() { threadDump = true; } } /** * Interrupt current thread in a while * @param ms interval to wait before interrupting * @return an Interrupter */ public Interrupter interruptMeIn(long ms) { Interrupter i = new Interrupter(ms, Thread.currentThread()); i.start(); return i; } /** * Interrupt current thread in a while, first printing a thread dump * @param ms interval to wait before interrupting * @param threadDump true if thread dump wanted * @return an Interrupter */ public Interrupter interruptMeIn(long ms, boolean threadDump) { Interrupter i = new Interrupter(ms, Thread.currentThread()); if (threadDump) { i.setThreadDump(); } i.start(); return i; } }
package org.intermine.web; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.Date; import java.util.Locale; import java.util.GregorianCalendar; import java.util.Map; import java.text.DateFormat; import java.text.ParseException; import org.apache.struts.Globals; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionError; import org.intermine.metadata.AttributeDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.Model; import org.intermine.util.TypeUtil; /** * The main form, using for editing constraints * @author Mark Woodbridge */ public class MainForm extends ActionForm { protected String constraintOp, constraintValue, path, subclass; /** * Gets the value of subclass * * @return the value of subclass */ public String getSubclass() { return subclass; } /** * Sets the value of subclass * * @param subclass Value to assign to subclass */ public void setSubclass(String subclass) { this.subclass = subclass; } /** * Gets the value of constraintOp * * @return the value of constraintOp */ public String getConstraintOp() { return constraintOp; } /** * Sets the value of constraintOp * * @param constraintOp Value to assign to constraintOp */ public void setConstraintOp(String constraintOp) { this.constraintOp = constraintOp; } /** * Gets the value of constraintValue * * @return the value of constraintValue */ public String getConstraintValue() { return constraintValue; } /** * Sets the value of constraintValue * * @param constraintValue Value to assign to constraintValue */ public void setConstraintValue(String constraintValue) { this.constraintValue = constraintValue; } /** * Gets the value of path * * @return the value of path */ public String getPath() { return path; } /** * Sets the value of path * * @param path Value to assign to path */ public void setPath(String path) { this.path = path; } /** * @see ActionForm#validate */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { HttpSession session = request.getSession(); ServletContext servletContext = session.getServletContext(); Model model = (Model) servletContext.getAttribute(Constants.MODEL); Locale locale = (Locale) session.getAttribute(Globals.LOCALE_KEY); ActionErrors errors = new ActionErrors(); FieldDescriptor fd = MainHelper.getFieldDescriptor(path, model); if (fd.isAttribute() && constraintValue != null) { AttributeDescriptor attr = (AttributeDescriptor) fd; Class fieldClass = TypeUtil.instantiate(attr.getType()); if (Date.class.equals(fieldClass)) { try { DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale).parse(constraintValue); } catch (ParseException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.date", constraintValue, new GregorianCalendar().getTime())); } } else { try { TypeUtil.stringToObject(fieldClass, constraintValue); } catch (NumberFormatException e) { String shortName = TypeUtil.unqualifiedName(fieldClass.getName()).toLowerCase(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors." + shortName, constraintValue)); } } } if (errors.size() > 0) { request.setAttribute("editingNode", ((Map) session.getAttribute(Constants.QUERY)).get(path)); } return errors; } /** * @see ActionForm#reset */ public void reset(ActionMapping mapping, HttpServletRequest request) { constraintOp = null; constraintValue = null; path = null; subclass = null; } }
package me.exphc.Writable; import java.util.Collections; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.UUID; import java.util.Iterator; import java.util.logging.Logger; import java.util.concurrent.ConcurrentHashMap; import java.io.*; import java.lang.Byte; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.*; import org.bukkit.event.*; import org.bukkit.event.block.*; import org.bukkit.event.player.*; import org.bukkit.Material.*; import org.bukkit.block.*; import org.bukkit.entity.*; import org.bukkit.command.*; import org.bukkit.inventory.*; import org.bukkit.configuration.*; import org.bukkit.configuration.file.*; import org.bukkit.scheduler.*; import org.bukkit.*; enum WritingState { NOT_WRITING, // initial state, timed out, or finished writing CLICKED_PAPER, // onPlayerInteract(), when right-click paper PLACED_SIGN, // onBlockPlace(), when placed temporary sign // onSignChange(), after wrote sign } class WritableSignPlaceTimeoutTask implements Runnable { static public ConcurrentHashMap<Player, Integer> taskIDs = new ConcurrentHashMap<Player, Integer>(); static Logger log = Logger.getLogger("Minecraft"); Player player; public WritableSignPlaceTimeoutTask(Player p) { player = p; } public void run() { if (Writable.getWritingState(player) != WritingState.PLACED_SIGN) { log.info("did not place sign in time"); WritablePlayerListener.restoreSavedItem(player); Writable.setWritingState(player, WritingState.NOT_WRITING); } WritableSignPlaceTimeoutTask.taskIDs.remove(player); } } class WritablePlayerListener extends PlayerListener { Logger log = Logger.getLogger("Minecraft"); Plugin plugin; static private ConcurrentHashMap<Player, ItemStack> savedItemStack = new ConcurrentHashMap<Player, ItemStack>(); static private ConcurrentHashMap<Player, Integer> savedItemSlot = new ConcurrentHashMap<Player, Integer>(); public WritablePlayerListener(Plugin pl) { plugin = pl; } public void onPlayerInteract(PlayerInteractEvent event) { Block block = event.getClickedBlock(); ItemStack item = event.getItem(); Player player = event.getPlayer(); Action action = event.getAction(); if (item != null && item.getType() == Material.PAPER && action == Action.RIGHT_CLICK_BLOCK) { if (Writable.getWritingState(player) != WritingState.NOT_WRITING) { player.sendMessage("You are already writing"); // TODO: stop other writing, restore (like timeout), cancel task? return; } // TODO: prevent writing on >1 stacks? or try to shuffle around? // TODO: check block to ensure is realistically hard surface to write on (stone, not gravel or sand, etc.) // TODO: check if have writing implement (ink sac), if so use up // If blank, assign new ID short id = item.getDurability(); if (id == 0) { id = Writable.nextPaperID(); // TODO: choose next! item.setDurability(id); } log.info("This is book // Save off old item in hand to restore savedItemStack.put(player, item); savedItemSlot.put(player, player.getInventory().getHeldItemSlot()); // Quickly change to sign, so double right-click paper = place sign to write on player.setItemInHand(new ItemStack(Material.SIGN, 1)); // TODO: if have >1, save off old paper? Writable.setWritingState(player, WritingState.CLICKED_PAPER); // Timeout to NOT_WRITING if our sign isn't used in a sufficient time WritableSignPlaceTimeoutTask task = new WritableSignPlaceTimeoutTask(player); int taskID = Bukkit.getScheduler().scheduleAsyncDelayedTask(plugin, task, plugin.getConfig().getLong("signTimeout", 2*20)); // Save task to cancel if did in fact make it to PLACED_SIGN in time WritableSignPlaceTimeoutTask.taskIDs.put(player, taskID); } } // Restore previous item held by player, before started writing (do not use setItemInHand()) // Returns items restored static public ItemStack restoreSavedItem(Player player) { ItemStack items = savedItemStack.get(player); int slot = savedItemSlot.get(player); player.getInventory().setItem(slot, items); savedItemStack.remove(player); savedItemSlot.remove(player); return items; } static public void readPaperToPlayer(Player player, int id) { ArrayList<String> lines = Writable.readPaper(id); player.sendMessage(lines + ""); // TODO: page through, view } // When change to in inventory slot, read back public void onItemHeldChange(PlayerItemHeldEvent event) { Player player = event.getPlayer(); ItemStack item = player.getInventory().getItem(event.getNewSlot()); if (item != null && item.getType() == Material.PAPER) { int id = item.getDurability(); // TODO: only if not zero readPaperToPlayer(player, id); } } // If pickup a paper with writing on it, let know public void onPlayerPickupItem(PlayerPickupItemEvent event) { ItemStack item = event.getItem().getItemStack(); if (item != null && item.getType() == Material.PAPER) { if (item.getDurability() != 0) { event.getPlayer().sendMessage("You picked up paper, mysteriously scribbled"); } } } } class WritableBlockListener extends BlockListener { Logger log = Logger.getLogger("Minecraft"); Plugin plugin; public WritableBlockListener(Plugin pl) { plugin = pl; } public void onBlockPlace(BlockPlaceEvent event) { Block block = event.getBlock(); Player player = event.getPlayer(); if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) { WritingState state = Writable.getWritingState(player); // Did they get this sign from right-clicking paper? if (state == WritingState.CLICKED_PAPER) { // We made it, stop timeout task (so won't revert to NOT_WRITING and take back sign) int taskID = WritableSignPlaceTimeoutTask.taskIDs.get(player); WritableSignPlaceTimeoutTask.taskIDs.remove(player); Bukkit.getScheduler().cancelTask(taskID); Writable.setWritingState(player, WritingState.PLACED_SIGN); // TODO: store paper ID } else { log.info("Place non-paper sign"); } } } public void onSignChange(SignChangeEvent event) { Block block = event.getBlock(); Player player = event.getPlayer(); String[] lines = event.getLines(); WritingState state = Writable.getWritingState(player); if (state != WritingState.PLACED_SIGN) { log.info("Changing sign not from paper"); return; } // This sign text came from a sign from clicking paper // Destroy sign block.setType(Material.AIR); // Restore previous item ItemStack paperItem = WritablePlayerListener.restoreSavedItem(player); // Write int id = paperItem.getDurability(); Writable.writePaper(id, lines); // Finish up Writable.setWritingState(player, WritingState.NOT_WRITING); WritablePlayerListener.readPaperToPlayer(player, id); } } public class Writable extends JavaPlugin { static Logger log = Logger.getLogger("Minecraft"); WritablePlayerListener playerListener; WritableBlockListener blockListener; static private ConcurrentHashMap<Player, WritingState> writingState; static private ConcurrentHashMap<Integer, ArrayList<String>> paperTexts; // TODO: paper class? public void onEnable() { writingState = new ConcurrentHashMap<Player, WritingState>(); loadConfig(); // TODO: load from disk paperTexts = new ConcurrentHashMap<Integer, ArrayList<String>>(); playerListener = new WritablePlayerListener(this); blockListener = new WritableBlockListener(this); Bukkit.getPluginManager().registerEvent(Event.Type.PLAYER_INTERACT, playerListener, org.bukkit.event.Event.Priority.Normal, this); Bukkit.getPluginManager().registerEvent(Event.Type.PLAYER_ITEM_HELD, playerListener, org.bukkit.event.Event.Priority.Normal, this); Bukkit.getPluginManager().registerEvent(Event.Type.PLAYER_PICKUP_ITEM, playerListener, org.bukkit.event.Event.Priority.Normal, this); Bukkit.getPluginManager().registerEvent(Event.Type.SIGN_CHANGE, blockListener, org.bukkit.event.Event.Priority.Normal, this); Bukkit.getPluginManager().registerEvent(Event.Type.BLOCK_PLACE, blockListener, org.bukkit.event.Event.Priority.Normal, this); configurePaperStacking(); log.info("Writable enabled"); } static List<Material> writingImplementMaterials; static List<Material> writingSurfaceMaterials; private void loadConfig() { List<String> implementsStrings = getConfig().getStringList("writingImplements"); writingImplementMaterials = new ArrayList<Material>(); for (String implementString: implementsStrings) { Material implementMaterial = Material.matchMaterial(implementString); if (implementMaterial == null) { log.info("Invalid implement material: " + implementString); // TODO: error continue; } writingImplementMaterials.add(implementMaterial); } List<String> surfacesStrings = getConfig().getStringList("writingSurfaces"); writingSurfaceMaterials = new ArrayList<Material>(); for (String surfaceString: surfacesStrings) { Material surfaceMaterial = Material.matchMaterial(surfaceString); if (surfaceMaterial == null) { log.info("Invalid surface material: " + surfaceString); // TODO: error; continue; } writingSurfaceMaterials.add(surfaceMaterial); } log.info("writingImplementMaterials="+writingImplementMaterials); log.info("writingSurfaceMaterials="+writingSurfaceMaterials); /* log.info("inks="+ getConfig().getValues(true)); //Map<String,Object> inksStrings = getConfig().get("inks").map; //Map<String,Object> inksStrings = getConfig().getConfigurationSection("inks").getValues(true); Iterator it = inksStrings.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); String inkString = (String)pair.getKey(); String colorString = (String)pair.getValue(); log.info("ink "+inkString+" = "+colorString); } */ } // Try to make paper stack by damage ID, or otherwise stack by one private void configurePaperStacking() { try { boolean ok = false; // attempt to make papers with different data values stack separately try { // obfuscated method name, check BookWorm for updates String methodName = getConfig().getString("stack-by-data-fn", "a"); Method method = net.minecraft.server.Item.class.getDeclaredMethod(methodName, boolean.class); if (method.getReturnType() == net.minecraft.server.Item.class) { method.setAccessible(true); method.invoke(net.minecraft.server.Item.PAPER, true); ok = true; } } catch (Exception e) { log.info("Not stacking papers together"); } if (!ok) { // otherwise limit stack size to 1 Field field = net.minecraft.server.Item.class.getDeclaredField("maxStackSize"); field.setAccessible(true); field.setInt(net.minecraft.server.Item.PAPER, 1); } else { log.info("Successfully changed paper stacking"); } } catch (Exception e) { e.printStackTrace(); } } public void onDisable() { // TODO: save paperTexts to disk log.info("Writable disabled"); } // Manipulate state machine static public void setWritingState(Player player, WritingState newState) { WritingState oldState = getWritingState(player); log.info("State change "+player.getName()+": "+oldState+" -> "+newState); if (newState == WritingState.NOT_WRITING) { writingState.remove(player); } else { writingState.put(player, newState); } } static public WritingState getWritingState(Player player) { WritingState state = writingState.get(player); return state == null ? WritingState.NOT_WRITING : state; } // Manipulate paper text static public void writePaper(int id, String[] newLines) { ArrayList<String> lines = readPaper(id); // Add non-empty lines for (int i = 0; i < newLines.length; i += 1) { String line = newLines[i]; if (line == null || line.equals("")) { // TODO: don't skip unless is last lines! // sometimes want to retain spacing, add whitespace.. // foo\n\n\n -> foo // foo\nbar -> foo\nbar // \n\nfoo -> \n\nfoo continue; } lines.add(line); } paperTexts.put(new Integer(id), lines); // TODO: save to disk now? } static public ArrayList<String> readPaper(int id) { ArrayList<String> lines = paperTexts.get(id); if (lines == null) { return new ArrayList<String>(); // empty array } else { return lines; } } static short nextPaperID() { // TODO: get next! return 1; } }
package org.jenetics.util; import static java.util.function.Predicates.isNull; import java.util.Iterator; import java.util.List; import java.util.RandomAccess; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; public interface Seq<T> extends Iterable<T> { /** * Return the value at the given {@code index}. * * @param index index of the element to return. * @return the value at the given {@code index}. * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < 0 || index >= size())}. */ public T get(final int index); /** * Return the length of this sequence. Once the sequence is created, the * length can't be changed. * * @return the length of this sequence. */ public int length(); /** * @see #length() */ public default int size() { return length(); } /** * Return an iterator with the new type {@code B}. * * @param <B> the component type of the returned type. * @param mapper the converter for converting from {@code T} to {@code B}. * @return the iterator of the converted type. * @throws NullPointerException if the given {@code converter} is {@code null}. */ public <B> Iterator<B> iterator( final Function<? super T, ? extends B> mapper ); /** * Applies a {@code function} to all elements of this sequence. * * @param consumer the code to apply to the elements. * @throws NullPointerException if the given {@code function} is * {@code null}. */ public default void foreach(final Consumer<? super T> consumer) { if (this instanceof RandomAccess) { for (int i = 0, n = length(); i < n; ++i) { consumer.accept(get(i)); } } else { for (final T value : this) { consumer.accept(value); } } } /** * Tests whether a predicate holds for all elements of this sequence. * * @param predicate the predicate to use to test the elements. * @return {@code true} if the given predicate p holds for all elements of * this sequence, {@code false} otherwise. * @throws NullPointerException if the given {@code predicate} is * {@code null}. */ public default boolean forall(final Predicate<? super T> predicate) { boolean valid = true; if (this instanceof RandomAccess) { for (int i = 0, n = length(); i < n && valid; ++i) { valid = predicate.test(get(i)); } return valid; } else { final Iterator<T> it = iterator(); while (it.hasNext() && valid) { valid = predicate.test(it.next()); } } return valid; } /** * Returns {@code true} if this sequence contains the specified element. * * @param element element whose presence in this sequence is to be tested. * The tested element can be {@code null}. * @return {@code true} if this sequence contains the specified element */ public default boolean contains(final Object element) { return indexOf(element) != -1; } /** * Returns the index of the first occurrence of the specified element * in this sequence, or -1 if this sequence does not contain the element. * * @param element element to search for, can be {@code null} * @return the index of the first occurrence of the specified element in * this sequence, or -1 if this sequence does not contain the element */ public default int indexOf(final Object element) { int index = -1; if (element == null) { index = indexWhere(isNull()); } else { index = indexWhere(o -> element.equals(o)); } return index; } /** * <p> * Returns the index of the first element on which the given predicate * returns {@code true}, or -1 if the predicate returns false for every * sequence element. * </p> * [code] * // Finding index of first null value. * final int index = seq.indexOf(new Predicates.Nil()); * * // Assert of no null values. * assert (sequence.indexOf(new Predicates.Nil()) == -1); * [/code] * * @param predicate the search predicate. * @return the index of the first element on which the given predicate * returns {@code true}, or -1 if the predicate returns {@code false} * for every sequence element. * @throws NullPointerException if the given {@code predicate} is {@code null}. */ public int indexWhere(final Predicate<? super T> predicate); /** * Returns the index of the last occurrence of the specified element * in this sequence, or -1 if this sequence does not contain the element. * * @param element element to search for, can be {@code null} * @return the index of the last occurrence of the specified element in * this sequence, or -1 if this sequence does not contain the element */ public default int lastIndexOf(final Object element) { int index = -1; if (element == null) { index = lastIndexWhere(isNull()); } else { index = lastIndexWhere(o -> element.equals(o)); } return index; } /** * Returns the index of the last element on which the given predicate * returns {@code true}, or -1 if the predicate returns false for every * sequence element. * * @param predicate the search predicate. * @return the index of the last element on which the given predicate * returns {@code true}, or -1 if the predicate returns false for * every sequence element. * @throws NullPointerException if the given {@code predicate} is {@code null}. */ public int lastIndexWhere(final Predicate<? super T> predicate); /** * Returns a fixed-size list backed by the specified sequence. (Changes to * the returned list "write through" to the array.) The returned list is * fixed size, serializable and implements {@link RandomAccess}. * * @return a list view of this sequence */ public List<T> asList(); /** * Builds a new sequence by applying a function to all elements of this * sequence. * * @param <B> the element type of the returned collection. * @param mapper the function to apply to each element. * @return a new sequence of type That resulting from applying the given * function f to each element of this sequence and collecting the * results. * @throws NullPointerException if the element {@code mapper} is * {@code null}. */ public <B> Seq<B> map(final Function<? super T, ? extends B> mapper); /** * Return an array containing all of the elements in this sequence in right * order. The returned array will be "safe" in that no references to it * are maintained by this sequence. (In other words, this method must allocate * a new array.) The caller is thus free to modify the returned array. * * @see java.util.Collection#toArray() * * @return an array containing all of the elements in this list in right * order */ public Object[] toArray(); /** * Return an array containing all of the elements in this sequence in right * order; the runtime type of the returned array is that of the specified * array. If this sequence fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the specified * array and the length of this array. * <p/> * If this sequence fits in the specified array with room to spare (i.e., the * array has more elements than this array), the element in the array * immediately following the end of this array is set to null. (This is * useful in determining the length of the array only if the caller knows * that the list does not contain any null elements.) * * @see java.util.Collection#toArray(Object[]) * * @param array the array into which the elements of this array are to be * stored, if it is big enough; otherwise, a new array of the same * runtime type is allocated for this purpose. * @return an array containing the elements of this array * @throws ArrayStoreException if the runtime type of the specified array is * not a super type of the runtime type of every element in this array * @throws NullPointerException if the given array is {@code null}. */ public T[] toArray(final T[] array); public Seq<T> subSeq(final int start); public Seq<T> subSeq(final int start, final int end); /** * Returns the hash code value for this sequence. The hash code is defined * as followed: * * [code] * int hashCode = 1; * final Iterator<E> it = seq.iterator(); * while (it.hasNext()) { * final E obj = it.next(); * hashCode = 31*hashCode + (obj == null ? 0 : obj.hashCode()); * } * [/code] * * @see List#hashCode() * * @return the hash code value for this list */ @Override public int hashCode(); /* { int hash = 1; for (Object element : this) { hash = 31*hash + (element == null ? 0: element.hashCode()); } return hash; } */ /** * Compares the specified object with this sequence for equality. Returns * true if and only if the specified object is also a sequence, both * sequence have the same size, and all corresponding pairs of elements in * the two sequences are equal. (Two elements e1 and e2 are equal if * (e1==null ? e2==null : e1.equals(e2)).) This definition ensures that the * equals method works properly across different implementations of the Seq * interface. * * @see List#equals(Object) * * @param object the object to be compared for equality with this sequence. * @return {@code true} if the specified object is equal to this sequence, * {@code false} otherwise. */ @Override public boolean equals(final Object object); /* { if (object == this) { return true; } if (!(object instanceof Seq<?>)) { return false; } final Seq<?> other = (Seq<?>)object; boolean equals = (length() == other.length()); for (int i = length(); equals && --i >= 0;) { final Object element = get(i); if (element != null) { equals = element.equals(other.get(i)); } else { equals = other.get(i) == null; } } return equals; } */ /** * Create a string representation of the given sequence. * * @param prefix the prefix of the string representation; e.g {@code '['}. * @param separator the separator of the array elements; e.g. {@code ','}. * @param suffix the suffix of the string representation; e.g. {@code ']'}. * @return the string representation of this sequence. */ public String toString( final String prefix, final String separator, final String suffix ); /** * Create a string representation of the given sequence. * * @param separator the separator of the array elements; e.g. {@code ','}. * @return the string representation of this sequence. */ public String toString(final String separator); }
package net.jsunit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import net.jsunit.configuration.Configuration; import net.jsunit.configuration.ConfigurationSource; import net.jsunit.configuration.DelegatingConfigurationSource; import net.jsunit.model.FarmTestRunResult; import net.jsunit.utility.XmlUtility; import org.mortbay.util.MultiException; import java.net.BindException; import java.net.URL; import java.util.List; public class DistributedTest extends TestCase { protected DistributedTestRunManager manager; private JsUnitStandardServer server; public DistributedTest(ConfigurationSource serverSource, ConfigurationSource farmSource) { super(farmSource.remoteMachineURLs()); server = new JsUnitStandardServer(new Configuration(serverSource)); manager = new DistributedTestRunManager(server.getStatusLogger(), new Configuration(farmSource)); } public void setUp() throws Exception { super.setUp(); startServerIfNecessary(); } private void startServerIfNecessary() throws Exception { try { server.start(); } catch (MultiException e) { if (!isMultiExceptionASingleBindException(e)) throw e; //if a server is already running, fine - we only need it to server content to remote machines } } private boolean isMultiExceptionASingleBindException(MultiException e) { List exceptions = e.getExceptions(); return exceptions.size() == 1 && exceptions.get(0) instanceof BindException; } public void tearDown() throws Exception { if (server != null && server.isAlive()) server.dispose(); super.tearDown(); } public static Test suite() { TestSuite suite = new TestSuite(); ConfigurationSource originalSource = Configuration.resolveSource(); Configuration configuration = new Configuration(originalSource); for (final URL remoteMachineURL : configuration.getRemoteMachineURLs()) suite.addTest(new DistributedTest( originalSource, new DelegatingConfigurationSource(originalSource) { public String remoteMachineURLs() { return remoteMachineURL.toString(); } })); return suite; } protected void runTest() throws Throwable { manager.runTests(); FarmTestRunResult result = manager.getFarmTestRunResult(); if (!result.wasSuccessful()) { StringBuffer buffer = new StringBuffer(); buffer.append(result.displayString()); buffer.append("\n"); String xml = XmlUtility.asPrettyString(result.asXml()); buffer.append(xml); fail(buffer.toString()); } } public DistributedTestRunManager getDistributedTestRunManager() { return manager; } }
package org.nuxeo.ecm.platform.relations.io.test; import java.io.Serializable; import java.util.Map; import org.nuxeo.ecm.core.api.DocumentException; import org.nuxeo.ecm.core.model.Repository; import org.nuxeo.ecm.core.model.Session; import org.nuxeo.ecm.core.schema.SchemaManager; import org.nuxeo.ecm.core.security.SecurityManager; /** * @author <a href="mailto:at@nuxeo.com">Anahide Tchertchian</a> * */ public class FakeRepository implements Repository { public String getName() { return "demo"; } public SecurityManager getNuxeoSecurityManager() { return new FakeSecurityManager(); } public Session getSession(Map<String, Serializable> context) throws DocumentException { return FakeSession.getSession(); } public int getActiveSessionsCount() { return 0; } public int getClosedSessionsCount() { return 0; } public Session[] getOpenedSessions() throws DocumentException { return null; } public int getStartedSessionsCount() { return 0; } public SchemaManager getTypeManager() { return null; } public void initialize() throws DocumentException { } public void shutdown() { } public boolean supportsTags() { return false; } }
package uk.org.opentrv.test.ETV; import static org.junit.Assume.assumeNotNull; import static org.junit.Assume.assumeTrue; import java.io.File; import java.io.IOException; import org.junit.Test; import uk.org.opentrv.ETV.driver.ETVSimpleDriverNBulkInputs; public class ETVDriverTest { public static final String fixedDataSetDir = "ETV-prepared-data"; public static final String fixedDataSetOutDir = "ETV-prepared-data-out"; /**Test for robust driver behaviour on fixed data set if any. * Will not run if input data directory is missing. * Will fail for other errors. */ @Test public void testWithExternalDataSet() throws IOException { final String homeDir = System.getProperty("user.home"); assumeNotNull(null != homeDir); final File inDir = new File(new File(homeDir), fixedDataSetDir); assumeTrue(inDir.isDirectory()); final File outDir = new File(new File(homeDir), fixedDataSetOutDir); // ETVSimpleDriverNBulkInputs.doComputation(inDir, outDir); // TODO } }
package com.opengamma.analytics.financial.instrument.volatilityswap; import org.apache.commons.lang.ObjectUtils; import org.threeten.bp.ZonedDateTime; import com.opengamma.analytics.financial.instrument.InstrumentDefinitionVisitor; import com.opengamma.analytics.financial.interestrate.InstrumentDerivative; import com.opengamma.analytics.financial.volatilityswap.FXVolatilitySwap; import com.opengamma.analytics.util.time.TimeCalculator; import com.opengamma.financial.convention.calendar.Calendar; import com.opengamma.financial.convention.daycount.DayCountFactory; import com.opengamma.financial.convention.frequency.PeriodFrequency; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; public class FXVolatilitySwapDefinition extends VolatilitySwapDefinition { /** * The base currency. */ private final Currency _baseCurrency; /** * The counter currency. */ private final Currency _counterCurrency; /** * @param currency The currency, not null * @param baseCurrency The base currency, not null * @param counterCurrency The counter currency, not null * @param volStrike The volatility strike, not negative * @param volNotional The volatility notional * @param observationStartDate The observation start date, not null * @param observationEndDate The observation end date, not null * @param effectiveDate The effective date, not null * @param maturityDate The maturity date, not null * @param observationFrequency The observation frequency, not null * @param annualizationFactor The annualization factor, greater than zero * @param calendar The holiday calendar, not null */ public FXVolatilitySwapDefinition(final Currency currency, final Currency baseCurrency, final Currency counterCurrency, final double volStrike, final double volNotional, final ZonedDateTime observationStartDate, final ZonedDateTime observationEndDate, final ZonedDateTime effectiveDate, final ZonedDateTime maturityDate, final PeriodFrequency observationFrequency, final double annualizationFactor, final Calendar calendar) { super(currency, volStrike, volNotional, observationStartDate, observationEndDate, effectiveDate, maturityDate, observationFrequency, annualizationFactor, calendar); ArgumentChecker.notNull(baseCurrency, "baseCurrency"); ArgumentChecker.notNull(counterCurrency, "counterCurrency"); ArgumentChecker.isFalse(baseCurrency.equals(counterCurrency), "base currency and counter currency cannot be equal"); _baseCurrency = baseCurrency; _counterCurrency = counterCurrency; } /** * Gets the base currency. * @return the base currency */ public Currency getBaseCurrency() { return _baseCurrency; } /** * Gets the counter currency. * @return the counter currency */ public Currency getCounterCurrency() { return _counterCurrency; } @Override public <V> V accept(final InstrumentDefinitionVisitor<?, V> visitor) { ArgumentChecker.notNull(visitor, "visitor"); return visitor.visitFXVolatilitySwapDefinition(this); } /** * {@inheritDoc} * @deprecated Yield curve names are no longer stored in {@link InstrumentDerivative} */ @Deprecated @Override public FXVolatilitySwap toDerivative(final ZonedDateTime date, final String... yieldCurveNames) { return toDerivative(date); } @Override public FXVolatilitySwap toDerivative(final ZonedDateTime date) { ArgumentChecker.notNull(date, "date"); final double timeToObservationStart = TimeCalculator.getTimeBetween(date, getObservationStartDate(), DayCountFactory.of("Business/252"), getCalendar()); final double timeToObservationEnd = TimeCalculator.getTimeBetween(date, getObservationEndDate(), DayCountFactory.of("Business/252"), getCalendar()); final double timeToMaturity = TimeCalculator.getTimeBetween(date, getMaturityDate(), DayCountFactory.of("Business/252"), getCalendar()); return new FXVolatilitySwap(timeToObservationStart, timeToObservationEnd, getObservationFrequency(), timeToMaturity, getVolatilityStrike(), getVolatilityNotional(), getCurrency(), _baseCurrency, _counterCurrency, getAnnualizationFactor()); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + _baseCurrency.hashCode(); result = prime * result + _counterCurrency.hashCode(); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof FXVolatilitySwapDefinition)) { return false; } final FXVolatilitySwapDefinition other = (FXVolatilitySwapDefinition) obj; if (!ObjectUtils.equals(_baseCurrency, other._baseCurrency)) { return false; } if (!ObjectUtils.equals(_counterCurrency, other._counterCurrency)) { return false; } return true; } }
/* * $Log: Wsdl.java,v $ * Revision 1.30 2013-01-24 17:31:35 m00f069 * Determine ESB SOAP type based on input EsbSoapValidator instead of input or output EsbSoapWrapperPipe * * Revision 1.29 2013/01/24 16:49:54 Jaco de Groot <jaco.de.groot@ibissource.org> * Removed header message. Added header part to request and response message. * Cleaned code a little. * * Revision 1.28 2012/12/06 15:19:28 Jaco de Groot <jaco.de.groot@ibissource.org> * Resolved warnings which showed up when using addNamespaceToSchema (src-include.2.1: The targetNamespace of the referenced schema..., src-resolve.4.2: Error resolving component...) * Handle includes in XSD's properly when generating a WSDL * Removed XSD download (unused and XSD's were not adjusted according to e.g. addNamespaceToSchema) * Sort schema's in WSDL (made sure the order is always the same) * Indent WSDL with tabs instead of spaces * Some cleaning and refactoring (made WSDL generator and XmlValidator share code) * * Revision 1.27 2012/11/21 14:11:00 Jaco de Groot <jaco.de.groot@ibissource.org> * Bugfix: Get root tags from root xsd's only otherwise when root tag name found in non root xsd, the non root xsd may be used which has no prefix, hence an exception is thrown. * * Revision 1.26 2012/10/26 15:43:18 Jaco de Groot <jaco.de.groot@ibissource.org> * Made WSDL without separate XSD's the default * * Revision 1.25 2012/10/24 14:34:00 Jaco de Groot <jaco.de.groot@ibissource.org> * Load imported XSD's into the WSDL too * When more than one XSD with the same namespace is present merge them into one schema element in the WSDL * Exclude SOAP Envelope XSD * * Revision 1.24 2012/10/19 11:52:28 Jaco de Groot <jaco.de.groot@ibissource.org> * Removed unused param * * Revision 1.23 2012/10/17 13:02:10 Jaco de Groot <jaco.de.groot@ibissource.org> * Check paradigm against list of valid values. * Use schemaLocation instead of outputWrapper as main source for ESB SOAP vars. * * Revision 1.22 2012/10/17 08:40:49 Jaco de Groot <jaco.de.groot@ibissource.org> * Added esbSoapOperationName and esbSoapOperationVersion * * Revision 1.21 2012/10/12 13:07:47 Jaco de Groot <jaco.de.groot@ibissource.org> * Removed "Unrecognized listener" comment from WSDL (when no useful listener found WSDL is marked abstract) * * Revision 1.20 2012/10/12 09:55:17 Jaco de Groot <jaco.de.groot@ibissource.org> * Some extra checks on configuration at WSDL listing time to prevent the user from being disappointed at WSDL generation time. * Handle retrieval of XSD's from outputValidator the same as for inputValidator (check on usage of schema instead of schemaLocation attribute and usage of recursiveXsds) * * Revision 1.19 2012/10/11 10:01:58 Jaco de Groot <jaco.de.groot@ibissource.org> * Use concrete filename with WebServiceListener too * * Revision 1.18 2012/10/11 09:45:58 Jaco de Groot <jaco.de.groot@ibissource.org> * Added WSDL filename to WSDL documentation * * Revision 1.17 2012/10/11 09:10:43 Jaco de Groot <jaco.de.groot@ibissource.org> * To lower case on targetAddress destination (QUEUE -> queue) * * Revision 1.16 2012/10/10 09:43:53 Jaco de Groot <jaco.de.groot@ibissource.org> * Added comment on ESB_SOAP_JMS * * Revision 1.15 2012/10/04 11:28:57 Jaco de Groot <jaco.de.groot@ibissource.org> * Fixed ESB Soap namespace * Added location (url) of WSDL generation to the WSDL documentation * Show warning add the bottom of the WSDL (if any) instead of Ibis logging * * Revision 1.14 2012/10/03 14:30:46 Jaco de Groot <jaco.de.groot@ibissource.org> * Different filename for ESB Soap WSDL * * Revision 1.13 2012/10/03 12:22:41 Jaco de Groot <jaco.de.groot@ibissource.org> * Different transport uri, jndi properties and connectionFactory for ESB Soap. * Fill targetAddress with a value when running locally. * * Revision 1.12 2012/10/02 16:12:14 Jaco de Groot <jaco.de.groot@ibissource.org> * Bugfix for one-way WSDL (switched esbSoapOperationName and esbSoapOperationVersion). * Log a warning in case paradigm could not be extracted from the soap body. * * Revision 1.11 2012/10/01 15:23:44 Jaco de Groot <jaco.de.groot@ibissource.org> * Strip schemaLocation from xsd import in case of generated WSDL with inline XSD's. * * Revision 1.10 2012/09/28 14:39:47 Jaco de Groot <jaco.de.groot@ibissource.org> * Bugfix WSLD target namespace for ESB Soap, part XSD should be WSDL * * Revision 1.9 2012/09/27 14:28:59 Jaco de Groot <jaco.de.groot@ibissource.org> * Better error message / adapter name when constructor throws exception. * * Revision 1.8 2012/09/27 13:44:31 Jaco de Groot <jaco.de.groot@ibissource.org> * Updates in generating wsdl namespace, wsdl input message name, wsdl output message name, wsdl port type name and wsdl operation name in case of EsbSoap * * Revision 1.7 2012/09/26 12:41:05 Jaco de Groot <jaco.de.groot@ibissource.org> * Bugfix in WSDL generator: Wrong prefix being used in element attribute of PipeLineInput and PipeLineOutput message part when using EsbSoapValidator. * * Revision 1.6 2012/08/23 11:57:43 Jaco de Groot <jaco.de.groot@ibissource.org> * Updates from Michiel * * Revision 1.5 2012/05/08 15:53:59 Jaco de Groot <jaco.de.groot@ibissource.org> * Fix invalid chars in wsdl:service name. * * Revision 1.4 2012/03/30 17:03:45 Jaco de Groot <jaco.de.groot@ibissource.org> * Michiel added JMS binding/service to WSDL generator, made WSDL validator work for Bis WSDL and made console show syntax problems for schema's used in XmlValidator * * Revision 1.3 2012/03/16 15:35:43 Jaco de Groot <jaco.de.groot@ibissource.org> * Michiel added EsbSoapValidator and WsdlXmlValidator, made WSDL's available for all adapters and did a bugfix on XML Validator where it seems to be dependent on the order of specified XSD's * * Revision 1.2 2011/12/15 10:08:06 Jaco de Groot <jaco.de.groot@ibissource.org> * Added CVS log * */ package nl.nn.adapterframework.soap; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.naming.NamingException; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import nl.nn.adapterframework.core.IListener; import nl.nn.adapterframework.core.IPipe; import nl.nn.adapterframework.core.PipeLine; import nl.nn.adapterframework.extensions.esb.EsbSoapValidator; import nl.nn.adapterframework.extensions.esb.EsbSoapWrapperPipe; import nl.nn.adapterframework.http.WebServiceListener; import nl.nn.adapterframework.jms.JmsListener; import nl.nn.adapterframework.pipes.XmlValidator; import nl.nn.adapterframework.util.AppConstants; import nl.nn.adapterframework.util.XmlUtils; import nl.nn.adapterframework.validation.SchemaUtils; import nl.nn.adapterframework.validation.XSD; import org.apache.commons.lang.StringUtils; /** * Utility class to generate the WSDL. Straight-forwardly implemented using stax only. * * An object of this class represents the WSDL associated with one IBIS pipeline. * * @author Michiel Meeuwissen * @author Jaco de Groot */ class Wsdl { protected static final String WSDL = "http://schemas.xmlsoap.org/wsdl/"; protected static final String SOAP_WSDL = "http://schemas.xmlsoap.org/wsdl/soap/"; protected static final String SOAP_HTTP = "http://schemas.xmlsoap.org/soap/http"; protected static final String SOAP_JMS = "http: // Tibco BW will not detect the transport when SOAP_JMS is being used // instead of ESB_SOAP_JMS. protected static final String ESB_SOAP_JMS = "http: protected static final String ESB_SOAP_JNDI = "http: protected static final String ESB_SOAP_TNS_BASE_URI = "http://nn.nl/WSDL"; protected static final List<String> excludeXsds = new ArrayList<String>(); static { excludeXsds.add("http://schemas.xmlsoap.org/soap/envelope/"); }; private boolean indent = true; private boolean useIncludes = false; private final String name; private final String filename; private final String targetNamespace; private final PipeLine pipeLine; private final XmlValidator inputValidator; private final XmlValidator outputValidator; private String webServiceListenerNamespace; private Set<XSD> rootXsds; private Set<XSD> xsdsRecursive; private Map<String, Set<XSD>> rootXsdsGroupedByNamespace; private LinkedHashMap<XSD, String> prefixByXsd; private LinkedHashMap<String, String> namespaceByPrefix; private String wsdlInputMessageName = "PipeLineInput"; private String wsdlOutputMessageName = "PipeLineOutput"; private String wsdlPortTypeName = "PipeLine"; private String wsdlOperationName = "Process"; private boolean esbSoap = false; private String esbSoapBusinessDomain; private String esbSoapServiceName; private String esbSoapServiceContext; private String esbSoapServiceContextVersion; private String esbSoapOperationName; private String esbSoapOperationVersion; private String documentation; private List<String> warnings = new ArrayList<String>(); Wsdl(PipeLine pipeLine) { this.pipeLine = pipeLine; this.name = this.pipeLine.getAdapter().getName(); if (this.name == null) { throw new IllegalArgumentException("The adapter '" + pipeLine.getAdapter() + "' has no name"); } inputValidator = (XmlValidator)pipeLine.getInputValidator(); if (inputValidator == null) { throw new IllegalStateException("The adapter '" + getName() + "' has no input validator"); } outputValidator = (XmlValidator)pipeLine.getOutputValidator(); String filename = name; AppConstants appConstants = AppConstants.getInstance(); String tns = appConstants.getResolvedProperty("wsdl." + getName() + ".targetNamespace"); if (tns == null) { tns = appConstants.getResolvedProperty("wsdl.targetNamespace"); } if (tns == null) { if (inputValidator instanceof EsbSoapValidator) { esbSoap = true; String schemaLocation = WsdlUtils.getFirstNamespaceFromSchemaLocation(inputValidator); if (EsbSoapWrapperPipe.isValidNamespace(schemaLocation)) { String s = WsdlUtils.getFirstNamespaceFromSchemaLocation(inputValidator); int i = s.lastIndexOf('/'); esbSoapOperationVersion = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapOperationName = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapServiceContextVersion = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapServiceContext = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapServiceName = s.substring(i + 1); s = s.substring(0, i); i = s.lastIndexOf('/'); esbSoapBusinessDomain = s.substring(i + 1); } else { warn("Namespace '" + schemaLocation + "' invalid according to ESB SOAP standard"); IPipe outputWrapper = pipeLine.getOutputWrapper(); if (outputWrapper != null && outputWrapper instanceof EsbSoapWrapperPipe) { EsbSoapWrapperPipe esbSoapWrapper = (EsbSoapWrapperPipe)outputWrapper; esbSoapBusinessDomain = esbSoapWrapper.getBusinessDomain(); esbSoapServiceName = esbSoapWrapper.getServiceName(); esbSoapServiceContext = esbSoapWrapper.getServiceContext(); esbSoapServiceContextVersion = esbSoapWrapper.getServiceContextVersion(); esbSoapOperationName = esbSoapWrapper.getOperationName(); esbSoapOperationVersion = esbSoapWrapper.getOperationVersion(); } } if (esbSoapBusinessDomain == null) { warn("Could not determine business domain"); } else if (esbSoapServiceName == null) { warn("Could not determine service name"); } else if (esbSoapServiceContext == null) { warn("Could not determine service context"); } else if (esbSoapServiceContextVersion == null) { warn("Could not determine service context version"); } else if (esbSoapOperationName == null) { warn("Could not determine operation name"); } else if (esbSoapOperationVersion == null) { warn("Could not determine operation version"); } else { String wsdlType = "abstract"; for(IListener l : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (l instanceof WebServiceListener || l instanceof JmsListener) { wsdlType = "concrete"; } } filename = esbSoapBusinessDomain + "_" + esbSoapServiceName + "_" + esbSoapServiceContext + "_" + esbSoapServiceContextVersion + "_" + esbSoapOperationName + "_" + esbSoapOperationVersion + "_" + wsdlType; tns = ESB_SOAP_TNS_BASE_URI + "/" + esbSoapBusinessDomain + "/" + esbSoapServiceName + "/" + esbSoapServiceContext + "/" + esbSoapServiceContextVersion + "/" + esbSoapOperationName + "/" + esbSoapOperationVersion; String inputParadigm = WsdlUtils.getEsbSoapParadigm(inputValidator); if (inputParadigm != null) { wsdlInputMessageName = esbSoapOperationName + "_" + esbSoapOperationVersion + "_" + inputParadigm; if (!"Action".equals(inputParadigm) && !"Event".equals(inputParadigm) && !"Request".equals(inputParadigm) && !"Solicit".equals(inputParadigm)) { warn("Paradigm for input message which was extracted from soapBody should be on of Action, Event, Request or Solicit instead of '" + inputParadigm + "'"); } } else { warn("Could not extract paradigm from soapBody attribute of inputValidator"); } if (outputValidator != null) { String outputParadigm = WsdlUtils.getEsbSoapParadigm(outputValidator); if (outputParadigm != null) { wsdlOutputMessageName = esbSoapOperationName + "_" + esbSoapOperationVersion + "_" + outputParadigm; if (!"Response".equals(outputParadigm)) { warn("Paradigm for output message which was extracted from soapBody should be Response instead of '" + outputParadigm + "'"); } } else { warn("Could not extract paradigm from soapBody attribute of outputValidator"); } } wsdlPortTypeName = esbSoapOperationName + "_Interface_" + esbSoapOperationVersion; wsdlOperationName = esbSoapOperationName + "_" + esbSoapOperationVersion; } } if (tns == null) { for(IListener l : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (l instanceof WebServiceListener) { webServiceListenerNamespace = ((WebServiceListener)l).getServiceNamespaceURI(); tns = webServiceListenerNamespace; } } if (tns == null) { tns = WsdlUtils.getFirstNamespaceFromSchemaLocation(inputValidator); } if (tns != null) { if (tns.endsWith("/")) { tns = tns + "wsdl/"; } else { tns = tns + "/wsdl/"; } } else { tns = "${wsdl." + getName() + ".targetNamespace}"; } } } this.filename = filename; this.targetNamespace = WsdlUtils.validUri(tns); } public String getName() { return name; } public String getFilename() { return filename; } public String getTargetNamespace() { return targetNamespace; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public boolean isIndent() { return indent; } public void setIndent(boolean indent) { this.indent = indent; } public boolean isUseIncludes() { return useIncludes; } public void setUseIncludes(boolean useIncludes) { this.useIncludes = useIncludes; } public void init() throws IOException, XMLStreamException { init(false); } public void init(boolean checkSchemaLocationOnly) throws IOException, XMLStreamException { Set<XSD> xsds = new TreeSet<XSD>(); xsds.addAll(initXsds(inputValidator, checkSchemaLocationOnly)); if (outputValidator != null) { xsds.addAll(initXsds(outputValidator, checkSchemaLocationOnly)); } if (!checkSchemaLocationOnly) { rootXsds = new TreeSet<XSD>(); xsdsRecursive = new TreeSet<XSD>(); rootXsds.addAll(xsds); xsdsRecursive.addAll(SchemaUtils.getXsdsRecursive(rootXsds)); prefixByXsd = new LinkedHashMap<XSD, String>(); namespaceByPrefix = new LinkedHashMap<String, String>(); int prefixCount = 1; rootXsdsGroupedByNamespace = SchemaUtils.getXsdsGroupedByNamespace(rootXsds); for (String namespace: rootXsdsGroupedByNamespace.keySet()) { xsds = rootXsdsGroupedByNamespace.get(namespace); for (XSD xsd: xsds) { prefixByXsd.put(xsd, "ns" + prefixCount); } namespaceByPrefix.put("ns" + prefixCount, namespace); prefixCount++; } } } public Set<XSD> initXsds(XmlValidator xmlValidator, boolean checkSchemaLocationOnly) throws IOException, XMLStreamException { Set<XSD> xsds = new TreeSet<XSD>(); String inputSchema = xmlValidator.getSchema(); if (inputSchema != null) { // In case of a WebServiceListener using soap=true it might be // valid to use the schema attribute (in which case the schema // doesn't have a namespace) as the WebServiceListener will // remove the soap envelop and body element before it is // validated. In this case we use the serviceNamespaceURI from // the WebServiceListener as the namespace for the schema. if (webServiceListenerNamespace != null) { if (!checkSchemaLocationOnly) { XSD xsd = SchemaUtils.getXSD(inputSchema, webServiceListenerNamespace, true, true); xsds.add(xsd); } } else { throw new IllegalStateException("The adapter " + pipeLine + " has a validator using the schema attribute but a namespace is required"); } } else { xsds = SchemaUtils.getXsds(xmlValidator.getSchemaLocation(), excludeXsds, xmlValidator.isAddNamespaceToSchema(), checkSchemaLocationOnly); } return xsds; } /** * Generates a zip file (and writes it to the given outputstream), containing the WSDL and all referenced XSD's. * @see {@link #wsdl(java.io.OutputStream, String)} */ public void zip(OutputStream stream, String servletName) throws IOException, XMLStreamException, NamingException { ZipOutputStream out = new ZipOutputStream(stream); // First an entry for the WSDL itself: ZipEntry wsdlEntry = new ZipEntry(getFilename() + ".wsdl"); out.putNextEntry(wsdlEntry); wsdl(out, servletName); out.closeEntry(); //And then all XSD's Set<String> entries = new HashSet<String>(); for (XSD xsd : xsdsRecursive) { String zipName = xsd.getBaseUrl() + xsd.getName(); if (entries.add(zipName)) { ZipEntry xsdEntry = new ZipEntry(zipName); out.putNextEntry(xsdEntry); XMLStreamWriter writer = WsdlUtils.getWriter(out, false); SchemaUtils.xsdToXmlStreamWriter(xsd, writer, true); out.closeEntry(); } else { warn("Duplicate xsds in " + this + " " + xsd + " " + xsdsRecursive); } } out.close(); } /** * Writes the WSDL to an output stream * @param out * @param servlet The servlet what is used as the web service (because this needs to be present in the WSDL) * @throws XMLStreamException * @throws IOException */ public void wsdl(OutputStream out, String servlet) throws XMLStreamException, IOException, NamingException { XMLStreamWriter w = WsdlUtils.getWriter(out, isIndent()); w.writeStartDocument(XmlUtils.STREAM_FACTORY_ENCODING, "1.0"); w.setPrefix("wsdl", WSDL); w.setPrefix("xsd", SchemaUtils.XSD); w.setPrefix("soap", SOAP_WSDL); if (esbSoap) { w.setPrefix("jms", ESB_SOAP_JMS); w.setPrefix("jndi", ESB_SOAP_JNDI); } else { w.setPrefix("jms", SOAP_JMS); } w.setPrefix("ibis", getTargetNamespace()); for (String prefix: namespaceByPrefix.keySet()) { w.setPrefix(prefix, namespaceByPrefix.get(prefix)); } w.writeStartElement(WSDL, "definitions"); { w.writeNamespace("wsdl", WSDL); w.writeNamespace("xsd", SchemaUtils.XSD); w.writeNamespace("soap", SOAP_WSDL); if (esbSoap) { w.writeNamespace("jndi", ESB_SOAP_JNDI); } w.writeNamespace("ibis", getTargetNamespace()); for (String prefix: namespaceByPrefix.keySet()) { w.writeNamespace(prefix, namespaceByPrefix.get(prefix)); } w.writeAttribute("targetNamespace", getTargetNamespace()); documentation(w); types(w); messages(w); portType(w); binding(w); service(w, servlet); } w.writeEndDocument(); warnings(w); w.close(); } /** * Outputs a 'documentation' section of the WSDL */ protected void documentation(XMLStreamWriter w) throws XMLStreamException { if (documentation != null) { w.writeStartElement(WSDL, "documentation"); w.writeCharacters(documentation); w.writeEndElement(); } } /** * Output the 'types' section of the WSDL * @param w * @throws XMLStreamException * @throws IOException */ protected void types(XMLStreamWriter w) throws XMLStreamException, IOException { w.writeStartElement(WSDL, "types"); if (isUseIncludes()) { SchemaUtils.mergeRootXsdsGroupedByNamespaceToSchemasWithIncludes( rootXsdsGroupedByNamespace, w); } else { Map<String, Set<XSD>> xsdsGroupedByNamespace = SchemaUtils.getXsdsGroupedByNamespace(xsdsRecursive); SchemaUtils.mergeXsdsGroupedByNamespaceToSchemasWithoutIncludes( xsdsGroupedByNamespace, w); } w.writeEndElement(); } /** * Outputs the 'messages' section. * @param w * @throws XMLStreamException * @throws IOException */ protected void messages(XMLStreamWriter w) throws XMLStreamException, IOException { List<QName> parts = new ArrayList<QName>(); parts.addAll(getInputHeaderTags()); parts.addAll(getInputBodyTags()); message(w, wsdlInputMessageName, parts); XmlValidator outputValidator = (XmlValidator) pipeLine.getOutputValidator(); if (outputValidator != null) { parts.clear(); parts.addAll(getOutputHeaderTags()); parts.addAll(getOutputBodyTags()); message(w, wsdlOutputMessageName, parts); } } protected void message(XMLStreamWriter w, String name, Collection<QName> tags) throws XMLStreamException, IOException { if (tags == null) throw new IllegalArgumentException("Tag cannot be null for " + name); if (!tags.isEmpty()) { w.writeStartElement(WSDL, "message"); w.writeAttribute("name", name); { for (QName tag : tags) { w.writeEmptyElement(WSDL, "part"); w.writeAttribute("name", getIbisName(tag)); String typ = tag.getPrefix() + ":" + tag.getLocalPart(); w.writeAttribute("element", typ); } } w.writeEndElement(); } } protected void portType(XMLStreamWriter w) throws XMLStreamException, IOException { w.writeStartElement(WSDL, "portType"); w.writeAttribute("name", wsdlPortTypeName); { w.writeStartElement(WSDL, "operation"); w.writeAttribute("name", wsdlOperationName); { w.writeEmptyElement(WSDL, "input"); w.writeAttribute("message", "ibis:" + wsdlInputMessageName); if (outputValidator != null) { w.writeEmptyElement(WSDL, "output"); w.writeAttribute("message", "ibis:" + wsdlOutputMessageName); } } w.writeEndElement(); } w.writeEndElement(); } protected String getSoapAction() { AppConstants appConstants = AppConstants.getInstance(); String sa = appConstants.getResolvedProperty("wsdl." + getName() + ".soapAction"); if (sa != null) return sa; sa = appConstants.getResolvedProperty("wsdl.soapAction"); if (sa != null) return sa; if (esbSoapOperationName != null && esbSoapOperationVersion != null) { return esbSoapOperationName + "_" + esbSoapOperationVersion; } return "${wsdl." + getName() + ".soapAction}"; } protected void binding(XMLStreamWriter w) throws XMLStreamException, IOException { for (IListener listener : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (listener instanceof WebServiceListener) { httpBinding(w); } else if (listener instanceof JmsListener) { jmsBinding(w); } } } protected void httpBinding(XMLStreamWriter w) throws XMLStreamException, IOException { w.writeStartElement(WSDL, "binding"); w.writeAttribute("name", "SoapBinding"); w.writeAttribute("type", "ibis:" + wsdlPortTypeName); { w.writeEmptyElement(SOAP_WSDL, "binding"); w.writeAttribute("transport", SOAP_HTTP); w.writeAttribute("style", "document"); writeSoapOperation(w); } w.writeEndElement(); } protected void writeSoapOperation(XMLStreamWriter w) throws XMLStreamException, IOException { w.writeStartElement(WSDL, "operation"); w.writeAttribute("name", wsdlOperationName); { w.writeEmptyElement(SOAP_WSDL, "operation"); w.writeAttribute("style", "document"); w.writeAttribute("soapAction", getSoapAction()); w.writeStartElement(WSDL, "input"); { writeSoapHeader(w, wsdlInputMessageName, getInputHeaderTags()); writeSoapBody(w, getInputBodyTags()); } w.writeEndElement(); if (outputValidator != null) { w.writeStartElement(WSDL, "output"); { writeSoapHeader(w, wsdlOutputMessageName, getOutputHeaderTags()); writeSoapBody(w, getOutputBodyTags()); } w.writeEndElement(); } } w.writeEndElement(); } protected void writeSoapHeader(XMLStreamWriter w, String wsdlMessageName, Collection<QName> tags) throws XMLStreamException, IOException { if (!tags.isEmpty()) { if (tags.size() > 1) { warn("Can only deal with one soap header. Taking only the first of " + tags); } w.writeEmptyElement(SOAP_WSDL, "header"); w.writeAttribute("part", getIbisName(tags.iterator().next())); w.writeAttribute("use", "literal"); w.writeAttribute("message", "ibis:" + wsdlMessageName); } } protected void writeSoapBody(XMLStreamWriter w, Collection<QName> tags) throws XMLStreamException, IOException { w.writeEmptyElement(SOAP_WSDL, "body"); writeParts(w, tags); w.writeAttribute("use", "literal"); } protected void writeParts(XMLStreamWriter w, Collection<QName> tags) throws XMLStreamException { StringBuilder builder = new StringBuilder(); for (QName outputTag : tags) { if (builder.length() > 0) builder.append(" "); builder.append(getIbisName(outputTag)); } w.writeAttribute("parts", builder.toString()); } protected String getIbisName(QName qname) { return qname.getLocalPart(); } protected void jmsBinding(XMLStreamWriter w) throws XMLStreamException, IOException { w.writeStartElement(WSDL, "binding"); w.writeAttribute("name", "SoapBinding"); w.writeAttribute("type", "ibis:" + wsdlPortTypeName); { w.writeEmptyElement(SOAP_WSDL, "binding"); w.writeAttribute("style", "document"); if (esbSoap) { w.writeAttribute("transport", ESB_SOAP_JMS); w.writeEmptyElement(ESB_SOAP_JMS, "binding"); w.writeAttribute("messageFormat", "Text"); writeSoapOperation(w); } else { w.writeAttribute("transport", SOAP_JMS); } } w.writeEndElement(); } protected void service(XMLStreamWriter w, String servlet) throws XMLStreamException, NamingException { for (IListener listener : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (listener instanceof WebServiceListener) { httpService(w, servlet); } else if (listener instanceof JmsListener) { jmsService(w, (JmsListener) listener); } } } protected void httpService(XMLStreamWriter w, String servlet) throws XMLStreamException { w.writeStartElement(WSDL, "service"); w.writeAttribute("name", WsdlUtils.getNCName(getName())); { w.writeStartElement(WSDL, "port"); w.writeAttribute("name", "SoapHttp"); w.writeAttribute("binding", "ibis:SoapBinding"); { w.writeEmptyElement(SOAP_WSDL, "address"); w.writeAttribute("location", servlet); } w.writeEndElement(); } w.writeEndElement(); } protected void jmsService(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, NamingException { w.writeStartElement(WSDL, "service"); w.writeAttribute("name", WsdlUtils.getNCName(getName())); { if (!esbSoap) { w.writeStartElement(SOAP_JMS, "jndiConnectionFactoryName"); w.writeCharacters(listener.getQueueConnectionFactoryName()); } w.writeStartElement(WSDL, "port"); w.writeAttribute("name", "SoapJMS"); w.writeAttribute("binding", "ibis:SoapBinding"); { w.writeEmptyElement(SOAP_WSDL, "address"); String destinationName = listener.getDestinationName(); if (destinationName != null) { w.writeAttribute("location", destinationName); } if (esbSoap) { writeEsbSoapJndiContext(w, listener); w.writeStartElement(ESB_SOAP_JMS, "connectionFactory"); { w.writeCharacters("externalJndiName-for-" + listener.getQueueConnectionFactoryName() + "-on-" + AppConstants.getInstance().getResolvedProperty("otap.stage")); w.writeEndElement(); } w.writeStartElement(ESB_SOAP_JMS, "targetAddress"); { w.writeAttribute("destination", listener.getDestinationType().toLowerCase()); String queueName = listener.getPhysicalDestinationShortName(); if (queueName == null) { queueName = "queueName-for-" + listener.getDestinationName() + "-on-" + AppConstants.getInstance().getResolvedProperty("otap.stage"); } w.writeCharacters(queueName); w.writeEndElement(); } } } w.writeEndElement(); } w.writeEndElement(); } protected void writeEsbSoapJndiContext(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, NamingException { w.writeStartElement(ESB_SOAP_JNDI, "context"); { w.writeStartElement(ESB_SOAP_JNDI, "property"); { w.writeAttribute("name", "java.naming.factory.initial"); w.writeAttribute("type", "java.lang.String"); w.writeCharacters("com.tibco.tibjms.naming.TibjmsInitialContextFactory"); w.writeEndElement(); } w.writeStartElement(ESB_SOAP_JNDI, "property"); { w.writeAttribute("name", "java.naming.provider.url"); w.writeAttribute("type", "java.lang.String"); String qcf = ""; String stage = ""; try { qcf = URLEncoder.encode( listener.getQueueConnectionFactoryName(), "UTF-8"); stage = URLEncoder.encode( AppConstants.getInstance().getResolvedProperty("otap.stage"), "UTF-8"); } catch (UnsupportedEncodingException e) { } w.writeCharacters("tibjmsnaming://host-for-" + qcf + "-on-" + stage + ":37222"); w.writeEndElement(); } w.writeStartElement(ESB_SOAP_JNDI, "property"); { w.writeAttribute("name", "java.naming.factory.object"); w.writeAttribute("type", "java.lang.String"); w.writeCharacters("com.tibco.tibjms.custom.CustomObjectFactory"); w.writeEndElement(); } } w.writeEndElement(); } protected void warnings(XMLStreamWriter w) throws XMLStreamException { for (String warning : warnings) { w.writeComment(warning); } } protected PipeLine getPipeLine() { return pipeLine; } protected Collection<QName> getHeaderTags(XmlValidator xmlValidator) throws XMLStreamException, IOException { if (xmlValidator instanceof SoapValidator) { String root = ((SoapValidator)xmlValidator).getSoapHeader(); QName q = getRootTag(root); if (q != null) { return Collections.singleton(q); } } return Collections.emptyList(); } protected Collection<QName> getRootTags(XmlValidator xmlValidator) throws IOException, XMLStreamException { String root; if (xmlValidator instanceof SoapValidator) { root = ((SoapValidator)xmlValidator).getSoapBody(); } else { root = xmlValidator.getRoot(); } QName q = getRootTag(root); if (q != null) { return Collections.singleton(q); } return Collections.emptyList(); } protected QName getRootTag(String tag) throws XMLStreamException, IOException { if (StringUtils.isNotEmpty(tag)) { for (XSD xsd : rootXsds) { for (String rootTag : xsd.rootTags) { if (tag.equals(rootTag)) { String prefix = prefixByXsd.get(xsd); return new QName(namespaceByPrefix.get(prefix), tag, prefix); } } } warn("Root element '" + tag + "' not found in XSD's"); } return null; } protected Collection<QName> getInputHeaderTags() throws IOException, XMLStreamException { return getHeaderTags(inputValidator); } protected Collection<QName> getInputBodyTags() throws IOException, XMLStreamException { return getRootTags(inputValidator); } protected Collection<QName> getOutputHeaderTags() throws IOException, XMLStreamException { return getHeaderTags(outputValidator); } protected Collection<QName> getOutputBodyTags() throws IOException, XMLStreamException { return getRootTags((XmlValidator)getPipeLine().getOutputValidator()); } protected void warn(String warning) { warning = "Warning: " + warning; if (!warnings.contains(warning)) { warnings.add(warning); } } }
package com.frontend; /** * Defines elements of a GameMap **/ public class GameMapEntry { private char symbol; private GameMapEntryColor foregroundColor; private GameMapEntryColor backgroundColor; private GameMapEntryAttribute attribute; public GameMapEntry(char symbol, GameMapEntryColor foregroundColor, GameMapEntryColor backgroundColor, GameMapEntryAttribute attribute) { this.symbol = symbol; this.foregroundColor = foregroundColor; this.backgroundColor = backgroundColor; this.attribute = attribute; } /* * copy constructor */ public GameMapEntry(GameMapEntry other) { this(other.symbol, other.foregroundColor, other.backgroundColor, other.attribute); } // accessor methods public char getSymbol() { return symbol; } public GameMapEntryColor getForegroundColor() { return foregroundColor; } public GameMapEntryColor getBackgroundColor() { return backgroundColor; } public GameMapEntryAttribute getAttribute() { return attribute; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final GameMapEntry other = (GameMapEntry) obj; if (this.getSymbol() != other.getSymbol()) { return false; } if (this.getBackgroundColor() != other.getBackgroundColor()) { return false; } if (this.getForegroundColor() != other.getForegroundColor()) { return false; } if (this.getAttribute() != other.getAttribute()) { return false; } return true; } }
package server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String []args){ int port = 1092; try { ServerSocket ss = new ServerSocket(port); System.out.println("Waiting for connection..."); Socket socket = ss.accept(); System.out.println("Accept connection!"); DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); //DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); String word = dataInputStream.readUTF(); System.out.println("Message from client: " + word); } catch (Exception x){ x.printStackTrace(); } } }
package loc.statistics; import loc.filter.Filter; import java.util.Comparator; import java.util.Map; public class StatisticsComparator implements Comparator<Map.Entry<Filter, FileStatistics>> { @Override public int compare(Map.Entry<Filter, FileStatistics> o1, Map.Entry<Filter, FileStatistics> o2) { if (o1 == null || o2 == null) throw new NullPointerException(); if (o1.getValue().lineCount < o2.getValue().lineCount) return 1; if (o1.getValue().lineCount > o2.getValue().lineCount) return -1; if (o1.getValue().fileCount < o2.getValue().fileCount) return 1; return 0; } }
package creatures; import java.io.File; import java.io.IOException; import javax.media.opengl.GL2; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.GLUquadric; import com.jogamp.opengl.util.texture.Texture; import com.jogamp.opengl.util.texture.TextureIO; import game.Building; import game.PlayerMotionWatcher; import game.PlayerStats; public class Mummy implements Creature, PlayerMotionWatcher, ProjectileWatcher{ float locx, locy, locz; float eyeAngle = 0; final float moveSpeed = 1f; final float runSpeed = 2f; final float rotateSpeed = 2f; final float sightRadius = 20; private Texture bodyTexture; private GLUquadric bodyQuadric; boolean facingFront = true; boolean agro, dead; static float T = 0; public Mummy(float x, float z, GL2 gl, GLU glu){ locx = x; locy = 0; locz = z; bodyTexture = Building.setupTexture(gl, "liangmummy.jpg"); bodyQuadric = glu.gluNewQuadric(); glu.gluQuadricDrawStyle(bodyQuadric, GLU.GLU_FILL); // GLU_POINT, GLU_LINE, GLU_FILL, GLU_SILHOUETTE glu.gluQuadricNormals (bodyQuadric, GLU.GLU_NONE); // GLU_NONE, GLU_FLAT, or GLU_SMOOTH glu.gluQuadricTexture (bodyQuadric, true); // false, or true to generate texture coordinates agro = false; dead = false; } private void drawMoving(GL2 gl, GLU glu, float T){ if (agro){drawAgro(gl,glu,T);} else drawPassive(gl, glu, T); } private void drawAgro(GL2 gl, GLU glu, float T) { T *= 2; gl.glEnable(GL2.GL_TEXTURE_2D); bodyTexture.bind(gl); drawHead(gl, glu); drawLeg(gl, glu, T); gl.glPushMatrix(); gl.glTranslatef(0f,4.75f,4.5f); gl.glRotatef(90, -1, 0, 0); drawArm(gl, glu, T+.5f); gl.glPopMatrix(); gl.glDisable(GL2.GL_TEXTURE_2D); drawBody(gl,glu); drawEye(gl,glu); gl.glPushMatrix(); gl.glScalef(-1,1,1); gl.glEnable(GL2.GL_TEXTURE_2D); bodyTexture.bind(gl); drawLeg(gl, glu, T+.5f); gl.glPushMatrix(); gl.glTranslatef(0f,4.75f,4.5f); gl.glRotatef(90, -1, 0, 0); drawArm(gl, glu, T); gl.glPopMatrix(); gl.glDisable(GL2.GL_TEXTURE_2D); drawEye(gl, glu); gl.glPopMatrix(); } private void drawPassive(GL2 gl, GLU glu, float T) { //Head gl.glEnable(GL2.GL_TEXTURE_2D); bodyTexture.bind(gl); drawHead(gl, glu); drawLeg(gl, glu, T); drawArm(gl, glu, T+.5f); gl.glDisable(GL2.GL_TEXTURE_2D); drawBody(gl, glu); drawEye(gl,glu); gl.glPushMatrix(); gl.glScalef(-1,1,1); gl.glEnable(GL2.GL_TEXTURE_2D); bodyTexture.bind(gl); drawLeg(gl, glu, T+.5f); drawArm(gl, glu, T); gl.glDisable(GL2.GL_TEXTURE_2D); drawEye(gl, glu); gl.glPopMatrix(); } private void drawHead(GL2 gl, GLU glu){ gl.glColor3f(.8007f, .7539f, .7695f); gl.glPushMatrix(); gl.glTranslatef(0f,6.5f,0f); //gl.glRotated(90,1f,0f,0f); glu.gluSphere(bodyQuadric, 1.5f, 20, 10); gl.glPopMatrix(); } private void drawBody(GL2 gl, GLU glu){ gl.glColor3f(.8007f, .7539f, .7695f); gl.glEnable(GL2.GL_TEXTURE_2D); gl.glEnable(GL2.GL_TEXTURE_GEN_S); gl.glEnable(GL2.GL_TEXTURE_GEN_T); gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_OBJECT_LINEAR); gl.glTexGeni(GL2.GL_T, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_OBJECT_LINEAR); float[] coef_s = {.2f,0f,.5f,0}; gl.glTexGenfv(GL2.GL_S, GL2.GL_OBJECT_PLANE, coef_s, 0); float[] coef_t = {0f,1f,0f,0}; gl.glTexGenfv(GL2.GL_T, GL2.GL_OBJECT_PLANE, coef_t, 0); bodyTexture.bind(gl); gl.glPushMatrix(); gl.glTranslatef(0f,.6f,-2.5f); gl.glRotatef(25f, 1f, 0f, 0f); gl.glBegin(GL2.GL_QUADS); gl.glVertex3f(1.75f, 3, 0.5f); gl.glVertex3f(1.75f, 3, -0.5f); gl.glVertex3f(2.f, 5, -0.75f); gl.glVertex3f(2.f, 5, 0.75f); gl.glVertex3f(-1.75f, 3, 0.5f); gl.glVertex3f(-1.75f, 3, -0.5f); gl.glVertex3f(-2.f, 5, -0.75f); gl.glVertex3f(-2.f, 5, 0.75f); gl.glVertex3f(-1.75f, 3, 0.5f); gl.glVertex3f(-2f, 5, 0.75f); gl.glVertex3f(2f, 5, 0.75f); gl.glVertex3f(1.75f, 3, 0.5f); gl.glVertex3f(-1.75f, 3, -0.5f); gl.glVertex3f(-2.f, 5, -0.75f); gl.glVertex3f(2.f, 5, -0.75f); gl.glVertex3f(1.75f, 3, -0.5f); gl.glVertex3f(-2.f, 5, 0.75f); gl.glVertex3f(-2.f, 5, -0.75f); gl.glVertex3f(2.f, 5, -0.75f); gl.glVertex3f(2.f, 5, 0.75f); gl.glColor3f(0f, 0f, 0f); gl.glVertex3f(1.75f, 3, 0.5f); gl.glVertex3f(1.75f, 3, -0.5f); gl.glVertex3f(.75f, 2, -0.2f); gl.glVertex3f(.75f, 2, 0.2f); gl.glVertex3f(-1.75f, 3, 0.5f); gl.glVertex3f(-1.75f, 3, -0.5f); gl.glVertex3f(-.75f, 2, -0.2f); gl.glVertex3f(-.75f, 2, 0.2f); gl.glVertex3f(-1.75f, 3, 0.5f); gl.glVertex3f(-.75f, 2, 0.2f); gl.glVertex3f(.75f, 2, 0.2f); gl.glVertex3f(1.75f, 3, 0.5f); gl.glVertex3f(-1.75f, 3, -0.5f); gl.glVertex3f(-.75f, 2, -0.2f); gl.glVertex3f(.75f, 2, -0.2f); gl.glVertex3f(1.75f, 3, -0.5f); gl.glEnd(); gl.glColor3f(.8007f, .7539f, .7695f); gl.glTranslatef(0f,5.5f,0.1f); gl.glRotatef(90f, 1f, 0f, 0f); glu.gluCylinder(bodyQuadric, .5f, .6f, 1f, 20, 10); gl.glPopMatrix(); gl.glDisable(GL2.GL_TEXTURE_2D); } private void drawLeg(GL2 gl, GLU glu,float T){ gl.glColor3f(.8007f, .7539f, .7695f); gl.glPushMatrix(); float angle = (float) (15*Math.cos(Math.toRadians(T*360))); gl.glTranslatef(-1.2f, 3f,-1.3f); gl.glRotated(90, 1, 0, 0); gl.glRotated(angle, 3f, 0,0); glu.gluCylinder(bodyQuadric, .4f, .3f, 2.5f, 20, 10); gl.glPopMatrix(); } private void drawArm(GL2 gl, GLU glu,float T){ gl.glColor3f(.8007f, .7539f, .7695f); gl.glPushMatrix(); float angle = (float) (15*Math.cos(Math.toRadians(T*360))); gl.glTranslatef(-2f, 4.75f,-0.5f); gl.glRotated(90, 1, 0, 0); gl.glRotated(angle, 5f, 0,0); glu.gluSphere(bodyQuadric, .4f, 20, 10); glu.gluCylinder(bodyQuadric, .4f, .3f, 2.5f, 20, 10); gl.glPopMatrix(); } private void drawEye(GL2 gl, GLU glu) { gl.glColor3f(1f, 1f, 1f); gl.glPushMatrix(); gl.glTranslatef(-0.5f,6.3f,1.1f); glu.gluSphere(bodyQuadric, .3f, 20, 10); gl.glPopMatrix(); } public void move(){ float speed; if (!agro) { speed = moveSpeed; if (eyeAngle == 360) eyeAngle = 0; if (locz < -20 ) { if (!facingFront)eyeAngle-=rotateSpeed; if (eyeAngle == 0) {facingFront = true; locz +=speed*Math.cos(Math.toRadians(eyeAngle)); locx -=speed*Math.sin(Math.toRadians(eyeAngle)); } } else if (locz > 20){ if (facingFront) eyeAngle+=rotateSpeed; if (eyeAngle == 180) {facingFront = false; locz +=speed*Math.cos(Math.toRadians(eyeAngle)); locx -=speed*Math.sin(Math.toRadians(eyeAngle)); } } else { locz +=speed*Math.cos(Math.toRadians(eyeAngle)); locx -=speed*Math.sin(Math.toRadians(eyeAngle)); } } else {speed = runSpeed; //if player within range, turn and face player locz +=speed*Math.cos(Math.toRadians(eyeAngle)); locx -=speed*Math.sin(Math.toRadians(eyeAngle)); } } public void draw(GL2 gl, GLU glu) { //move(); gl.glTranslatef(locx, (float) (locy + 0.1*Math.sin(Math.toRadians((T/60)*360))), locz); gl.glRotatef(eyeAngle, 0, 1, 0); drawMoving(gl, glu, T/60); System.out.println("Position: " + locx + " " + locz); T+=1f; if (T > 60) T = 0; } @Override public void projectileMoved(double x, double z) { // TODO Auto-generated method stub } @Override public void playerMoved(float x, float y, float z, float angle, float y_angle, PlayerStats s) { float distance = (float) Math.sqrt(Math.pow((x-locx),2) + Math.pow((y-locy),2)); if (distance < sightRadius) {agro = true;} if(distance < 2){s.changeHealth(-1); }; } }
package scal.io.liger; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.util.Log; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; import java.io.File; import java.io.IOException; public class StorageHelper { public static final String KEY_USE_INTERNAL = "p_use_internal_storage"; @Nullable public static File getActualStorageDirectory(Context context) { // locate actual external storage path if available File returnValue = null; // values for debugging int storageState = 0; int storageCount = 0; if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) { // can't use this method for older versions, just use existing method // Log.d("SDCARD", "VERSION " + Build.VERSION.SDK_INT + ", USING OLD METHOD: " + context.getExternalFilesDir(null).getPath()); storageState = 1; returnValue = context.getExternalFilesDir(null); } else { // use new method to get all directories, only the first directory should be internal storage File[] externalFilesDirs = context.getExternalFilesDirs(null); storageCount = externalFilesDirs.length; /// FIXME what if internal is null? try to use external even though they said useIinternal returnValue = externalFilesDirs[0]; // FIXME default our returnValue to the internal so if we fail finding a more appropriate place this is our fallback storageState = 2; // FIXME just for debugging now SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); boolean useInternal = settings.getBoolean(KEY_USE_INTERNAL, false); if (useInternal) { storageState = 4; } else { if (externalFilesDirs.length > 1) { // iterate over storage options in case one or more is unavailable int i = 1; while (i < externalFilesDirs.length) { if (externalFilesDirs[i] != null) { storageState = 3; returnValue = externalFilesDirs[i]; break; // FIXME using the first available card, if we detect more than one we should probably let the user pick which one? } i++; } } } if (returnValue == null) { Log.e("STORAGE_ERROR", "EXTERNAL FILES DIRECTORY IS NULL (STORAGE IS UNAVAILABLE)"); switch (storageState) { case 1: Log.e("STORAGE_ERROR", "PRE-JELLYBEAN BUILD " + Build.VERSION.SDK_INT + " FOUND SO INTERNAL STORAGE MUST BE USED"); break; case 2: Log.e("STORAGE_ERROR", storageCount + " EXTERNAL STORAGE OPTIONS FOUND BUT USER SELECTED INTERNAL STORAGE"); break; case 3: Log.e("STORAGE_ERROR", storageCount + " EXTERNAL STORAGE OPTIONS FOUND AND USER SELECTED EXTERNAL STORAGE"); break; case 4: Log.e("STORAGE_ERROR", storageCount + " EXTERNAL STORAGE OPTIONS FOUND SO INTERNAL STORAGE MUST BE USED"); break; default: Log.e("STORAGE_ERROR", "UNEXPECTED STATE"); break; } } return returnValue; } public static String fixPath (String currentPath, Context context) { // instances and indexes may store full paths, need to compare and update String actualPath = getActualStorageDirectory(context).getPath(); if (!currentPath.contains(actualPath)) { Log.d("SDCARD", currentPath + " MUST BE UPDATED -> " + actualPath); return actualPath + currentPath.substring(currentPath.lastIndexOf(File.separator)); } return currentPath; } public static boolean migrateToExternal(Context context) { // migrate files from internal storage to external storage if available if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) { // can't use this method for older versions, so no point in migrating Log.e("SDCARD", "VERSION " + Build.VERSION.SDK_INT + ", CAN'T DETERMINE EXTERNAL PATH FOR MIGRATION"); return false; } else { // use new method to get all directories, only the first directory should be internal storage File[] externalFilesDirs = context.getExternalFilesDirs(null); if (externalFilesDirs.length > 1) { Log.d("SDCARD", "VERSION " + Build.VERSION.SDK_INT + ", MIGRATING FILES TO EXTERNAL PATH " + externalFilesDirs[1].getPath()); return moveFromHereToThere(externalFilesDirs[0], externalFilesDirs[1]); } else { // no external directories available, so no point in migrating Log.e("SDCARD", "VERSION " + Build.VERSION.SDK_INT + ", NO EXTERNAL PATH FOR MIGRATION"); return false; } } } // adding this method to allow the user to switch back to internal storage public static boolean migrateFromExternal(Context context) { // migrate files from external storage (if available) to internal storage if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) { // can't use this method for older versions, so no point in migrating Log.e("SDCARD", "VERSION " + Build.VERSION.SDK_INT + ", CAN'T DETERMINE EXTERNAL PATH FOR MIGRATION"); return false; } else { // use new method to get all directories, only the first directory should be internal storage File[] externalFilesDirs = context.getExternalFilesDirs(null); if (externalFilesDirs.length > 1) { // TODO: actually migrate files Log.d("SDCARD", "VERSION " + Build.VERSION.SDK_INT + ", MIGRATING FILES TO INTERNAL PATH " + externalFilesDirs[0].getPath()); return moveFromHereToThere(externalFilesDirs[1], externalFilesDirs[0]); } else { // no external directories available, so no point in migrating Log.e("SDCARD", "VERSION " + Build.VERSION.SDK_INT + ", NO EXTERNAL PATH FOR MIGRATION"); return false; } } } private static boolean moveFromHereToThere(File source, File destination) { if (!source.exists()) { Log.e("SDCARD", "SOURCE DIRECTORY " + source.getPath() + " DOES NOT EXIST"); return false; } try { FileUtils.copyDirectory(source, destination, true); } catch (IOException ioe) { Log.e("SDCARD", "FAILED TO COPY " + source.getPath() + " - " + ioe.getMessage()); return false; } try { FileUtils.deleteDirectory(source); } catch (IOException ioe) { Log.e("SDCARD", "FAILED TO DELETE " + source.getPath() + " - " + ioe.getMessage()); return false; } return true; } }
package top.zibin.luban; import android.graphics.BitmapFactory; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; enum Checker { SINGLE; private static final String TAG = "Luban"; private static final String JPG = ".jpg"; private final byte[] JPEG_SIGNATURE = new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF}; /** * Determine if it is JPG. * * @param is image file input stream */ boolean isJPG(InputStream is) { return isJPG(toByteArray(is)); } /** * Returns the degrees in clockwise. Values are 0, 90, 180, or 270. */ int getOrientation(InputStream is) { return getOrientation(toByteArray(is)); } private boolean isJPG(byte[] data) { if (data == null || data.length < 3) { return false; } byte[] signatureB = new byte[]{data[0], data[1], data[2]}; return Arrays.equals(JPEG_SIGNATURE, signatureB); } private int getOrientation(byte[] jpeg) { if (jpeg == null) { return 0; } int offset = 0; int length = 0; // ISO/IEC 10918-1:1993(E) while (offset + 3 < jpeg.length && (jpeg[offset++] & 0xFF) == 0xFF) { int marker = jpeg[offset] & 0xFF; // Check if the marker is a padding. if (marker == 0xFF) { continue; } offset++; // Check if the marker is SOI or TEM. if (marker == 0xD8 || marker == 0x01) { continue; } // Check if the marker is EOI or SOS. if (marker == 0xD9 || marker == 0xDA) { break; } // Get the length and check if it is reasonable. length = pack(jpeg, offset, 2, false); if (length < 2 || offset + length > jpeg.length) { Log.e(TAG, "Invalid length"); return 0; } // Break if the marker is EXIF in APP1. if (marker == 0xE1 && length >= 8 && pack(jpeg, offset + 2, 4, false) == 0x45786966 && pack(jpeg, offset + 6, 2, false) == 0) { offset += 8; length -= 8; break; } // Skip other markers. offset += length; length = 0; } // JEITA CP-3451 Exif Version 2.2 if (length > 8) { // Identify the byte order. int tag = pack(jpeg, offset, 4, false); if (tag != 0x49492A00 && tag != 0x4D4D002A) { Log.e(TAG, "Invalid byte order"); return 0; } boolean littleEndian = (tag == 0x49492A00); // Get the offset and check if it is reasonable. int count = pack(jpeg, offset + 4, 4, littleEndian) + 2; if (count < 10 || count > length) { Log.e(TAG, "Invalid offset"); return 0; } offset += count; length -= count; // Get the count and go through all the elements. count = pack(jpeg, offset - 2, 2, littleEndian); while (count-- > 0 && length >= 12) { // Get the tag and check if it is orientation. tag = pack(jpeg, offset, 2, littleEndian); if (tag == 0x0112) { int orientation = pack(jpeg, offset + 8, 2, littleEndian); switch (orientation) { case 1: return 0; case 3: return 180; case 6: return 90; case 8: return 270; } Log.e(TAG, "Unsupported orientation"); return 0; } offset += 12; length -= 12; } } Log.e(TAG, "Orientation not found"); return 0; } String extSuffix(InputStreamProvider input) { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(input.open(), null, options); return options.outMimeType.replace("image/", "."); } catch (Exception e) { return JPG; } } boolean needCompress(int leastCompressSize, String path) { if (leastCompressSize > 0) { File source = new File(path); return source.exists() && source.length() > (leastCompressSize << 10); } return true; } private int pack(byte[] bytes, int offset, int length, boolean littleEndian) { int step = 1; if (littleEndian) { offset += length - 1; step = -1; } int value = 0; while (length value = (value << 8) | (bytes[offset] & 0xFF); offset += step; } return value; } private byte[] toByteArray(InputStream is) { if (is == null) { return new byte[0]; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int read; byte[] data = new byte[4096]; try { while ((read = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, read); } } catch (Exception ignored) { return new byte[0]; } finally { try { buffer.close(); } catch (IOException ignored) { } } return buffer.toByteArray(); } }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.io.IOException; import java.nio.charset.Charset; import java.util.function.BiConsumer; public class FileReader { // Properties private String filePath; private FileInputStream inputStream; private InputStreamReader inputStreamReader; private BufferedReader bufferedReader; private int currentLine = Integer.MIN_VALUE; // Accessors public void setFilePath(String f) { filePath = f; } public String getFilePath() { return filePath; } public void setInputStream(FileInputStream i) { inputStream = i; } public FileInputStream getInputStream() { return inputStream; } public void setInputStreamReader(InputStreamReader i) { inputStreamReader = i; } public InputStreamReader getInputStreamReader() { return inputStreamReader; } public void setBufferedReader(BufferedReader r) { bufferedReader = r; } public BufferedReader getBufferedReader() { return bufferedReader; } private void setCurrentLine(int cl) { currentLine = cl; } private int getCurrentLine() { return currentLine; } // Convenience private void incrementLine() { currentLine ++; } // Constructor public FileReader(String path) { setFilePath(path); } // Uses a lamda to deal with every line. Thanks, Java 8 public void forEachLine(BiConsumer<String, Integer> lambda) { try { // Create our input stream objects. setInputStream(new FileInputStream(getFilePath())); setInputStreamReader(new InputStreamReader (getInputStream(), Charset.forName("UTF-8"))); setBufferedReader(new BufferedReader(getInputStreamReader())); String line = null; BufferedReader reader = getBufferedReader(); // Set our current line to 1. setCurrentLine(1); while((line = reader.readLine()) != null) { // Call the function that was passed in lambda.accept(line, new Integer(getCurrentLine())); incrementLine(); } getInputStream().close(); getInputStreamReader().close(); getBufferedReader().close(); } catch (UnsupportedEncodingException ex) { Main.exitWithError( "The encoding used was incompatible with the file."); } catch (FileNotFoundException ex) { Main.exitWithError("The file you entered was not found."); } catch (IOException ex) { Main.exitWithError( "There was an IO error while attempting to read the file."); } } }
package tracklayout.utilities; import com.Endpoint; import com.SenderI; import database.Database; import datatypes.enumerations.ErrorId; import datatypes.objects.ErrorData; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.NoSuchElementException; import java.util.logging.Level; import java.util.logging.Logger; import messages.Message; import messages.MessageType; public class TracklayoutLock { protected static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); protected Database database = null; protected SenderI dispatcher = null; public TracklayoutLock(SenderI dispatcher, Database database) { this.database = database; this.dispatcher = dispatcher; } public void freeLocks(long id) { try { Connection con = database.getConnection(); String q = "UPDATE `TrackLayouts` SET `Locked` = NULL "; if(id != -1) { q += "WHERE `Locked` = ?"; } try(PreparedStatement pstmt = con.prepareStatement(q)) { if(id != -1) { pstmt.setLong(1, id); } pstmt.executeUpdate(); TracklayoutLock.LOGGER.log(Level.INFO, "<{0}>", new Object[]{pstmt.toString()}); } } catch(SQLException e) { TracklayoutLock.LOGGER.log(Level.WARNING, "<{0}>", new Object[]{e.toString()}); } } public boolean isLocked(long id, Endpoint ep) throws SQLException, NoSuchElementException { long appId = ep.getAppId(); long lockedBy = isLocked(id); if(lockedBy == 0 || lockedBy == appId) { return false; } TracklayoutLock.LOGGER.log(Level.WARNING, "layout <{0}> is locked", new Object[]{id}); dispatcher.dispatch(new Message( MessageType.CLIENT_ERROR, new ErrorData(ErrorId.DATASET_LOCKED, "layout is locked by <" + Long.toString(lockedBy) + ">"), ep )); return true; } protected long isLocked(long id) throws SQLException, NoSuchElementException { Connection con = database.getConnection(); String q = "SELECT `locked` FROM `TrackLayouts` WHERE `Id` = ?"; try(PreparedStatement pstmt = con.prepareStatement(q)) { pstmt.setLong(1, id); ResultSet rs = pstmt.executeQuery(); if(!rs.next()) { throw new NoSuchElementException("no layout found with id <" + Long.toString(id) + ">"); } return rs.getLong("locked"); } } public void unlockLayout(Message msg) { try { long id = (Long)msg.getData(); if(isLocked(id, msg.getEndpoint())) { return; } Connection con = database.getConnection(); String q = "UPDATE `TrackLayouts` SET `locked` = 0 WHERE `locked` = ? AND `id` = ? "; try(PreparedStatement pstmt = con.prepareStatement(q)) { pstmt.setLong(2, msg.getEndpoint().getAppId()); pstmt.setLong(3, id); TracklayoutLock.LOGGER.log(Level.INFO, "<{0}>", new Object[]{pstmt.toString()}); if(pstmt.executeUpdate() == 0) { dispatcher.dispatch( new Message(MessageType.CLIENT_ERROR, new ErrorData(ErrorId.DATASET_MISSING), msg.getEndpoint()) ); pstmt.close(); return; } } dispatcher.dispatch(new Message(MessageType.LAYOUT_LAYOUT_UNLOCKED, id)); } catch(SQLException e) { TracklayoutLock.LOGGER.log(Level.WARNING, "<{0}>", new Object[]{e.toString()}); dispatcher.dispatch(new Message(MessageType.CLIENT_ERROR, new ErrorData(ErrorId.DATABASE_ERROR, e.getMessage()), msg.getEndpoint())); } } }
package com.psddev.dari.util; import java.util.concurrent.locks.ReadWriteLock; /** * For making sure that something runs only once safely and efficiently. * * <p>Typical usage looks like:</p> * * <p><blockquote><code> * public class Foo { * private static final Once INIT_ONCE = new Once() { * {@literal @}Override * protected void run() { * // Do something. * } * } * * private void bar() { * INIT_ONCE.ensure(); * // Do something else that depends on the init. * } * } * </code></blockquote></p> */ public abstract class Once { private volatile Thread running; private volatile boolean ran; /** * Creates an instance. * * @param lock Not used. * @deprecated Use {@link Once()} instead. */ @Deprecated public Once(ReadWriteLock lock) { } /** * Creates an instance. */ public Once() { } /** * Runs some code. */ protected abstract void run() throws Exception; /** * Ensures that {@link #run} has been called at least once. */ public final void ensure() { if (Thread.currentThread().equals(running) || ran) { return; } synchronized (this) { if (!ran) { try { running = Thread.currentThread(); run(); ran = true; } catch (Exception error) { ErrorUtils.rethrow(error); } finally { running = null; } } } } /** * Resets so that the next invocation of {@link #ensure} can call * {@link #run} again. */ public final void reset() { ran = false; } }
/* * This is each node in the input, output and hidden layers */ import java.util.ArrayList; import java.util.HashMap; public class Node { static int counter=0;// This is the id of each of the Nodes that will increment each time a new node is created final public int id; Connection biasConnection;//Connection with a bias Node set up in the neural network class double bias=-1; double output; ArrayList<Connection> InConnections = new ArrayList<Connection>();//Input connections HashMap<Integer,Connection> findConnection = new HashMap<Integer,Connection>();//Find the connection based on the id of the connection public Node() { id=counter; counter++; } /* * Sj = (Wij * Iij) + w0j*bias * * Sigmoid for a node is the total weight for each of the weights * the total inputs from the previous * layer plus the weight of the bias connection times the bias input * The bias allows for the shifting of the graph in the case a 0 is needed for output */ public void calculateOutput() { double s = 0;//Sigmoid total for the node for(Connection con : InConnections)//Getting the total weight*output for the Node { Node prevNode = con.getFromNode(); double weight = con.getWeight(); double input = prevNode.getOutput();//Get output from previous layer s = s + (weight*input); } s = s + (biasConnection.getWeight()*bias); output = sigmoid(s); } /* * The activation function makes the function non linear to get the desired outputs */ double sigmoid(double s) { return 1.0 / (1.0 + Math.exp(s)); } public double getBias() { return bias; } public double getOutput() { return output; } public void setOutput(double o){ output = o; } public ArrayList<Connection> getAllInConnections(){ return InConnections; } public Connection getConnection(int neuronIndex){ return findConnection.get(neuronIndex); } //Adds connections for an ArrayList of nodes public void addInConnections(ArrayList<Node> inNodes){ for(Node n: inNodes) { Connection con = new Connection(n,this); InConnections.add(con); findConnection.put(n.id, con); } } public void addInConnection(Connection con){ InConnections.add(con); } public void addBiasConnection(Node n){ Connection con = new Connection(n,this); biasConnection = con; InConnections.add(con); } }
package textedu; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; public class LeaderBoard { ArrayList<SimpleUser> userScores = new ArrayList<SimpleUser>(); public LeaderBoard() { } private void addUser(User u) { userScores.add(new SimpleUser(u)); Collections.sort((List<SimpleUser>) userScores); } public void updateUsers(User u) { SimpleUser su = new SimpleUser(u); if (!userScores.contains(su)) { addUser(u); } else { userScores.remove(su); userScores.add(su); } Collections.sort((List<SimpleUser>) userScores); } public String getRank(User u) { String toReturn = ""; for (int i = 0; i < userScores.size(); i++) { if (userScores.get(i).equals(u)) { int rank = i + 1; int rankPrev = i; if (rankPrev == 0) { toReturn += "Rank: " + rankPrev + " " + userScores.get(i-1).getName() + " " + userScores.get(i-1).getScore() + "\n"; } toReturn += "Rank: " + rank + " " + userScores.get(i).getName() + " " + userScores.get(i).getScore(); } } return toReturn; } public int getNumUsersInLeaderboard() { return userScores.size(); } public String getTopScores() { String top = ""; int sizeTo = 5; if (userScores.size() < sizeTo) { sizeTo = userScores.size(); } top += "Top " + sizeTo + " Scores:\n"; for (int i = 1; i <= sizeTo; i++) { top += userScores.get(i-1).getName() + " " + userScores.get(i-1).getScore() + "\n"; } return top; } private class SimpleUser implements Comparable { private String name; private int score; public SimpleUser(User u) { name = u.getName(); score = u.getPoints(); } public String getName() { return name; } public int getScore() { return score; } public boolean equals(User u) { if (name.equalsIgnoreCase(u.getName())) { return true; } else { return false; } } public boolean equals(SimpleUser u) { if (name.equalsIgnoreCase(u.getName())) { return true; } else { return false; } } public int compareTo(Object o) { SimpleUser other = (SimpleUser) o; return ((Integer) other.getScore()).compareTo((Integer) score); } } }
package test; import static org.junit.Assert.*; import java.util.Vector; import misc.PolyFunction; import org.junit.Test; import finders.FinderInterface; import finders.InvalidFuncException; import finders.LinearFinder; import finders.NewtonFinder; import finders.QuadricFinder; public class FinderTest { @Test public void testLinearFinder() { FinderInterface finder = new LinearFinder(); // probeprfung 2a // -2/3x + 5 // result = 7.5 PolyFunction f1 = new PolyFunction(). setKoeff(1, -2.0/3.0). setKoeff(0, 5.0); try { assertEquals((Double) 7.5, finder.find(f1).firstElement()); } catch (InvalidFuncException e) { fail(); } } @Test public void testQuadricFinder() { FinderInterface finder = new QuadricFinder(); // probeprfung 2b // 1/2x^2 - 2x - 6 // results = -2, 6 PolyFunction f1 = new PolyFunction(). setKoeff(2, 0.5). setKoeff(1, -2.0). setKoeff(0, -6.0); try { Vector<Double> results = finder.find(f1); assertTrue(results.contains(-2.0)); assertTrue(results.contains(6.0)); } catch (InvalidFuncException e) { fail(); } } @Test public void testNewtonFinder1() { FinderInterface finder = new NewtonFinder(); // probeprfung 2e // x^3 - 3x - 2 // results = -1, 2 PolyFunction f1 = new PolyFunction(). setKoeff(3, 1.0). setKoeff(1, -3.0). setKoeff(0, -2.0); try { Vector<Double> results = finder.find(f1); assertTrue(results.contains(-1.0)); assertTrue(results.contains(2.0)); } catch (InvalidFuncException e) { fail(); } } @Test public void testNewtonFinder2() { FinderInterface finder = new NewtonFinder(); // result = 0 PolyFunction f1 = new PolyFunction(). setKoeff(3, 1.0); try { Vector<Double> results = finder.find(f1); assertEquals(1, results.size()); assertEquals((Double) 0.0, results.firstElement()); } catch (InvalidFuncException e) { fail(); } } @Test public void testNewtonFinder3() { FinderInterface finder = new NewtonFinder(); // -x^3 - 3x // result = 0 PolyFunction f1 = new PolyFunction(). setKoeff(3, -1.0). setKoeff(1, -3.0); try { Vector<Double> results = finder.find(f1); assertEquals(1, results.size()); assertEquals((Double) 0.0, results.firstElement()); } catch (InvalidFuncException e) { fail(); } } }
package sample.jline; import jline.console.ConsoleReader; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { ConsoleReader console = new ConsoleReader(); System.out.println(console.readLine((char)0)); } }
package benchmarking; import datamodel.CpuUsageResults; import org.apache.commons.io.input.ReversedLinesFileReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; public class CpuMonitoring implements MonitoringInterface { private final static Logger logger = LoggerFactory.getLogger(CpuMonitoring.class); private Calendar startTimeOfMonitoring; private Calendar endTimeOfMonitoring; @Override public void startMonitoring() { startTimeOfMonitoring = Calendar.getInstance(); startTimeOfMonitoring.add(Calendar.SECOND, -1); } @Override public void stopMonitoring() { endTimeOfMonitoring = Calendar.getInstance(); endTimeOfMonitoring.add(Calendar.SECOND, 1); } public CpuUsageResults parseForPid(long pid) { BufferedReader br = null; String line; List<String> cpuUsageResults = new ArrayList<String>(); try { Thread.sleep(1500); String strpath="/tmp/performanceMonitoring.log"; ReversedLinesFileReader reverseFileReader = new ReversedLinesFileReader(new File(strpath));; do { line = reverseFileReader.readLine(); if (line == null) { continue; } String[] splitedLine = line.split("\\s+"); if ((splitedLine.length >= 6) && // at least a timestamp, a pid and a % (splitedLine[0].trim().length() > 18)) { // a valid timestamp (date + time) String[] dateAndTime = splitedLine[0].split("_"); String date = dateAndTime[0]; String time = dateAndTime[1]; if (date.trim().length() == 0 || time.trim().length() == 0) { continue; } String[] dateSplit = date.split("/"); String[] timeSplit = time.split(":"); Calendar timeFromLog = Calendar.getInstance(); timeFromLog.set(Calendar.SECOND, Integer.parseInt(timeSplit[2])); timeFromLog.set(Calendar.MINUTE, Integer.parseInt(timeSplit[1])); timeFromLog.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeSplit[0])); timeFromLog.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateSplit[2])); timeFromLog.set(Calendar.MONTH, Integer.parseInt(dateSplit[1]) - 1); timeFromLog.set(Calendar.YEAR, Integer.parseInt(dateSplit[0])); if (timeFromLog.after(startTimeOfMonitoring) && timeFromLog.before(endTimeOfMonitoring) && isNumeric(splitedLine[1].trim())) { long resultsPid = Long.parseLong(splitedLine[1]); if (resultsPid == pid) { cpuUsageResults.add(splitedLine[2]); // PID is ok and time is ok } } // look untill the time read from log is before the process began if (timeFromLog.before(startTimeOfMonitoring)) { break; } } } while (line != null); reverseFileReader.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } Collections.reverse(cpuUsageResults); return new CpuUsageResults(pid, startTimeOfMonitoring, cpuUsageResults); } public CpuUsageResults parseForPidFromFileHead(long pid) { BufferedReader br = null; String line; List<String> cpuUsageResults = new ArrayList<String>(); try { // wait for 1 second before reading the file so that all data for PID is written in file Thread.sleep(1500); br = new BufferedReader(new FileReader("/tmp/everySecondMonitoring.txt")); while ((line = br.readLine()) != null) { String[] splitedLine = line.split("\\s+"); if ((splitedLine.length > 2) && // at least a timestamp, a pid and a % splitedLine[1].trim().length() > 0 && // the PID length is > 0 isNumeric(splitedLine[1].trim()) && // the PID is a number (splitedLine[0].trim().length() > 18)) { // a valid timestamp (date + time) long resultsPid = Long.parseLong(splitedLine[1]); if (resultsPid == pid) { String[] dateAndTime = splitedLine[0].split("_"); String date = dateAndTime[0]; String time = dateAndTime[1]; if (date.trim().length() == 0 || time.trim().length() == 0) { continue; } String[] dateSplit = date.split("/"); String[] timeSplit = time.split(":"); Calendar timeFromLog = Calendar.getInstance(); timeFromLog.set(Calendar.SECOND, Integer.parseInt(timeSplit[2])); timeFromLog.set(Calendar.MINUTE, Integer.parseInt(timeSplit[1])); timeFromLog.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeSplit[0])); timeFromLog.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateSplit[2])); timeFromLog.set(Calendar.MONTH, Integer.parseInt(dateSplit[1]) - 1); timeFromLog.set(Calendar.YEAR, Integer.parseInt(dateSplit[0])); if (timeFromLog.after(startTimeOfMonitoring) && timeFromLog.before(endTimeOfMonitoring)) { cpuUsageResults.add(splitedLine[2]); // PID is ok and time is ok } if (timeFromLog.after(endTimeOfMonitoring)) { // it is useless to look after the time the monitoring was stopped break; } } } } } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } catch (NumberFormatException e) { logger.error(e.getMessage(), e); } catch (ArrayIndexOutOfBoundsException e) { logger.error(e.getMessage(), e); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } finally { try { br.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } return new CpuUsageResults(pid, startTimeOfMonitoring, cpuUsageResults); } private boolean isNumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(str.charAt(i)) == false) { return false; } } return true; } }
package org.jboss.as.test.integration.jaxrs.validator; import java.net.URL; import java.util.concurrent.TimeUnit; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.jaxrs.packaging.war.WebXml; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) @RunAsClient @Ignore public class HibernateValidatorProviderTestCase { @Deployment(testable = false) public static Archive<?> deploy() { WebArchive war = ShrinkWrap.create(WebArchive.class, "jaxrsnoap.war"); war.addPackage(HttpRequest.class.getPackage()); war.addClasses(HibernateValidatorProviderTestCase.class, ValidatorModel.class, ValidatorResource.class); war.addAsWebInfResource(WebXml.get("<servlet-mapping>\n" + " <servlet-name>javax.ws.rs.core.Application</servlet-name>\n" +
package org.xwiki.url.internal; import java.util.List; import org.xwiki.resource.AbstractResourceReference; import org.xwiki.resource.ResourceReferenceHandler; import org.xwiki.resource.ResourceType; /** * The reference of a {@link ResourceReferenceHandler} leading to other sub-{@link ResourceReferenceHandler}s. * * @version $Id$ * @since 10.2RC1 */ public class ParentResourceReference extends AbstractResourceReference { private String rootPath; private String child; private List<String> childSegments; /** * Default constructor. * * @param rootPath the path starting with the child * @param child the child handler hint * @param pathSegments the rest of the path */ public ParentResourceReference(ResourceType type, String rootPath, String child, List<String> pathSegments) { setType(type); this.rootPath = rootPath; this.child = child; this.childSegments = pathSegments; } /** * @return the path starting with the child */ public String getRootPath() { return this.rootPath; } /** * @return the child hint */ public String getChild() { return this.child; } /** * @return the child path (elements after the child) */ public List<String> getPathSegments() { return this.childSegments; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("path = "); builder.append(getRootPath()); builder.append(", child = "); builder.append(getChild()); builder.append(", pathSegments = "); builder.append(getPathSegments()); return builder.toString(); } }
package com.camnter.mvvm.view; import android.app.Activity; import android.databinding.DataBindingUtil; import android.databinding.ViewDataBinding; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public abstract class MVVMFragment extends Fragment { protected View self; protected Activity activity; protected LayoutInflater inflater; protected ViewGroup container; protected ViewDataBinding rootBinding; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.activity = this.getActivity(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { this.onBeforeDataBinding(savedInstanceState); final int layoutId = this.getLayoutId(); if (layoutId == 0) return null; try { this.inflater = inflater; if (this.autoInflateView()) { this.rootBinding = DataBindingUtil.inflate(inflater, layoutId, container, false); } // binding success, but maybe this.contentViewBinding == null this.onCastingRootBinding(this.rootBinding); if (this.rootBinding != null) { this.self = this.rootBinding.getRoot(); } } catch (Exception e) { e.printStackTrace(); } // cast success this.baseFragmentInit(); this.onAfterDataBinding(savedInstanceState); // self may be null return this.self; } /** * default true * * @return auto ? */ protected boolean autoInflateView() { return true; } /** * Fill in layout id * * @return layout id */ protected abstract int getLayoutId(); /** * on casting root binding * * @param rootBinding rootBinding */ protected abstract void onCastingRootBinding( @Nullable final ViewDataBinding rootBinding); /** * on before data binding * * @param savedInstanceState savedInstanceState */ protected void onBeforeDataBinding(@Nullable final Bundle savedInstanceState) { // Nothing to do } /** * baseFragment init */ protected void baseFragmentInit() { // Nothing to do } /** * on after data binding * * @param savedInstanceState savedInstanceState */ protected abstract void onAfterDataBinding(@Nullable final Bundle savedInstanceState); }
package eu.bcvsolutions.idm.core.config.domain; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.unit.DataSize; import org.springframework.util.unit.DataUnit; import eu.bcvsolutions.idm.core.api.config.domain.AbstractConfiguration; import eu.bcvsolutions.idm.core.api.config.domain.IdentityConfiguration; import eu.bcvsolutions.idm.core.api.config.domain.PrivateIdentityConfiguration; import eu.bcvsolutions.idm.core.api.domain.ContractState; @Component("privateIdentityConfiguration") public class DefaultPrivateIdentityConfiguration extends AbstractConfiguration implements PrivateIdentityConfiguration { @Autowired private IdentityConfiguration publicConfiguration; @Override public IdentityConfiguration getPublicConfiguration() { return publicConfiguration; } @Override public long getProfileImageMaxFileSize() { String maxFileSize = getConfigurationService().getValue(PROPERTY_IDENTITY_PROFILE_IMAGE_MAX_FILE_SIZE); if (StringUtils.isBlank(maxFileSize)) { return DataSize.parse(DEFAULT_IDENTITY_PROFILE_IMAGE_MAX_FILE_SIZE).toBytes(); } return DataSize.parse(maxFileSize, DataUnit.BYTES).toBytes(); } @Override public boolean isCreateDefaultContractEnabled() { // new configuration - higher priority String newConfiguration = getConfigurationService().getValue(PROPERTY_IDENTITY_CREATE_DEFAULT_CONTRACT_ENABLED); if (StringUtils.isNotBlank(newConfiguration)) { return Boolean.parseBoolean(newConfiguration); } // backward compatible @SuppressWarnings("deprecation") String previousConfiguration = getConfigurationService().getValue(IdentityConfiguration.PROPERTY_IDENTITY_CREATE_DEFAULT_CONTRACT); if (StringUtils.isNotBlank(previousConfiguration)) { return Boolean.parseBoolean(previousConfiguration); } // default (same as previous) return DEFAULT_IDENTITY_CREATE_DEFAULT_CONTRACT_ENABLED; } @Override public String getCreateDefaultContractPosition() { return getConfigurationService().getValue(PROPERTY_IDENTITY_CREATE_DEFAULT_CONTRACT_POSITION, DEFAULT_IDENTITY_CREATE_DEFAULT_CONTRACT_POSITION); } @Override public Long getCreateDefaultContractExpiration() { return getConfigurationService().getLongValue(PROPERTY_IDENTITY_CREATE_DEFAULT_CONTRACT_EXPIRATION); } @Override public ContractState getCreateDefaultContractState() { String contractState = getConfigurationService().getValue(PROPERTY_IDENTITY_CREATE_DEFAULT_CONTRACT_STATE); if (StringUtils.isBlank(contractState)) { return null; } return ContractState.valueOf(contractState.trim().toUpperCase()); } }
package org.eclipse.birt.report.designer.ui.cubebuilder.dialog; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.aggregation.AggregationManager; import org.eclipse.birt.data.engine.api.aggregation.IAggrFunction; import org.eclipse.birt.data.engine.api.aggregation.IParameterDefn; import org.eclipse.birt.report.data.adapter.api.AdapterException; import org.eclipse.birt.report.data.adapter.api.DataAdapterUtil; import org.eclipse.birt.report.designer.data.ui.util.DataUtil; import org.eclipse.birt.report.designer.internal.ui.dialogs.expression.ExpressionButton; import org.eclipse.birt.report.designer.internal.ui.dialogs.helper.IDialogHelper; import org.eclipse.birt.report.designer.internal.ui.dialogs.helper.IDialogHelperProvider; import org.eclipse.birt.report.designer.internal.ui.util.ExpressionButtonUtil; import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.internal.ui.util.WidgetUtil; import org.eclipse.birt.report.designer.ui.cubebuilder.nls.Messages; import org.eclipse.birt.report.designer.ui.cubebuilder.provider.CubeACLExpressionProvider; import org.eclipse.birt.report.designer.ui.cubebuilder.provider.CubeMeasureExpressionProvider; import org.eclipse.birt.report.designer.ui.cubebuilder.provider.LinkToCubeExpressionProvider; import org.eclipse.birt.report.designer.ui.cubebuilder.util.BuilderConstants; import org.eclipse.birt.report.designer.ui.dialogs.BaseTitleAreaDialog; import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider; import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory; import org.eclipse.birt.report.designer.ui.util.ExceptionUtil; import org.eclipse.birt.report.designer.ui.views.ElementAdapterManager; import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory; import org.eclipse.birt.report.designer.util.AlphabeticallyComparator; import org.eclipse.birt.report.designer.util.ColorManager; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.Expression; import org.eclipse.birt.report.model.api.ExpressionHandle; import org.eclipse.birt.report.model.api.ExpressionType; import org.eclipse.birt.report.model.api.FormatValueHandle; import org.eclipse.birt.report.model.api.PropertyHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.ReportDesignConstants; import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn; import org.eclipse.birt.report.model.api.elements.structures.FormatValue; import org.eclipse.birt.report.model.api.metadata.IChoice; import org.eclipse.birt.report.model.api.olap.MeasureHandle; import org.eclipse.birt.report.model.elements.interfaces.IMeasureModel; import org.eclipse.birt.report.model.elements.olap.Measure; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import com.ibm.icu.util.ULocale; public class MeasureDialog extends BaseTitleAreaDialog { private static final String ARGUMENT_EXPRESSION = "Expression"; private boolean isEdit = false; private boolean isAutoPrimaryKeyChecked = false; private CubeMeasureExpressionProvider provider; private Combo typeCombo; private Text expressionText; private Text txtFilter; private Button derivedMeasureBtn, visibilityBtn; private Label exprDesc; private FunctionUI functionUI; private MeasureHandle input; private Text nameText; private static IChoice[] dataTypes = DEUtil.getMetaDataDictionary( ) .getElement( ReportDesignConstants.MEASURE_ELEMENT ) .getProperty( IMeasureModel.DATA_TYPE_PROP ) .getAllowedChoices( ) .getChoices( ); private Object result; private IDialogHelper securityHelper; private IDialogHelper formatHelper; private IDialogHelper alignmentHelper; private IMeasureDialogHelper measureHelper; private Text displayNameText; public MeasureDialog( boolean newOrEdit ) { super( UIUtil.getDefaultShell( ) ); setShellStyle( getShellStyle( ) | SWT.RESIZE | SWT.MAX ); this.isEdit = !newOrEdit; } private String[] getDataTypeNames( ) { IChoice[] choices = dataTypes; if ( choices == null ) return new String[0]; String[] names = new String[choices.length]; for ( int i = 0; i < choices.length; i++ ) { names[i] = choices[i].getName( ); } return names; } private String getDataTypeDisplayName( String name ) { return ChoiceSetFactory.getDisplayNameFromChoiceSet( name, DEUtil.getMetaDataDictionary( ) .getElement( ReportDesignConstants.MEASURE_ELEMENT ) .getProperty( IMeasureModel.DATA_TYPE_PROP ) .getAllowedChoices( ) ); } private String[] getDataTypeDisplayNames( ) { IChoice[] choices = dataTypes; if ( choices == null ) return new String[0]; String[] displayNames = new String[choices.length]; for ( int i = 0; i < choices.length; i++ ) { displayNames[i] = choices[i].getDisplayName( ); } return displayNames; } public void setInput( MeasureHandle input ) { this.input = input; } public void setAutoPrimaryKeyStatus( boolean isChecked ) { this.isAutoPrimaryKeyChecked = isChecked; } @Override protected Control createDialogArea( Composite parent ) { UIUtil.bindHelp( parent, IHelpContextIds.MEASURE_DIALOG ); Composite area = (Composite) super.createDialogArea( parent ); ScrolledComposite sc = new ScrolledComposite( area, SWT.V_SCROLL ); sc.setAlwaysShowScrollBars( false ); sc.setExpandHorizontal( true ); sc.setLayoutData( new GridData( GridData.FILL_BOTH ) ); Composite contents = new Composite( sc, SWT.NONE); sc.setContent( contents ); GridLayout layout = new GridLayout( ); layout.verticalSpacing = 0; layout.marginWidth = 20; contents.setLayout( layout ); GridData data = new GridData( GridData.FILL_BOTH ); data.widthHint = convertWidthInCharsToPixels( 70 ); contents.setLayoutData( data ); createMeasureArea( contents ); createVisibilityGroup( contents); WidgetUtil.createGridPlaceholder( contents, 1, true ); initMeasureDialog( ); // calculate the size explicitly as it is in scrollable composite Point size = contents.computeSize( SWT.DEFAULT, SWT.DEFAULT ); contents.setSize( Math.max( size.x, 400 ), Math.max( size.y, 320 ) ); return contents; } protected Control createContents( Composite parent ) { Control control = super.createContents( parent ); setTitle( Messages.getString( "MeasureDialog.Title.Description" ) ); //$NON-NLS-1$ setMessage( Messages.getString( "MeasureDialog.Text.Description" ) ); //$NON-NLS-1$ return control; } private void initMeasureDialog( ) { functionUI.initUI( ); typeCombo.setItems( getDataTypeDisplayNames( ) ); if ( !isEdit ) { if ( typeCombo.getItemCount( ) > 0 ) { typeCombo.select( 0 ); } handleFunctionSelectEvent( ); } else { try { String funcName = DataAdapterUtil.adaptModelAggregationType( input.getFunction( ) ); Map<String, Expression> arguments = getArguments( input ); ExpressionHandle argExpr = input.getExpressionProperty( Measure.MEASURE_EXPRESSION_PROP ); functionUI.setAggregation( funcName, arguments, (Expression) argExpr.getValue( ) ); } catch ( AdapterException e ) { ExceptionUtil.handle( e ); } ExpressionButtonUtil.initExpressionButtonControl( expressionText, input, MeasureHandle.MEASURE_EXPRESSION_PROP ); nameText.setText( input.getName( ) == null ? "" : input.getName( ) ); //$NON-NLS-1$ displayNameText.setText( input.getDisplayName( ) == null ? "" : input.getDisplayName( ) ); //$NON-NLS-1$ handleFunctionSelectEvent( ); typeCombo.setText( getDataTypeDisplayName( input.getDataType( ) ) == null ? "" //$NON-NLS-1$ : getDataTypeDisplayName( input.getDataType( ) ) ); derivedMeasureBtn.setSelection( input.isCalculated( ) ); updateDerivedMeasureStatus( ); } if ( measureHelper != null && measureHelper.hasFilter( input ) ) { Expression filterExpr = measureHelper.getFilter( input ); if ( filterExpr != null ) { ExpressionButtonUtil.initExpressionButtonControl( txtFilter, filterExpr ); } } if ( formatHelper != null ) { if ( typeCombo.getSelectionIndex( ) > -1 ) { formatHelper.setProperty( BuilderConstants.FORMAT_VALUE_TYPE, getDataTypeNames( )[typeCombo.getSelectionIndex( )] ); } formatHelper.update( true ); } if ( alignmentHelper != null ) { if ( input.getAlignment( ) != null ) { alignmentHelper.setProperty( BuilderConstants.ALIGNMENT_VALUE, input.getAlignment( ) ); } else if ( !isEdit && input.getDataType( ) != null ) { if ( isNumber( input.getDataType( ) ) ) { alignmentHelper.setProperty( BuilderConstants.ALIGNMENT_VALUE, DesignChoiceConstants.TEXT_ALIGN_RIGHT ); } else { alignmentHelper.setProperty( BuilderConstants.ALIGNMENT_VALUE, DesignChoiceConstants.TEXT_ALIGN_LEFT ); } } alignmentHelper.update( true ); } } private boolean isNumber( String dataType ) { return ( DesignChoiceConstants.COLUMN_DATA_TYPE_DECIMAL.equals( dataType ) || DesignChoiceConstants.COLUMN_DATA_TYPE_FLOAT.equals( dataType ) || DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER.equals( dataType ) ); } public Object getResult( ) { return result; } private boolean hasFilter( MeasureHandle measure ) { if ( measureHelper != null) { return measureHelper.hasFilter( measure ); } return false; } private Expression getFilter( MeasureHandle measure ) { if ( this.measureHelper != null ) { return measureHelper.getFilter( measure ); } return null; } private void setFilter( MeasureHandle measure, Expression expr ) throws SemanticException { if ( this.measureHelper != null ) { measureHelper.setFilter( measure, expr ); } } private Map<String, Expression> getArguments( MeasureHandle measure ) { if ( measureHelper != null ) { return measureHelper.getArguments( measure ); } return null; } private void setArguments( MeasureHandle measure, Map<String, Expression> arguments ) throws SemanticException { if ( measureHelper != null ) { measureHelper.setArguments( measure, arguments ); } } private MeasureHandle createMeasure( String name ) throws SemanticException { if ( this.measureHelper != null ) { return measureHelper.createMeasure( name ); } return DesignElementFactory.getInstance( ).newTabularMeasure( nameText.getText( ) ); } @Override protected void okPressed( ) { try { MeasureHandle measure = input; if ( measure == null ) { measure = createMeasure( nameText.getText( ).trim( ) ); } else { input.setName( nameText.getText( ).trim( ) ); } if ( displayNameText.getText( ).trim( ).length( ) > 0 ) { measure.setDisplayName( displayNameText.getText( ).trim( ) ); } else { measure.setDisplayName( null ); } measure.setCalculated( derivedMeasureBtn.getSelection( ) ); if ( derivedMeasureBtn.getSelection( ) ) { measure.setFunction( null ); setArguments( measure, null ); } else { IAggrFunction func = functionUI.getSelectedFunction( ); if ( func != null ) { String modelFuncName = DataAdapterUtil.toModelAggregationType( func.getName( ) ); measure.setFunction( modelFuncName ); } setArguments( measure, functionUI.getArguments( ) ); } measure.setDataType( getDataTypeNames( )[typeCombo.getSelectionIndex( )] ); if ( expressionText.isEnabled( ) ) { ExpressionButtonUtil.saveExpressionButtonControl( expressionText, measure, MeasureHandle.MEASURE_EXPRESSION_PROP ); } if ( !derivedMeasureBtn.getSelection( ) ) { if ( securityHelper != null ) { securityHelper.validate( ); measure.setExpressionProperty( MeasureHandle.ACL_EXPRESSION_PROP, (Expression) securityHelper.getProperty( BuilderConstants.SECURITY_EXPRESSION_PROPERTY ) ); } if ( hasFilter( measure ) ) { setFilter( measure, ExpressionButtonUtil.getExpression( txtFilter ) ); } } else { measure.setExpressionProperty( MeasureHandle.ACL_EXPRESSION_PROP, null ); if ( hasFilter( measure ) ) { setFilter( measure, null ); } } if ( alignmentHelper != null ) { measure.setAlignment( (String) alignmentHelper.getProperty( BuilderConstants.ALIGNMENT_VALUE ) ); } if ( formatHelper != null && formatHelper.getProperty( BuilderConstants.FORMAT_VALUE_RESULT ) instanceof Object[] ) { Object[] formatValue = (Object[]) formatHelper.getProperty( BuilderConstants.FORMAT_VALUE_RESULT ); Object value = measure.getProperty( Measure.FORMAT_PROP ); if ( value == null ) { FormatValue formatValueToSet = new FormatValue( ); formatValueToSet.setCategory( (String) formatValue[0] ); formatValueToSet.setPattern( (String) formatValue[1] ); formatValueToSet.setLocale( (ULocale) formatValue[2] ); measure.setProperty( Measure.FORMAT_PROP, formatValueToSet ); } else { PropertyHandle propHandle = measure.getPropertyHandle( Measure.FORMAT_PROP ); FormatValue formatValueToSet = (FormatValue) value; FormatValueHandle formatHandle = (FormatValueHandle) formatValueToSet.getHandle( propHandle ); formatHandle.setCategory( (String) formatValue[0] ); formatHandle.setPattern( (String) formatValue[1] ); formatHandle.setLocale( (ULocale) formatValue[2] ); } } measure.setVisible( !visibilityBtn.getSelection( ) ); result = measure; } catch ( SemanticException e ) { ExceptionUtil.handle( e ); return; } super.okPressed( ); } protected void createButtonsForButtonBar( Composite parent ) { super.createButtonsForButtonBar( parent ); checkOkButtonStatus( ); } private Composite createMeasureArea( Composite parent ) { DesignElementHandle container = input.getContainer( ); DesignElementHandle superContainer = container.getContainer( ); this.measureHelper = (IMeasureDialogHelper) ElementAdapterManager .getAdapter( superContainer, IMeasureDialogHelper.class ); getShell( ).setText( Messages.getString( "MeasureDialog.Title.Property" ) ); //$NON-NLS-1$ Group group = new Group( parent, SWT.NONE ); GridData gd = new GridData( ); gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = SWT.FILL; group.setLayoutData( gd ); GridLayout layout = new GridLayout( ); layout.numColumns = 3; group.setLayout( layout ); Label nameLabel = new Label( group, SWT.NONE ); nameLabel.setText( Messages.getString( "MeasureDialog.Label.Name" ) ); //$NON-NLS-1$ nameText = new Text( group, SWT.BORDER ); gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 2; nameText.setLayoutData( gd ); nameText.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { checkOkButtonStatus( ); } } ); Label displayNameLabel = new Label( group, SWT.NONE ); displayNameLabel.setText( Messages.getString( "MeasureDialog.Label.DisplayName" ) ); //$NON-NLS-1$ displayNameText = new Text( group, SWT.BORDER ); gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 2; displayNameText.setLayoutData( gd ); displayNameText.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { checkOkButtonStatus( ); } } ); new Label( group, SWT.NONE ); derivedMeasureBtn = new Button( group, SWT.CHECK ); derivedMeasureBtn.setText( Messages.getString( "MeasureDialog.Label.DerivedMeasure" ) ); //$NON-NLS-1$ derivedMeasureBtn.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { updateDerivedMeasureStatus( ); if ( !derivedMeasureBtn.getSelection( ) ) { handleTypeSelectEvent( ); } checkOkButtonStatus(); } } ); new Label( group, SWT.NONE ); functionUI = createFunctionUI( group ); functionUI.createUI( ); Label typeLabel = new Label( group, SWT.NONE ); typeLabel.setText( Messages.getString( "MeasureDialog.Label.DataType" ) ); //$NON-NLS-1$ typeCombo = new Combo( group, SWT.BORDER | SWT.READ_ONLY ); gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 2; typeCombo.setLayoutData( gd ); typeCombo.setVisibleItemCount( 30 ); typeCombo.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { if ( !derivedMeasureBtn.getSelection( ) ) { handleTypeSelectEvent( ); } checkOkButtonStatus( ); if ( formatHelper != null ) { if ( typeCombo.getSelectionIndex( ) > -1 ) formatHelper.setProperty( BuilderConstants.FORMAT_VALUE_TYPE, getDataTypeNames( )[typeCombo.getSelectionIndex( )] ); formatHelper.update( true ); } } } ); Label expressionLabel = new Label( group, SWT.NONE ); expressionLabel.setText( Messages.getString( "MeasureDialog.Label.Expression" ) ); //$NON-NLS-1$ expressionText = new Text( group, SWT.BORDER | SWT.MULTI ); gd = new GridData( GridData.FILL_HORIZONTAL ); gd.heightHint = expressionText.computeSize( SWT.DEFAULT, SWT.DEFAULT ).y - expressionText.getBorderWidth( ) * 2; expressionText.setLayoutData( gd ); expressionText.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { checkOkButtonStatus( ); } } ); if ( measureHelper != null ) { provider = measureHelper.getExpressionProvider( input ); } else { provider = new CubeMeasureExpressionProvider( input, input.isCalculated( ) ); } ExpressionButtonUtil.createExpressionButton( group, expressionText, provider, input ); new Label( group, SWT.NONE ); exprDesc = new Label( group, SWT.NONE ); gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 2; gd.grabExcessHorizontalSpace = true; exprDesc.setLayoutData( gd ); exprDesc.setText( Messages.getString( Messages.getString( derivedMeasureBtn.getSelection( ) ? "MeasureDialog.Label.ExprDesc.Derived" : "MeasureDialog.Label.ExprDesc" ) ) ); //$NON-NLS-1$ //$NON-NLS-2$ exprDesc.setForeground( ColorManager.getColor( 128, 128, 128 ) ); // new Label( group, SWT.NONE ); if ( hasFilter( input ) ) { createFilterPart( group ); } if ( measureHelper == null || !measureHelper.hideSecurityPart( ) ) { createSecurityPart( group ); } if ( measureHelper == null || !measureHelper.hideHyperLinkPart( ) ) { createHyperLinkPart( group ); } if ( measureHelper == null || !measureHelper.hideFormatPart( ) ) { createFormatPart( group ); } if ( measureHelper == null || !measureHelper.hideAlignmentPart( ) ) { createAlignmentPart( group ); } return group; } private Composite createVisibilityGroup( Composite parent ) { Group group = new Group( parent, SWT.NONE ); GridData gd = new GridData( ); gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = SWT.FILL; group.setLayoutData( gd ); GridLayout layout = new GridLayout( ); layout.numColumns = 2; group.setLayout( layout ); group.setText( Messages.getString( "MeasureDialog.Label.Visibility.Group" ) ); //$NON-NLS-1$ visibilityBtn = new Button( group, SWT.CHECK ); visibilityBtn.setText( Messages.getString( "MeasureDialog.Label.Visibility" ) ); //$NON-NLS-1$ visibilityBtn.setSelection( !input.isVisible( ) ); return group; } private IDialogHelper createHyperLinkPart( Composite parent ) { Object[] helperProviders = ElementAdapterManager.getAdapters( input, IDialogHelperProvider.class ); if ( helperProviders != null ) { for ( int i = 0; i < helperProviders.length; i++ ) { IDialogHelperProvider helperProvider = (IDialogHelperProvider) helperProviders[i]; if ( helperProvider != null ) { final IDialogHelper hyperLinkHelper = helperProvider.createHelper( this, BuilderConstants.HYPERLINK_HELPER_KEY ); if ( hyperLinkHelper != null ) { hyperLinkHelper.setProperty( BuilderConstants.HYPERLINK_LABEL, Messages.getString( "MeasureDialog.Label.LinkTo" ) ); //$NON-NLS-1$ hyperLinkHelper.setProperty( BuilderConstants.HYPERLINK_BUTTON_TEXT, Messages.getString( "MeasureDialog.Button.Text.Edit" ) ); //$NON-NLS-1$ hyperLinkHelper.setProperty( BuilderConstants.HYPERLINK_REPORT_ITEM_HANDLE, input ); hyperLinkHelper.setProperty( BuilderConstants.HYPERLINK_REPORT_ITEM_PROVIDER, new LinkToCubeExpressionProvider( input ) ); hyperLinkHelper.createContent( parent ); hyperLinkHelper.addListener( SWT.Modify, new Listener( ) { public void handleEvent( Event event ) { hyperLinkHelper.update( false ); } } ); hyperLinkHelper.update( true ); return hyperLinkHelper; } } } } return null; } private IDialogHelper createFormatPart( Composite parent ) { Object[] helperProviders = ElementAdapterManager.getAdapters( input, IDialogHelperProvider.class ); if ( helperProviders != null ) { for ( int i = 0; i < helperProviders.length; i++ ) { IDialogHelperProvider helperProvider = (IDialogHelperProvider) helperProviders[i]; if ( helperProvider != null ) { formatHelper = helperProvider.createHelper( this, BuilderConstants.FORMAT_HELPER_KEY ); if ( formatHelper != null ) { formatHelper.setProperty( BuilderConstants.FORMAT_LABEL, Messages.getString( "MeasureDialog.Label.Format" ) ); //$NON-NLS-1$ formatHelper.setProperty( BuilderConstants.FORMAT_BUTTON_TEXT, Messages.getString( "MeasureDialog.Button.Format.Edit" ) ); //$NON-NLS-1$ PropertyHandle propHandle = input.getPropertyHandle( Measure.FORMAT_PROP ); if ( input.getProperty( Measure.FORMAT_PROP ) != null ) { Object value = input.getProperty( Measure.FORMAT_PROP ); FormatValue formatValueToSet = (FormatValue) value; FormatValueHandle formatHandle = (FormatValueHandle) formatValueToSet.getHandle( propHandle ); formatHelper.setProperty( BuilderConstants.FORMAT_VALUE, formatHandle ); } formatHelper.createContent( parent ); formatHelper.update( true ); return formatHelper; } } } } return null; } private IDialogHelper createAlignmentPart( Composite parent ) { Object[] helperProviders = ElementAdapterManager.getAdapters( input, IDialogHelperProvider.class ); if ( helperProviders != null ) { for ( int i = 0; i < helperProviders.length; i++ ) { IDialogHelperProvider helperProvider = (IDialogHelperProvider) helperProviders[i]; if ( helperProvider != null ) { alignmentHelper = helperProvider.createHelper( this, BuilderConstants.ALIGNMENT_HELPER_KEY ); if ( alignmentHelper != null ) { alignmentHelper.setProperty( BuilderConstants.ALIGNMENT_LABEL, Messages.getString( "MeasureDialog.Label.Alignment" ) ); //$NON-NLS-1$ alignmentHelper.setProperty( BuilderConstants.ALIGNMENT_VALUE, input.getAlignment( ) ); alignmentHelper.createContent( parent ); alignmentHelper.update( true ); return alignmentHelper; } } } } return null; } private void createSecurityPart( Composite parent ) { Object[] helperProviders = ElementAdapterManager.getAdapters( input, IDialogHelperProvider.class ); if ( helperProviders != null ) { for ( int i = 0; i < helperProviders.length; i++ ) { IDialogHelperProvider helperProvider = (IDialogHelperProvider) helperProviders[i]; if ( helperProvider != null && securityHelper == null ) { securityHelper = helperProvider.createHelper( this, BuilderConstants.SECURITY_HELPER_KEY ); if ( securityHelper != null ) { securityHelper.setProperty( BuilderConstants.SECURITY_EXPRESSION_LABEL, Messages.getString( "MeasureDialog.Access.Control.List.Expression" ) ); //$NON-NLS-1$ securityHelper.setProperty( BuilderConstants.SECURITY_EXPRESSION_CONTEXT, input ); securityHelper.setProperty( BuilderConstants.SECURITY_EXPRESSION_PROVIDER, new CubeACLExpressionProvider( input ) ); securityHelper.setProperty( BuilderConstants.SECURITY_EXPRESSION_PROPERTY, input.getACLExpression( ) ); securityHelper.createContent( parent ); securityHelper.addListener( SWT.Modify, new Listener( ) { public void handleEvent( Event event ) { securityHelper.update( false ); } } ); securityHelper.update( true ); } } } } } private void createFilterPart( Composite composite ) { new Label( composite, SWT.NONE ).setText( Messages.getString( "MeasureDialog.Label.Filter" ) ); //$NON-NLS-1$ txtFilter = new Text( composite, SWT.BORDER | SWT.MULTI ); GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.heightHint = txtFilter.computeSize( SWT.DEFAULT, SWT.DEFAULT ).y - txtFilter.getBorderWidth( ) * 2; gd.horizontalSpan = 1; txtFilter.setLayoutData( gd ); txtFilter.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent arg0 ) { checkOkButtonStatus( ); } } ); ExpressionButtonUtil.createExpressionButton( composite, txtFilter, provider, input ); } protected void handleTypeSelectEvent( ) { IAggrFunction function = functionUI.getSelectedFunction( ); if ( function == null ) return; int returnType = function.getDataType( ); String typeName = DataAdapterUtil.adapterToModelDataType( returnType ); String recommendType = getDataTypeDisplayName( typeName ); //recommendType may be any, which is not in the type list if ( !typeCombo.getText( ).equals( recommendType ) && typeCombo.indexOf( recommendType ) != -1 ) { if ( !MessageDialog.openQuestion( getShell( ), Messages.getString( "MeasureDialog.MessageDialog.Title" ), //$NON-NLS-1$ Messages.getFormattedString( "MeasureDialog.MessageDialog.Message", //$NON-NLS-1$ new Object[]{ recommendType } ) ) ) typeCombo.setText( recommendType ); } } private FunctionProvider createFuncProvider( ) { IAggrFunction[] funcs = null; if ( measureHelper != null ) { funcs = measureHelper.getAggregationFunctions( input ); } else { try { @SuppressWarnings("unchecked") List<IAggrFunction> aggrInfoList = DataUtil.getAggregationManager( ) .getAggregations( AggregationManager.AGGR_MEASURE ); funcs = (IAggrFunction[]) aggrInfoList.toArray( new IAggrFunction[0] ); } catch ( BirtException e ) { ExceptionUtil.handle( e ); funcs = new IAggrFunction[0]; } } return new FunctionProvider( funcs ); } protected Runnable createFunctionUICallback( ) { return new Runnable( ) { public void run( ) { handleFunctionSelectEvent( ); checkOkButtonStatus( ); } }; } protected FunctionUI createFunctionUI( Composite composite ) { FunctionProvider funcProvider = createFuncProvider( ); Runnable callback = createFunctionUICallback( ); FunctionUI ui = new FunctionUI( composite, input, funcProvider, provider, null, callback ); return ui; } protected void createFunctionUIPart( Composite composite ) { functionUI = createFunctionUI( composite); functionUI.createUI( ); functionUI.initUI(); } private void handleFunctionSelectEvent( ) { IAggrFunction func = functionUI.getSelectedFunction( ); if ( func == null ) return; int returnType = func.getDataType( ); String typeName = DataAdapterUtil.adapterToModelDataType( returnType ); String typeDisplayText = getDataTypeDisplayName( typeName ); typeCombo.setText( typeDisplayText ); int parameterLength = func.getParameterDefn( ).length; expressionText.setEnabled( parameterLength > 0 ); ( (ExpressionButton) expressionText.getData( ExpressionButtonUtil.EXPR_BUTTON ) ) .setEnabled( parameterLength > 0 ); } private boolean isValidExpression( Expression expr ) { return expr != null && expr.getStringExpression( ) != null && expr.getStringExpression( ).trim( ).length( ) != 0; } protected String checkExpression( ) { if ( expressionText.getText( ) == null || expressionText.getText( ).trim( ).length( ) == 0 ) { return Messages.getString( "MeasureDialog.Message.BlankExpression" ); //$NON-NLS-1$ } if ( !this.derivedMeasureBtn.getSelection( ) ) { IAggrFunction function = functionUI.getSelectedFunction( ); if ( function == null ) { return Messages.getString( "MeasureDialog.Message.BlankFunction" ); //$NON-NLS-1$ } IParameterDefn[] paramDefs = function.getParameterDefn( ); if ( paramDefs != null ) { Map<String, Expression> argValues = functionUI.getArguments( ); for ( IParameterDefn paramDef : paramDefs ) { if ( !paramDef.isOptional( ) ) { String argName = DataAdapterUtil.adaptArgumentName( paramDef.getName( ) ); // ARGUMENT_EXPRESSION is defined in expressionText if ( !ARGUMENT_EXPRESSION.equals( argName ) ) { Expression value = argValues.get( argName ); if ( !isValidExpression( value ) ) { return Messages .getFormattedString( "MessageDialog.Message.BlankArgument", //$NON-NLS-1$ new String[]{paramDef.getDisplayName( ) .replaceAll( "\\(&[a-zA-Z0-9]\\)", "" ) .replaceAll( "&", "" )} ); } } } } } } return null; } private String checkName( ) { if ( nameText.getText( ) == null || nameText.getText( ).trim( ).equals( "" ) ) //$NON-NLS-1$ { return Messages.getString( "MeasureDialog.Message.BlankName" ); //$NON-NLS-1$ } if ( !UIUtil.validateDimensionName( nameText.getText( ) ) ) { return Messages.getString( "MeasureDialog.Message.NumericName" ); //$NON-NLS-1$ } return null; } private String checkType( ) { if ( typeCombo.getSelectionIndex( ) == -1 ) { return Messages.getString( "MeasureDialog.Message.BlankType" ); //$NON-NLS-1$ } return null; } protected void checkOkButtonStatus( ) { String errorMessage = null; if ( ( errorMessage = checkName( ) ) == null ) { if ( ( errorMessage = checkType( ) ) == null ) { if ( ( errorMessage = checkExpression( ) ) == null ) { if ( getButton( IDialogConstants.OK_ID ) != null ) { getButton( IDialogConstants.OK_ID ).setEnabled( true ); setErrorMessage( null ); setMessage( Messages.getString( "MeasureDialog.Text.Description" ) ); //$NON-NLS-1$ return; } } } } // there are errors here if ( getButton( IDialogConstants.OK_ID ) != null ) { getButton( IDialogConstants.OK_ID ).setEnabled( false ); setMessage( null ); setErrorMessage( errorMessage ); } } private void updateDerivedMeasureStatus( ) { boolean isDerivedMeasure = derivedMeasureBtn.getSelection( ); if ( txtFilter != null ) { txtFilter.setEnabled( !isDerivedMeasure ); } functionUI.setEnabled( !( isDerivedMeasure || isAutoPrimaryKeyChecked ) ); if ( securityHelper != null ) { securityHelper.setProperty( BuilderConstants.SECURITY_EXPRESSION_ENABLE, !isDerivedMeasure ); securityHelper.update( true ); } exprDesc.setText( Messages.getString( isDerivedMeasure ? "MeasureDialog.Label.ExprDesc.Derived" : "MeasureDialog.Label.ExprDesc" ) ); //$NON-NLS-1$ //$NON-NLS-2$ provider.setDerivedMeasure( isDerivedMeasure ); } protected static class FunctionUI { static final String FUNCTION = Messages.getString( "MeasureDialog.Label.Function" ) ; //$NON-NLS-1$ protected Composite parent; private Combo cmbFunction; private Composite paramsComposite; private Map<String, Control> paramsMap = new HashMap<String, Control>( ); private DesignElementHandle bindingHolder; private ExpressionProvider exprProvider; private FunctionProvider funcProvider; private ComputedColumn[] bindings; private Runnable callback; private Map<String, Expression> paramsValueMap = new HashMap<String, Expression>( ); public FunctionUI( Composite parent, DesignElementHandle bindingHolder, FunctionProvider funcProvider, ExpressionProvider exprProvider, ComputedColumn[] bindings, Runnable callback ) { this.parent = parent; this.bindingHolder = bindingHolder; this.exprProvider = exprProvider; this.funcProvider = funcProvider; this.bindings = bindings; this.callback = callback; } /** * the initial defined function name. * * The name is saved in report design. * * @param functions */ public void setAggregation( String funcName, Map<String, Expression> args, Expression expr ) { IAggrFunction func = funcProvider.getFunction( funcName ); cmbFunction.setText( func == null ? "" : func.getDisplayName( ) ); //$NON-NLS-1$ if ( args != null ) { paramsValueMap.putAll( args ); } updateArgumentUI( ); } public void setEnabled( boolean enabled ) { cmbFunction.setEnabled( enabled ); paramsComposite.setEnabled( enabled ); } /** * selected aggregate function. * * @return */ public IAggrFunction getSelectedFunction( ) { String displayText = cmbFunction.getText( ); return funcProvider.getFunctionByDisplayText( displayText ); } public String getSelectedFunctionName( ) { IAggrFunction func = getSelectedFunction( ); return func == null ? "" : func.getName( ); //$NON-NLS-1$ ; } /** * Arguments of the function. * * @return */ public Map<String, Expression> getArguments( ) { HashMap<String, Expression> results = new HashMap<String, Expression>( ); for ( String argName : paramsMap.keySet( ) ) { Control control = paramsMap.get( argName ); Expression expr = ExpressionButtonUtil.getExpression( control ); results.put( argName, expr ); } return results; } private int getParentLayoutColumns( ) { assert parent.getLayout( ) instanceof GridLayout; Layout layout = parent.getLayout( ); if ( layout instanceof GridLayout ) { return ( (GridLayout) layout ).numColumns; } return 3; } public void createUI( ) { //assume the parent has grid layout with 4 columns. int columns = getParentLayoutColumns(); new Label( parent, SWT.NONE ).setText( FUNCTION ); cmbFunction = new Combo( parent, SWT.BORDER | SWT.READ_ONLY ); GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = gd.horizontalSpan = columns - 1; cmbFunction.setLayoutData( gd ); cmbFunction.setVisibleItemCount( 30 ); // WidgetUtil.createGridPlaceholder( composite, 1, false ); cmbFunction.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { String funcText = cmbFunction.getText( ); IAggrFunction func = funcProvider.getFunctionByDisplayText( funcText ); if ( func != null ) { updateArgumentUI( ); callback.run( ); } } } ); paramsComposite = new Composite( parent, SWT.NONE ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalIndent = 0; gridData.horizontalSpan = columns; gridData.exclude = true; paramsComposite.setLayoutData( gridData ); GridLayout layout = new GridLayout( ); layout.marginWidth = layout.marginHeight = 0; layout.numColumns = 3; Layout parentLayout = parent.getLayout( ); if ( parentLayout instanceof GridLayout ) layout.horizontalSpacing = ( (GridLayout) parentLayout ).horizontalSpacing; paramsComposite.setLayout( layout ); } private void initUI( ) { // initiate function UI cmbFunction.setItems( funcProvider.getDisplayTexts( ) ); cmbFunction.select( 0 ); // create argument UI part updateArgumentUI( ); } private void resetArgumentUI( ) { Control[] children = paramsComposite.getChildren( ); for ( int i = 0; i < children.length; i++ ) { children[i].dispose( ); } paramsMap.clear( ); // don't display the parameter ( (GridData) paramsComposite.getLayoutData( ) ).exclude = true; ( (GridData) paramsComposite.getLayoutData( ) ).heightHint = 0; } private int getMaxLabelWidth( Composite parent ) { int maxWidth = 0; Control[] controls = parent.getChildren( ); for ( int i = 0; i < controls.length; i++ ) { if ( controls[i] instanceof Label ) { int labelWidth = getLabelWidth( (Label) controls[i] ); if ( labelWidth > maxWidth ) { maxWidth = labelWidth; } } } return maxWidth; } private int getLabelWidth( Label label ) { Object layout = label.getLayoutData( ); if ( layout instanceof GridData ) { if ( ( (GridData) layout ).horizontalSpan == 1 ) { return label.getBounds( ).width - label.getBorderWidth( ) * 2; } } return 0; } private void createArgumentUI( ) { IAggrFunction function = getSelectedFunction( ); if ( function != null ) { IParameterDefn[] params = function.getParameterDefn( ); if ( params != null && params.length > 0 ) { ( (GridData) paramsComposite.getLayoutData( ) ).exclude = false; ( (GridData) paramsComposite.getLayoutData( ) ).heightHint = SWT.DEFAULT; int width = getMaxLabelWidth( parent ); for ( final IParameterDefn param : params ) { String paramName = DataAdapterUtil.adaptArgumentName(param.getName( ) ); //Expression is handled as measureExpression if ( ARGUMENT_EXPRESSION.equals( paramName ) ) { continue; } Label lblParam = new Label( paramsComposite, SWT.NONE ); lblParam.setText( param.getDisplayName( ) + Messages.getString( "MeasureDialog.Text.Colon" ) ); //$NON-NLS-1$ GridData gd = new GridData( ); gd.widthHint = lblParam.computeSize( SWT.DEFAULT, SWT.DEFAULT ).x; if ( gd.widthHint < width ) gd.widthHint = width; lblParam.setLayoutData( gd ); if ( param.isDataField( ) ) { createComboControl( paramsComposite, param ); } else { createTextControl( paramsComposite, param ); } } } } } private void createComboControl( Composite paramsComposite, final IParameterDefn param ) { assert param.isDataField( ); final Combo cmbDataField = new Combo( paramsComposite, SWT.BORDER ); cmbDataField.setLayoutData( new GridData( GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL ) ); cmbDataField.setVisibleItemCount( 30 ); createExpressionButton( paramsComposite, cmbDataField, param ); paramsMap.put( param.getName( ), cmbDataField ); cmbDataField.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { paramsValueMap.put( param.getName( ), new Expression( cmbDataField.getText( ), (String) cmbDataField.getData( ExpressionButtonUtil.EXPR_TYPE ) ) ); callback.run( ); } } ); cmbDataField.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { Expression expr = createBindingExpression( cmbDataField ); if ( expr != null ) { cmbDataField.setText( expr.getStringExpression( ) ); } if ( expr == null ) { expr = new Expression( cmbDataField.getText( ), (String) cmbDataField.getData( ExpressionButtonUtil.EXPR_TYPE ) ); } paramsValueMap.put( param.getName( ), expr ); } } ); } private void createTextControl( Composite paramsComposite, final IParameterDefn param ) { assert!param.isDataField( ); final Text txtParam = new Text( paramsComposite, SWT.BORDER | SWT.MULTI ); GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.heightHint = txtParam.computeSize( SWT.DEFAULT, SWT.DEFAULT ).y - txtParam.getBorderWidth( ) * 2; gridData.horizontalIndent = 0; txtParam.setLayoutData( gridData ); createExpressionButton( paramsComposite, txtParam, param ); paramsMap.put( param.getName( ), txtParam ); txtParam.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { paramsValueMap.put( param.getName( ), new Expression( txtParam.getText( ), (String) txtParam.getData( ExpressionButtonUtil.EXPR_TYPE ) ) ); callback.run( ); } } ); } private void initArgumentUI( ) { IAggrFunction function = getSelectedFunction( ); if ( function != null ) { IParameterDefn[] params = function.getParameterDefn( ); for ( final IParameterDefn param : params ) { initArgumentField( param ); } } } /** * Create function parameters area. If parameter is data field type, create * a combo box filled with binding holder's computed column. */ protected void updateArgumentUI( ) { resetArgumentUI( ); createArgumentUI( ); initArgumentUI( ); Point size = parent.getParent( ).computeSize( SWT.DEFAULT, SWT.DEFAULT ); parent.getParent( ).setSize( Math.max( size.x, 400 ), Math.max( size.y, 320 ) ); } private void initArgumentField( IParameterDefn param ) { Expression expr = paramsValueMap.get( param.getName( ) ); if ( expr != null ) { String text = expr.getStringExpression( ) == null ? "" : expr.getStringExpression( ); String type = expr.getType( ) == null ? ExpressionType.JAVASCRIPT : expr.getType( ); Control control = paramsMap.get( param.getName( ) ); assert control != null; if ( control instanceof Text ) { Text txtParam = (Text) control; txtParam.setText( text ); txtParam.setData( ExpressionButtonUtil.EXPR_TYPE, type ); } else if ( control instanceof Combo ) { Combo cmbDataField = (Combo) control; cmbDataField.setItems( getColumnBindings( ) ); cmbDataField.setText( text ); cmbDataField.setData( ExpressionButtonUtil.EXPR_TYPE, type); } ExpressionButton button = (ExpressionButton) control.getData( ExpressionButtonUtil.EXPR_BUTTON ); if ( button != null ) button.refresh( ); } } private void createExpressionButton( final Composite parent, final Control control, final IParameterDefn param ) { Listener listener = new Listener( ) { public void handleEvent( Event event ) { callback.run( ); } }; ExpressionButtonUtil.createExpressionButton( parent, control, exprProvider, this.bindingHolder, listener ); } private String[] getColumnBindings( ) { if ( bindings == null ) { return new String[]{}; } String[] names = new String[bindings.length]; for ( int i = 0; i < bindings.length; i++ ) { names[i] = bindings[i].getName( ); } return names; } private Expression createBindingExpression( Combo combo ) { String text = combo.getText( ); String expr = ExpressionButtonUtil.getCurrentExpressionConverter( combo ).getBindingExpression( text ); if ( expr != null ) { return new Expression( expr, ExpressionType.JAVASCRIPT ); } return new Expression( text, ExpressionType.JAVASCRIPT ); } } private class FunctionProvider { private IAggrFunction[] funcs; private HashMap<String, IAggrFunction> displayName2Funcs; private HashMap<String, IAggrFunction> name2Funcs; public FunctionProvider( IAggrFunction[] funcs ) { this.funcs = funcs == null ? new IAggrFunction[0] : funcs; this.displayName2Funcs = new HashMap<String, IAggrFunction>( funcs.length ); this.name2Funcs = new HashMap<String, IAggrFunction>( funcs.length ); for ( IAggrFunction func : funcs ) { displayName2Funcs.put( func.getDisplayName( ), func ); name2Funcs.put( func.getName( ), func ); } } public IAggrFunction getFunction( String funcName ) { return name2Funcs.get( funcName ); } public IAggrFunction getFunctionByDisplayText( String displayText ) { return displayName2Funcs.get( displayText ); } public String[] getDisplayTexts( ) { String[] displayTexts = new String[funcs.length]; for ( int i = 0; i < funcs.length; i++ ) { displayTexts[i] = funcs[i].getDisplayName( ); } Arrays.sort( displayTexts, new AlphabeticallyComparator( ) ); return displayTexts; } } }
package biz.netcentric.cq.tools.actool.authorizableutils.impl; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.ValueFactory; import javax.jcr.ValueFormatException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.apache.jackrabbit.api.JackrabbitSession; import org.apache.jackrabbit.api.security.user.Authorizable; import org.apache.jackrabbit.api.security.user.AuthorizableExistsException; import org.apache.jackrabbit.api.security.user.Group; import org.apache.jackrabbit.api.security.user.User; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.sling.jcr.api.SlingRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import biz.netcentric.cq.tools.actool.authorizableutils.AuthorizableBean; import biz.netcentric.cq.tools.actool.authorizableutils.AuthorizableCreatorException; import biz.netcentric.cq.tools.actool.authorizableutils.AuthorizableCreatorService; import biz.netcentric.cq.tools.actool.authorizableutils.AuthorizableInstallationHistory; import biz.netcentric.cq.tools.actool.configmodel.AuthorizableConfigBean; import biz.netcentric.cq.tools.actool.helper.AcHelper; import biz.netcentric.cq.tools.actool.helper.AccessControlUtils; import biz.netcentric.cq.tools.actool.helper.Constants; import biz.netcentric.cq.tools.actool.helper.ContentHelper; import biz.netcentric.cq.tools.actool.installationhistory.AcInstallationHistoryPojo; @Service @Component(metatype = true, label = "AC AuthorizableCreatorService", description = "Service that installs groups according to textual configuration files") public class AuthorizableCreatorServiceImpl implements AuthorizableCreatorService { private static final Logger LOG = LoggerFactory.getLogger(AuthorizableCreatorServiceImpl.class); private static final String PATH_SEGMENT_SYSTEMUSERS = "system"; private static final String PRINCIPAL_EVERYONE = "everyone"; // not using org.apache.jackrabbit.oak.spi.security.authentication.external.basic.DefaultSyncContext.REP_EXTERNAL_ID since it is an // optional dependency and not available in AEM 6.1 public static final String REP_EXTERNAL_ID = "rep:externalId"; AcInstallationHistoryPojo status; Map<String, Set<AuthorizableConfigBean>> principalMapFromConfig; AuthorizableInstallationHistory authorizableInstallationHistory; @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY) ExternalGroupCreatorServiceImpl externalGroupCreatorService; @Override public void createNewAuthorizables( Map<String, Set<AuthorizableConfigBean>> principalMapFromConfig, final Session session, AcInstallationHistoryPojo status, AuthorizableInstallationHistory authorizableInstallationHistory) throws AccessDeniedException, UnsupportedRepositoryOperationException, RepositoryException, AuthorizableCreatorException { this.status = status; this.principalMapFromConfig = principalMapFromConfig; this.authorizableInstallationHistory = authorizableInstallationHistory; Set<String> authorizableFromConfigurations = principalMapFromConfig.keySet(); for (String principalId : authorizableFromConfigurations) { Set<AuthorizableConfigBean> currentPrincipalData = principalMapFromConfig .get(principalId); Iterator<AuthorizableConfigBean> it = currentPrincipalData .iterator(); AuthorizableConfigBean tmpPricipalConfigBean = null; while (it.hasNext()) { tmpPricipalConfigBean = it.next(); status.addVerboseMessage("Starting installation of authorizable bean: " + tmpPricipalConfigBean.toString()); } installAuthorizableConfigurationBean(session, tmpPricipalConfigBean, status, authorizableInstallationHistory); } } private void installAuthorizableConfigurationBean(final Session session, AuthorizableConfigBean authorizableConfigBean, AcInstallationHistoryPojo history, AuthorizableInstallationHistory authorizableInstallationHistory) throws AccessDeniedException, UnsupportedRepositoryOperationException, RepositoryException, AuthorizableExistsException, AuthorizableCreatorException { String principalId = authorizableConfigBean.getPrincipalID(); LOG.debug("- start installation of authorizable: {}", principalId); UserManager userManager = AccessControlUtils.getUserManagerAutoSaveDisabled(session); ValueFactory vf = session.getValueFactory(); // if current authorizable from config doesn't exist yet Authorizable authorizableToInstall = userManager.getAuthorizable(principalId); if (authorizableToInstall == null) { authorizableToInstall = createNewAuthorizable(authorizableConfigBean, history, authorizableInstallationHistory, userManager, vf, session); } // if current authorizable from config already exists in repository else { // update name for both groups and users setAuthorizableProperties(authorizableToInstall, vf, authorizableConfigBean, session); // update password for users if (!authorizableToInstall.isGroup() && !authorizableConfigBean.isSystemUser() && StringUtils.isNotBlank(authorizableConfigBean.getPassword())) { ((User) authorizableToInstall).changePassword(authorizableConfigBean.getPassword()); } // move authorizable if path changed (retaining existing members) handleRecreationOfAuthorizableIfNecessary(session, authorizableConfigBean, history, authorizableInstallationHistory, userManager); mergeGroup(history, authorizableInstallationHistory, authorizableConfigBean, userManager); } if (authorizableConfigBean.isGroup()) { // this has to be added explicitly here (all other memberships are maintained isMemberOf) Group installedGroup = (Group) userManager.getAuthorizable(principalId); Authorizable anonymous = userManager.getAuthorizable(Constants.USER_ANONYMOUS); if (authorizableConfigBean.membersContainsAnonymous()) { installedGroup.addMember(anonymous); } else { installedGroup.removeMember(anonymous); } } if (StringUtils.isNotBlank(authorizableConfigBean.getMigrateFrom()) && authorizableConfigBean.isGroup()) { migrateFromOldGroup(authorizableConfigBean, userManager); } } private void migrateFromOldGroup(AuthorizableConfigBean authorizableConfigBean, UserManager userManager) throws RepositoryException { Authorizable groupForMigration = userManager.getAuthorizable(authorizableConfigBean.getMigrateFrom()); String principalId = authorizableConfigBean.getPrincipalID(); if (groupForMigration == null) { status.addMessage("Group " + authorizableConfigBean.getMigrateFrom() + " does not exist (specified as migrateFrom in group " + principalId + ") - no action taken"); return; } if (!groupForMigration.isGroup()) { status.addWarning("Specifying a user in 'migrateFrom' does not make sense (migrateFrom=" + authorizableConfigBean.getMigrateFrom() + " in " + principalId + ")"); return; } status.addMessage("Migrating from group " + authorizableConfigBean.getMigrateFrom() + " to " + principalId); Set<Authorizable> usersFromGroupToTakeOver = new HashSet<Authorizable>(); Iterator<Authorizable> membersIt = ((Group) groupForMigration).getMembers(); while (membersIt.hasNext()) { Authorizable member = membersIt.next(); if (!member.isGroup()) { usersFromGroupToTakeOver.add(member); } } if (!usersFromGroupToTakeOver.isEmpty()) { status.addMessage("- Taking over " + usersFromGroupToTakeOver.size() + " member users from group " + authorizableConfigBean.getMigrateFrom() + " to group " + principalId); Group currentGroup = (Group) userManager.getAuthorizable(principalId); for (Authorizable user : usersFromGroupToTakeOver) { currentGroup.addMember(user); } } groupForMigration.remove(); status.addMessage("- Deleted group " + authorizableConfigBean.getMigrateFrom()); } private void handleRecreationOfAuthorizableIfNecessary(final Session session, AuthorizableConfigBean principalConfigBean, AcInstallationHistoryPojo history, AuthorizableInstallationHistory authorizableInstallationHistory, UserManager userManager) throws RepositoryException, AuthorizableCreatorException { String principalId = principalConfigBean.getPrincipalID(); // compare intermediate paths Authorizable existingAuthorizable = userManager.getAuthorizable(principalId); String intermediatedPathOfExistingAuthorizable = existingAuthorizable.getPath() .substring(0, existingAuthorizable.getPath().lastIndexOf("/")); // Relative paths need to be prefixed with /home/groups (issue String authorizablePathFromBean = principalConfigBean.getPath(); if (StringUtils.isNotEmpty(authorizablePathFromBean) && (authorizablePathFromBean.charAt(0) != '/')) { authorizablePathFromBean = (principalConfigBean.isGroup() ? Constants.GROUPS_ROOT : Constants.USERS_ROOT) + (principalConfigBean.isSystemUser() && !authorizablePathFromBean.startsWith(PATH_SEGMENT_SYSTEMUSERS) ? "/" + PATH_SEGMENT_SYSTEMUSERS : "") + "/" + authorizablePathFromBean; } boolean pathHasChanged = !StringUtils.equals(intermediatedPathOfExistingAuthorizable, authorizablePathFromBean) && StringUtils.isNotBlank(principalConfigBean.getPath()); if (pathHasChanged) { String msg = "Found change of intermediate path for " + existingAuthorizable.getID() + ": " + intermediatedPathOfExistingAuthorizable + " -> " + authorizablePathFromBean; history.addMessage(msg); LOG.info(msg); } // using "" to compare non-external (both sides) to true String externalIdExistingAuthorizable = StringUtils .defaultIfEmpty(AcHelper.valuesToString(existingAuthorizable.getProperty(REP_EXTERNAL_ID)), ""); String externalIdConfig = StringUtils.defaultIfEmpty(principalConfigBean.getExternalId(), ""); boolean externalIdHasChanged = !StringUtils.equals(externalIdExistingAuthorizable, externalIdConfig); if (externalIdHasChanged) { String msg = "Found change of external id of " + existingAuthorizable.getID() + ": '" + externalIdExistingAuthorizable + "' (current) is not '" + externalIdConfig + "' (in config)"; history.addMessage(msg); LOG.info(msg); } if (pathHasChanged || externalIdHasChanged) { // save members of existing group before deletion Set<Authorizable> membersOfDeletedGroup = new HashSet<Authorizable>(); if (existingAuthorizable.isGroup()) { Group existingGroup = (Group) existingAuthorizable; Iterator<Authorizable> memberIt = existingGroup.getDeclaredMembers(); while (memberIt.hasNext()) { membersOfDeletedGroup.add(memberIt.next()); } } // delete existingAuthorizable; existingAuthorizable.remove(); // create group again using values form config ValueFactory vf = session.getValueFactory(); Authorizable newAuthorizable = createNewAuthorizable( principalConfigBean, history, authorizableInstallationHistory, userManager, vf, session); int countMovedMembersOfGroup = 0; if (newAuthorizable.isGroup()) { Group newGroup = (Group) newAuthorizable; // add members of deleted group for (Authorizable authorizable : membersOfDeletedGroup) { newGroup.addMember(authorizable); countMovedMembersOfGroup++; } } deleteOldIntermediatePath(session, session.getNode(intermediatedPathOfExistingAuthorizable)); String msg = "Recreated authorizable " + newAuthorizable + " at path " + newAuthorizable.getPath() + (newAuthorizable.isGroup() ? "(retained " + countMovedMembersOfGroup + " members of group)" : ""); history.addMessage(msg); LOG.info(msg); } } /** Deletes old intermediatePath parent node and all empty parent nodes up to /home/groups or /home/user. * * @param session * @param oldIntermediateNode * @throws RepositoryException */ private void deleteOldIntermediatePath(final Session session, Node oldIntermediateNode) throws RepositoryException { // if '/home/groups' or '/home/users' was intermediatedNode, these must // not get deleted! // also node to be deleted has to be empty, so no other authorizables // stored under this path get deleted while (!StringUtils.equals(Constants.GROUPS_ROOT, oldIntermediateNode.getPath()) && !StringUtils.equals(Constants.USERS_ROOT, oldIntermediateNode.getPath()) && !oldIntermediateNode.hasNodes()) { // delete old intermediatedPath Node parent = oldIntermediateNode.getParent(); session.removeItem(oldIntermediateNode.getPath()); // go one path level back for next iteration oldIntermediateNode = parent; } } private void mergeGroup(AcInstallationHistoryPojo status, AuthorizableInstallationHistory authorizableInstallationHistory, AuthorizableConfigBean principalConfigBean, UserManager userManager) throws RepositoryException, ValueFormatException, UnsupportedRepositoryOperationException, AuthorizableExistsException, AuthorizableCreatorException { String[] memberOf = principalConfigBean.getMemberOf(); String principalId = principalConfigBean.getPrincipalID(); LOG.debug("Authorizable {} already exists", principalId); Authorizable currentGroupFromRepository = userManager.getAuthorizable(principalId); Set<String> membershipGroupsFromConfig = getMembershipGroupsFromConfig(memberOf); Set<String> membershipGroupsFromRepository = getMembershipGroupsFromRepository(currentGroupFromRepository); // create snapshot bean authorizableInstallationHistory.addAuthorizable( currentGroupFromRepository.getID(), getAuthorizableName(currentGroupFromRepository), currentGroupFromRepository.getPath(), membershipGroupsFromRepository); mergeMemberOfGroups(principalId, status, userManager, membershipGroupsFromConfig, membershipGroupsFromRepository); } private String getAuthorizableName(Authorizable currentGroupFromRepository) throws RepositoryException, ValueFormatException { String authorizableName = ""; if (currentGroupFromRepository.getProperty("profile/givenName") != null) { authorizableName = currentGroupFromRepository .getProperty("profile/givenName")[0].getString(); } return authorizableName; } private Authorizable createNewAuthorizable( AuthorizableConfigBean principalConfigBean, AcInstallationHistoryPojo status, AuthorizableInstallationHistory authorizableInstallationHistory, UserManager userManager, ValueFactory vf, Session session) throws AuthorizableExistsException, RepositoryException, AuthorizableCreatorException { boolean isGroup = principalConfigBean.isGroup(); String principalId = principalConfigBean.getPrincipalID(); Authorizable newAuthorizable = null; if (isGroup) { newAuthorizable = createNewGroup(userManager, principalConfigBean, status, authorizableInstallationHistory, vf, principalMapFromConfig, session); LOG.info("Successfully created new group: {}", principalId); } else { if (StringUtils.isNotEmpty(principalConfigBean.getExternalId())) { throw new IllegalStateException("External IDs are not supported for users (" + principalConfigBean.getPrincipalID() + " is using '" + principalConfigBean.getExternalId() + "') - use a ootb sync handler to have users automatically created."); } newAuthorizable = createNewUser(userManager, principalConfigBean, status, authorizableInstallationHistory, vf, principalMapFromConfig, session); LOG.info("Successfully created new user: {}", principalId); } // for rollback authorizableInstallationHistory.addNewCreatedAuthorizable(principalId); return newAuthorizable; } private Set<String> getMembershipGroupsFromRepository(Authorizable currentGroupFromRepository) throws RepositoryException { Set<String> membershipGroupsFromRepository = new HashSet<String>(); Iterator<Group> memberOfGroupsIterator = currentGroupFromRepository.declaredMemberOf(); // build Set which contains the all Groups of which the existingGroup is // a member of while (memberOfGroupsIterator.hasNext()) { Authorizable memberOfGroup = memberOfGroupsIterator.next(); membershipGroupsFromRepository.add(memberOfGroup.getID()); } return membershipGroupsFromRepository; } private Set<String> getMembershipGroupsFromConfig(String[] memberOf) { // Set which holds all other groups which the current Group from config // is a member of Set<String> membershipGroupsFromConfig = new HashSet<String>(); if (memberOf != null) { // member of at least one other groups for (String s : memberOf) { membershipGroupsFromConfig.add(s); } } return membershipGroupsFromConfig; } @SuppressWarnings("unchecked") void mergeMemberOfGroups(String principalId, AcInstallationHistoryPojo status, UserManager userManager, Set<String> membershipGroupsFromConfig, Set<String> membershipGroupsFromRepository) throws RepositoryException, AuthorizableExistsException, AuthorizableCreatorException { LOG.debug("mergeMemberOfGroups() for {}", principalId); // membership to everyone cannot be removed or added => take it out from both lists membershipGroupsFromConfig.remove(PRINCIPAL_EVERYONE); membershipGroupsFromRepository.remove(PRINCIPAL_EVERYONE); logAndVerboseHistoryMessage(status, "Principal " + principalId + " isMemberOf(repo)=" + membershipGroupsFromRepository); logAndVerboseHistoryMessage(status, "Principal " + principalId + " isMemberOf(conifg)=" + membershipGroupsFromConfig); Set<String> validatedMembershipGroupsFromConfig = validateAssignedGroups(userManager, principalId, membershipGroupsFromConfig); Collection<String> unChangedMembers = CollectionUtils.intersection(membershipGroupsFromRepository, validatedMembershipGroupsFromConfig); logAndVerboseHistoryMessage(status, "Principal " + principalId + " remains member of groups " + unChangedMembers); Collection<String> toBeAddedMembers = CollectionUtils.subtract(validatedMembershipGroupsFromConfig, membershipGroupsFromRepository); logAndVerboseHistoryMessage(status, "Principal " + principalId + " will be added as member of " + toBeAddedMembers); Collection<String> toBeRemovedMembers = CollectionUtils.subtract(membershipGroupsFromRepository, validatedMembershipGroupsFromConfig); Set<String> toBeSkippedFromRemovalMembers = new HashSet<String>(); Pattern ignoredMembershipsPattern = status.getAcConfiguration().getGlobalConfiguration().getAllowExternalGroupNamesRegEx(); Iterator<String> toBeRemovedMembersIt = toBeRemovedMembers.iterator(); while (toBeRemovedMembersIt.hasNext()) { String groupId = toBeRemovedMembersIt.next(); if ((ignoredMembershipsPattern != null) && ignoredMembershipsPattern.matcher(groupId).find()) { toBeSkippedFromRemovalMembers.add(groupId); toBeRemovedMembersIt.remove(); } } logAndVerboseHistoryMessage(status, "Principal " + principalId + " will be removed from members of " + toBeRemovedMembers); if (!toBeSkippedFromRemovalMembers.isEmpty()) { logAndVerboseHistoryMessage(status, "Principal " + principalId + " remains member of groups " + toBeSkippedFromRemovalMembers + " (due to configured ignoredMembershipsPattern=" + ignoredMembershipsPattern + ")"); } // perform changes Authorizable currentAuthorizable = userManager.getAuthorizable(principalId); for (String groupId : toBeAddedMembers) { LOG.debug("Membership Change: Adding {} to members of group {} in repository", principalId, groupId); Authorizable targetAuthorizable = userManager.getAuthorizable(groupId); ((Group) targetAuthorizable).addMember(currentAuthorizable); } for (String groupId : toBeRemovedMembers) { LOG.debug("Membership Change: Removing {} from members of group {} in repository", principalId, groupId); Authorizable targetAuthorizable = userManager.getAuthorizable(groupId); ((Group) targetAuthorizable).removeMember(currentAuthorizable); } if (!toBeAddedMembers.isEmpty() && !toBeAddedMembers.isEmpty()) { logAndVerboseHistoryMessage(status, "Membership Change: Principal " + principalId + " was added to " + toBeAddedMembers.size() + " and removed from " + toBeRemovedMembers.size() + " groups"); } } private void logAndVerboseHistoryMessage(AcInstallationHistoryPojo status, String msg) { LOG.debug(msg); status.addVerboseMessage(msg); } private Authorizable createNewGroup( final UserManager userManager, AuthorizableConfigBean principalConfigBean, AcInstallationHistoryPojo status, AuthorizableInstallationHistory authorizableInstallationHistory, ValueFactory vf, Map<String, Set<AuthorizableConfigBean>> principalMapFromConfig, Session session) throws AuthorizableExistsException, RepositoryException, AuthorizableCreatorException { String groupID = principalConfigBean.getPrincipalID(); String intermediatePath = principalConfigBean.getPath(); // create new Group Group newGroup = null; try { if (StringUtils.isNotEmpty(principalConfigBean.getExternalId())) { if (externalGroupCreatorService == null) { throw new IllegalStateException("External IDs are not availabe for your AEM version (" + principalConfigBean.getPrincipalID() + " is using '" + principalConfigBean.getExternalId() + "')"); } newGroup = (Group) externalGroupCreatorService.createGroupWithExternalId(userManager, principalConfigBean, status, authorizableInstallationHistory, vf, principalMapFromConfig, session); LOG.info("Successfully created new external group: {}", groupID); } else { PrincipalImpl principalForNewGroup = new PrincipalImpl(groupID); if (StringUtils.isNotBlank(intermediatePath)) { newGroup = userManager.createGroup(principalForNewGroup, intermediatePath); } else { newGroup = userManager.createGroup(principalForNewGroup); } } } catch (AuthorizableExistsException e) { LOG.warn("Group {} already exists in system!", groupID); newGroup = (Group) userManager.getAuthorizable(groupID); } addMembersToReferencingAuthorizables(newGroup, principalConfigBean, userManager); setAuthorizableProperties(newGroup, vf, principalConfigBean, session); return newGroup; } private void setAuthorizableProperties(Authorizable authorizable, ValueFactory vf, AuthorizableConfigBean principalConfigBean, Session session) throws RepositoryException { String profileContent = principalConfigBean.getProfileContent(); if (StringUtils.isNotBlank(profileContent)) { ContentHelper.importContent(session, authorizable.getPath() + "/profile", profileContent); } String preferencesContent = principalConfigBean.getPreferencesContent(); if (StringUtils.isNotBlank(preferencesContent)) { ContentHelper.importContent(session, authorizable.getPath() + "/preferences", preferencesContent); } String name = principalConfigBean.getName(); if (StringUtils.isNotBlank(name)) { if (authorizable.isGroup()) { authorizable.setProperty("profile/givenName", vf.createValue(name)); } else { String givenName = StringUtils.substringBeforeLast(name, " "); String familyName = StringUtils.substringAfterLast(name, " "); authorizable.setProperty("profile/givenName", vf.createValue(givenName)); authorizable.setProperty("profile/familyName", vf.createValue(familyName)); } } String description = principalConfigBean.getDescription(); if (StringUtils.isNotBlank(description)) { authorizable.setProperty("profile/aboutMe", vf.createValue(description)); } } private Authorizable createNewUser( final UserManager userManager, AuthorizableConfigBean principalConfigBean, AcInstallationHistoryPojo status, AuthorizableInstallationHistory authorizableInstallationHistory, ValueFactory vf, Map<String, Set<AuthorizableConfigBean>> principalMapFromConfig, Session session) throws AuthorizableExistsException, RepositoryException, AuthorizableCreatorException { String principalId = principalConfigBean.getPrincipalID(); String password = principalConfigBean.getPassword(); boolean isSystemUser = principalConfigBean.isSystemUser(); String intermediatePath = principalConfigBean.getPath(); User newUser = null; if (isSystemUser) { newUser = userManagerCreateSystemUserViaReflection(userManager, principalId, intermediatePath, status); } else { newUser = userManager.createUser(principalId, password, new PrincipalImpl(principalId), intermediatePath); } setAuthorizableProperties(newUser, vf, principalConfigBean, session); addMembersToReferencingAuthorizables(newUser, principalConfigBean, userManager); return newUser; } private void addMembersToReferencingAuthorizables(Authorizable authorizable, AuthorizableConfigBean principalConfigBean, final UserManager userManager) throws RepositoryException, AuthorizableCreatorException { String principalId = principalConfigBean.getPrincipalID(); String[] memberOf = principalConfigBean.getMemberOf(); if ((authorizable != null) && (memberOf != null) && (memberOf.length > 0)) { // add group to groups according to configuration Set<String> referencingAuthorizablesToBeChanged = validateAssignedGroups(userManager, principalId, new HashSet<String>(Arrays.asList(memberOf))); if (!referencingAuthorizablesToBeChanged.isEmpty()) { LOG.debug("start adding {} to assignedGroups", principalId); for (String referencingAuthorizableToBeChangedId : referencingAuthorizablesToBeChanged) { Group referencingAuthorizableToBeChanged = (Group) userManager.getAuthorizable(referencingAuthorizableToBeChangedId); referencingAuthorizableToBeChanged.addMember(authorizable); LOG.debug("added to {} ", referencingAuthorizableToBeChanged); } } } } // using reflection with fallback to create a system user in order to be backwards compatible private User userManagerCreateSystemUserViaReflection(UserManager userManager, String userID, String intermediatePath, AcInstallationHistoryPojo status) throws RepositoryException { // make sure all relative intermediate paths get the prefix suffix (but don't touch absolute paths) String systemPrefix = "system/"; if ((intermediatePath != null) && !intermediatePath.startsWith(systemPrefix) && !intermediatePath.startsWith("/")) { intermediatePath = systemPrefix + intermediatePath; } try { Method method = userManager.getClass().getMethod("createSystemUser", String.class, String.class); User user = (User) method.invoke(userManager, userID, intermediatePath); return user; } catch (Throwable e) { if (e instanceof InvocationTargetException) { e = ((InvocationTargetException) e).getTargetException(); } status.addError("Could not create system user " + userID + ". e:" + e); } return null; } /** Validates the authorizables in 'membersOf' array of a given authorizable. Validation fails if an authorizable is a user. * * If an authorizable contained in membersOf array doesn't exist it gets created and the current authorizable gets added as a member. * * @param userManager * @param authorizablelID the ID of authorizable to validate * @param isMemberOf String array that contains the groups which the authorizable should be a member of * @return Set of authorizables which the current authorizable is a member of * @throws RepositoryException * @throws AuthorizableCreatorException if one of the authorizables contained in membersOf array is a user */ Set<String> validateAssignedGroups( final UserManager userManager, final String authorizablelID, final Set<String> isMemberOf) throws RepositoryException, AuthorizableCreatorException { Set<String> authorizableSet = new HashSet<String>(); for (String memberOfPrincipal : isMemberOf) { if (StringUtils.equals(authorizablelID, memberOfPrincipal)) { throw new AuthorizableCreatorException("Cannot add authorizable " + authorizablelID + " as member of itself."); } Authorizable authorizable = userManager.getAuthorizable(memberOfPrincipal); // validation // if authorizable is existing in system if (authorizable != null) { // check if authorizable is a group if (authorizable.isGroup()) { authorizableSet.add(authorizable.getID()); } else { String message = "Failed to add authorizable " + authorizablelID + " to autorizable " + memberOfPrincipal + "! Authorizable is not a group"; throw new AuthorizableCreatorException(message); } // if authorizable doesn't exist yet, it gets created and the // current authorizable gets added as a member } else { // check if authorizable is contained in any of the // configurations if (principalMapFromConfig.keySet().contains(memberOfPrincipal)) { // get authorizable intermediatePath Set<AuthorizableConfigBean> authorizableConfigSet = principalMapFromConfig.get(memberOfPrincipal); Iterator<AuthorizableConfigBean> it = authorizableConfigSet.iterator(); AuthorizableConfigBean authorizableConfigBean = null; while (it.hasNext()) { authorizableConfigBean = it.next(); } // create authorizable // if authorizableConfigBean.getPath() returns an empty // string (no path defined in configuration) the standard // path gets used Group newGroup = userManager.createGroup( new PrincipalImpl(memberOfPrincipal), authorizableConfigBean.getPath()); authorizableSet.add(newGroup.getID()); authorizableInstallationHistory.addNewCreatedAuthorizable(newGroup.getID()); LOG.info("Created group to be able to add {} to group {} ", authorizablelID, memberOfPrincipal); } else { String message = "Failed to add group: " + authorizablelID + " as member to authorizable: " + memberOfPrincipal + ". Neither found this authorizable (" + memberOfPrincipal + ") in any of the configurations nor installed in the system!"; LOG.error(message); throw new AuthorizableCreatorException(message); } } } return authorizableSet; } @Override public void performRollback(SlingRepository repository, AuthorizableInstallationHistory authorizableInstallationHistory, AcInstallationHistoryPojo history) throws RepositoryException { Session session = repository.loginAdministrative(null); ValueFactory vf = session.getValueFactory(); try { JackrabbitSession js = (JackrabbitSession) session; UserManager userManager = js.getUserManager(); // if groups was newly created delete it Set<String> newCreatedAuthorizables = authorizableInstallationHistory .getNewCreatedAuthorizables(); String message = "starting rollback of authorizables..."; history.addWarning(message); if (!newCreatedAuthorizables.isEmpty()) { history.addWarning("performing Groups rollback!"); for (String authorizableName : newCreatedAuthorizables) { Authorizable authorizable = userManager.getAuthorizable(authorizableName); if (authorizable != null) { authorizable.remove(); message = "removed authorizable " + authorizableName + " from the system!"; LOG.info(message); history.addWarning(message); } else { message = "Can't remove authorizable " + authorizableName + " from the system!"; LOG.error(message); history.addError(message); } } } // if not compare the changes and reset them to the prevoius state Set<AuthorizableBean> authorizableBeans = authorizableInstallationHistory .getAuthorizableBeans(); for (AuthorizableBean snapshotBean : authorizableBeans) { Authorizable authorizable = userManager .getAuthorizable(snapshotBean.getName()); if (authorizable != null) { history.addMessage("found changed authorizable:" + authorizable.getID()); // check memberOf groups Iterator<Group> it = authorizable.memberOf(); Set<String> memberOfGroups = new HashSet<String>(); while (it.hasNext()) { memberOfGroups.add(it.next().getID()); } if (snapshotBean.getAuthorizablesSnapshot().equals( memberOfGroups)) { history.addMessage("No change found in memberOfGroups of authorizable: " + authorizable.getID()); } else { history.addMessage("changes found in memberOfGroups of authorizable: " + authorizable.getID()); // delete membership of currently set memberOf groups Iterator<Group> it2 = authorizable.memberOf(); while (it2.hasNext()) { Group group = it2.next(); group.removeMember(authorizable); history.addWarning("removed authorizable: " + authorizable.getID() + " from members of group: " + group.getID()); } // reset the state from snapshot bean for (String group : snapshotBean .getAuthorizablesSnapshot()) { Authorizable groupFromSnapshot = userManager .getAuthorizable(group); if (groupFromSnapshot != null) { ((Group) groupFromSnapshot) .addMember(authorizable); history.addWarning("add authorizable: " + authorizable.getID() + " to members of group: " + groupFromSnapshot.getID() + " again"); } } } String authorizableName = ""; if (authorizable.hasProperty("profile/givenName")) { authorizableName = authorizable .getProperty("profile/givenName")[0] .getString(); } if (snapshotBean.getName().equals(authorizableName)) { history.addMessage("No change found in name of authorizable: " + authorizable.getID()); } else { history.addMessage("change found in name of authorizable: " + authorizable.getID()); authorizable.setProperty("profile/givenName", vf.createValue(snapshotBean.getName())); history.addMessage("changed name of authorizable from: " + authorizableName + " back to: " + snapshotBean.getName()); } // TODO: compare other properties as well (name, path,...) } } } finally { if (session != null) { session.save(); session.logout(); } } } }
import java.util.*; public class CircularLinkedList { public CircularLinkedList () { _entries = new HashMap<Integer, Node>(); _head = _tail = _current = null; } public final HashMap<Integer, Node> getEntries () { return _entries; } public final Node getCurrent () { return _current; } public final void setCurrent (Node c) { _current = c; } public final void add (int value) { add(new Node(value)); } public final void add (Node n) { if (_entries.size() == 0) { _head = n; _tail = _head; _current = _head; _current.setNext(_head); } else { Node last = _tail; last.setNext(n); n.setNext(_head); _tail = n; } _entries.put(n.getValue(), n); } public void addTo (Node position, CircularLinkedList toAdd) { if (position == _tail) { Node theTail = _tail; _tail = toAdd._tail; _tail.setNext(_head); theTail.setNext(toAdd._head); } else { Node posNext = position.getNext(); position.setNext(toAdd._head); toAdd._tail.setNext(posNext); } _entries.putAll(toAdd._entries); } public final CircularLinkedList removeFrom (Node position) { CircularLinkedList removed = new CircularLinkedList(); Node cup = position.getNext(); Node entry = cup; removed.add(cup); _entries.remove(cup.getValue()); for (int i = 0; i < 2; i++) { entry = entry.getNext(); removed.add(entry); _entries.remove(entry.getValue()); } if ((entry == _tail) || (entry == _head)) { _tail = position; _tail.setNext(_head); if (entry == _head) _head = _head.getNext(); } else { if ((cup == _tail) || (cup == _head)) { _head = _head.getNext().getNext(); if (cup == _head) { _head = _head.getNext(); } else _tail = position; _tail.setNext(_head); } else position.setNext(entry.getNext()); } return removed; } private HashMap<Integer, Node> _entries; private Node _head; private Node _tail; private Node _current; }
/* WUGraph.java */ package com.xqbase.java.graph; import com.xqbase.java.dict.HashTable; import com.xqbase.java.list.DList; import com.xqbase.java.list.DListNode; /** * The WUGraph class represents a weighted, undirected graph. Self-edges are * permitted. */ public class WUGraph { /** * The Vertex HashTable mapping application's vertex to the internal vertex. */ private HashTable vertexTable; /** * The Vertex Doubly-Linked list. */ private DList<Vertex> vertexList; /** * The Edge Hash Table. */ private HashTable edgeTable; /** * The Adjacency List. */ private DList<DList<Edge>> adjacencyList; private int edgeCount; private int vertexCount; /** * WUGraph() constructs a graph having no vertices or edges. * <p/> * Running time: O(1). */ public WUGraph() { vertexTable = new HashTable(); vertexList = new DList<Vertex>(); edgeTable = new HashTable(); adjacencyList = new DList<DList<Edge>>(); vertexCount = 0; edgeCount = 0; } /** * vertexCount() returns the number of vertices in the graph. * <p/> * Running time: O(1). */ public int vertexCount() { return vertexCount; } /** * edgeCount() returns the total number of edges in the graph. * <p/> * Running time: O(1). */ public int edgeCount() { return edgeCount; } /** * getVertices() returns an array containing all the objects that serve * as vertices of the graph. The array's length is exactly equal to the * number of vertices. If the graph has no vertices, the array has length * zero. * <p/> * (NOTE: Do not return any internal data structure you use to represent * vertices! Return only the same objects that were provided by the * calling application in calls to addVertex().) * <p/> * Running time: O(|V|). */ public Object[] getVertices() { Object[] vertices = new Object[vertexCount]; DListNode<Vertex> head = vertexList.front(); int i = 0; while (head != null) { vertices[i] = head.item.element; head = head.next; i ++; } return vertices; } /** * addVertex() adds a vertex (with no incident edges) to the graph. * The vertex's "name" is the object provided as the parameter "vertex". * If this object is already a vertex of the graph, the graph is unchanged. * <p/> * Running time: O(1). */ public void addVertex(Object vertex) { if (vertex == null) return; DList<Edge> edgeDList = new DList<Edge>(); Vertex v = new Vertex(vertex, edgeDList); vertexTable.insert(vertex, v); vertexList.insertFront(v); adjacencyList.insertFront(edgeDList); vertexCount ++; } /** * removeVertex() removes a vertex from the graph. All edges incident on the * deleted vertex are removed as well. If the parameter "vertex" does not * represent a vertex of the graph, the graph is unchanged. * <p/> * Running time: O(d), where d is the degree of "vertex". */ public void removeVertex(Object vertex) { if (!isVertex(vertex)) return; Vertex v = (Vertex) vertexTable.find(vertex).value(); DList<Edge> edgeDList = v.edgeDList; DListNode<Edge> head = edgeDList.front(); while (head != null) { DListNode<Edge> nextEdge = head.next; Edge edge = head.item; if (edge.firstNode.equals(edge.secondNode)) { edgeDList.remove(head); edgeCount } else { edgeDList.remove(head); edge.dest.edgeDList.remove(head); edgeCount } head = nextEdge; } vertexCount } /** * isVertex() returns true if the parameter "vertex" represents a vertex of * the graph. * <p/> * Running time: O(1). */ public boolean isVertex(Object vertex) { return vertexTable.contains(vertex); } /** * degree() returns the degree of a vertex. Self-edges add only one to the * degree of a vertex. If the parameter "vertex" doesn't represent a vertex * of the graph, zero is returned. * <p/> * Running time: O(1). */ public int degree(Object vertex) { if (!isVertex(vertex)) return 0; Vertex v = (Vertex) vertexTable.find(vertex).value(); return v.edgeDList.length(); } /** * getNeighbors() returns a new Neighbors object referencing two arrays. The * Neighbors.neighborList array contains each object that is connected to the * input object by an edge. The Neighbors.weightList array contains the * weights of the corresponding edges. The length of both arrays is equal to * the number of edges incident on the input vertex. If the vertex has * degree zero, or if the parameter "vertex" does not represent a vertex of * the graph, null is returned (instead of a Neighbors object). * <p/> * The returned Neighbors object, and the two arrays, are both newly created. * No previously existing Neighbors object or array is changed. * <p/> * (NOTE: In the neighborList array, do not return any internal data * structure you use to represent vertices! Return only the same objects * that were provided by the calling application in calls to addVertex().) * <p/> * Running time: O(d), where d is the degree of "vertex". */ public Neighbors getNeighbors(Object vertex) { if (!isVertex(vertex) || degree(vertex) == 0) return null; Vertex v = (Vertex) vertexTable.find(vertex).value(); int degree = degree(vertex); DList<Edge> edgeDList = v.edgeDList; Neighbors neighbors = new Neighbors(); Object[] neighborList = new Object[degree]; int[] weightList = new int[degree]; DListNode<Edge> head = edgeDList.front(); int i = 0; while (head != null) { Edge edge = head.item; weightList[i] = edge.weight; if (edge.origin.element.equals(vertex)) { neighborList[i] = edge.dest.element; } else { neighborList[i] = edge.origin.element; } head = head.next; i ++; } neighbors.neighborList = neighborList; neighbors.weightList = weightList; return neighbors; } /** * addEdge() adds an edge (u, v) to the graph. If either of the parameters * u and v does not represent a vertex of the graph, the graph is unchanged. * The edge is assigned a weight of "weight". If the graph already contains * edge (u, v), the weight is updated to reflect the new value. Self-edges * (where u.equals(v)) are allowed. * <p/> * Running time: O(1). */ public void addEdge(Object u, Object v, int weight) { if (!isVertex(u) || !isVertex(v)) return; Vertex uVertex = (Vertex) vertexTable.find(u).value(); Vertex vVertex = (Vertex) vertexTable.find(v).value(); Edge edge = new Edge(weight, uVertex, vVertex, null, null); DListNode<Edge> firstNode = uVertex.edgeDList.insertFront(edge); DListNode<Edge> secondNode = vVertex.edgeDList.insertFront(edge); edge.firstNode = firstNode; edge.secondNode = secondNode; edgeTable.insert(new VertexPair(u, v), edge); edgeCount ++; } /** * removeEdge() removes an edge (u, v) from the graph. If either of the * parameters u and v does not represent a vertex of the graph, the graph * is unchanged. If (u, v) is not an edge of the graph, the graph is * unchanged. * <p/> * Running time: O(1). */ public void removeEdge(Object u, Object v) { if (!isVertex(u) || !isVertex(v)) return; if (!isEdge(u, v)) return; Edge edge = (Edge) edgeTable.find(new VertexPair(u, v)).value(); Vertex uVertex = (Vertex) vertexTable.find(u).value(); uVertex.edgeDList.remove(edge.firstNode); Vertex vVertex = (Vertex) vertexTable.find(v).value(); vVertex.edgeDList.remove(edge.secondNode); edgeCount } /** * isEdge() returns true if (u, v) is an edge of the graph. Returns false * if (u, v) is not an edge (including the case where either of the * parameters u and v does not represent a vertex of the graph). * <p/> * Running time: O(1). */ public boolean isEdge(Object u, Object v) { return edgeTable.contains(new VertexPair(u, v)); } /** * weight() returns the weight of (u, v). Returns zero if (u, v) is not * an edge (including the case where either of the parameters u and v does * not represent a vertex of the graph). * <p/> * (NOTE: A well-behaved application should try to avoid calling this * method for an edge that is not in the graph, and should certainly not * treat the result as if it actually represents an edge with weight zero. * However, some sort of default response is necessary for missing edges, * so we return zero. An exception would be more appropriate, but also more * annoying.) * <p/> * Running time: O(1). */ public int weight(Object u, Object v) { if (!isEdge(u, v)) return 0; Edge edge = (Edge) edgeTable.find(new VertexPair(u, v)).value(); return edge.weight; } /** * The internal Vertex class. */ private static class Vertex { private Object element; private DList<Edge> edgeDList; public Vertex(Object element, DList<Edge> edgeDList) { this.element = element; this.edgeDList = edgeDList; } } /** * The internal Edge class. */ private static class Edge { private int weight; private Vertex origin; private Vertex dest; private DListNode<Edge> firstNode; private DListNode<Edge> secondNode; public Edge(int weight, Vertex origin, Vertex dest, DListNode<Edge> firstNode, DListNode<Edge> secondNode) { this.weight = weight; this.origin = origin; this.dest = dest; this.firstNode = firstNode; this.secondNode = secondNode; } } }
package org.wildfly.clustering.marshalling.protostream; import java.security.PrivilegedAction; import java.util.Collections; import java.util.EnumSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.ServiceLoader; import org.infinispan.protostream.ImmutableSerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.wildfly.security.manager.WildFlySecurityManager; /** * Builds a ProtoStream {@link ImmutableSerializationContext}. * @author Paul Ferraro */ public class SerializationContextBuilder { private static final String PROTOSTREAM_BASE_PACKAGE_NAME = org.infinispan.protostream.BaseMarshaller.class.getPackage().getName(); private final DefaultSerializationContext context = new DefaultSerializationContext(); /** * Constructs a builder for a {@link org.infinispan.protostream.SerializationContext} using a default set of initializers. * @param marshaller a class loader marshaller */ public SerializationContextBuilder(ClassLoaderMarshaller marshaller) { // Load default schemas first, so they can be referenced by loader-specific schemas this.register(Collections.singleton(new LangSerializationContextInitializer(marshaller))); this.register(EnumSet.allOf(DefaultSerializationContextInitializerProvider.class)); } /** * Returns an immutable {@link org.infinispan.protostream.SerializationContext}. * @return the completed and immutable serialization context */ public ImmutableSerializationContext build() { return this.context.get(); } /** * Registers an initializer with the {@link org.infinispan.protostream.SerializationContext}. * @param initializer an initializer for the {@link org.infinispan.protostream.SerializationContext}. * @return this builder */ public SerializationContextBuilder register(SerializationContextInitializer initializer) { this.init(initializer); return this; } /** * Registers a number of initializers with the {@link org.infinispan.protostream.SerializationContext}. * @param initializers one or more initializers for the {@link org.infinispan.protostream.SerializationContext}. * @return this builder */ public SerializationContextBuilder register(Iterable<? extends SerializationContextInitializer> initializers) { for (SerializationContextInitializer initializer : initializers) { this.init(initializer); } return this; } /** * Loads {@link SerializationContextInitializer} instances from the specified {@link ClassLoader} and registers then with the {@link org.infinispan.protostream.SerializationContext}. * @param loader a class loader * @return this builder */ public SerializationContextBuilder load(ClassLoader loader) { this.tryLoad(loader); return this; } /** * Similar to {@link #load(ClassLoader)}, but throws a {@link NoSuchElementException} if no {@link SerializationContextInitializer} instances were found. * @param loader a class loader * @return this builder */ public SerializationContextBuilder require(ClassLoader loader) { if (!this.tryLoad(loader)) { throw new NoSuchElementException(); } return this; } private boolean tryLoad(ClassLoader loader) { PrivilegedAction<Boolean> action = new PrivilegedAction<>() { @Override public Boolean run() { Iterator<SerializationContextInitializer> initializers = ServiceLoader.load(SerializationContextInitializer.class, loader).iterator(); boolean init = false; while (initializers.hasNext()) { SerializationContextInitializer initializer = initializers.next(); // Do not load initializers from protostream-types if (!initializer.getClass().getName().startsWith(PROTOSTREAM_BASE_PACKAGE_NAME)) { SerializationContextBuilder.this.init(initializer); init = true; } } return init; } }; return WildFlySecurityManager.doUnchecked(action); } void init(SerializationContextInitializer initializer) { initializer.registerSchema(this.context); initializer.registerMarshallers(this.context); } }
package android.support.v7.appcompat; public final class R { public static final class anim { public static final int abc_fade_in = 0x7f040000; public static final int abc_fade_out = 0x7f040001; public static final int abc_slide_in_bottom = 0x7f040002; public static final int abc_slide_in_top = 0x7f040003; public static final int abc_slide_out_bottom = 0x7f040004; public static final int abc_slide_out_top = 0x7f040005; } public static final class attr { public static final int actionBarDivider = 0x7f01000f; public static final int actionBarItemBackground = 0x7f010010; public static final int actionBarSize = 0x7f01000e; public static final int actionBarSplitStyle = 0x7f01000c; public static final int actionBarStyle = 0x7f01000b; public static final int actionBarTabBarStyle = 0x7f010008; public static final int actionBarTabStyle = 0x7f010007; public static final int actionBarTabTextStyle = 0x7f010009; public static final int actionBarWidgetTheme = 0x7f01000d; public static final int actionButtonStyle = 0x7f010016; public static final int actionDropDownStyle = 0x7f010047; public static final int actionLayout = 0x7f01004e; public static final int actionMenuTextAppearance = 0x7f010011; public static final int actionMenuTextColor = 0x7f010012; public static final int actionModeBackground = 0x7f01003c; public static final int actionModeCloseButtonStyle = 0x7f01003b; public static final int actionModeCloseDrawable = 0x7f01003e; public static final int actionModeCopyDrawable = 0x7f010040; public static final int actionModeCutDrawable = 0x7f01003f; public static final int actionModeFindDrawable = 0x7f010044; public static final int actionModePasteDrawable = 0x7f010041; public static final int actionModePopupWindowStyle = 0x7f010046; public static final int actionModeSelectAllDrawable = 0x7f010042; public static final int actionModeShareDrawable = 0x7f010043; public static final int actionModeSplitBackground = 0x7f01003d; public static final int actionModeStyle = 0x7f01003a; public static final int actionModeWebSearchDrawable = 0x7f010045; public static final int actionOverflowButtonStyle = 0x7f01000a; public static final int actionProviderClass = 0x7f010050; public static final int actionViewClass = 0x7f01004f; public static final int activityChooserViewStyle = 0x7f01006c; public static final int background = 0x7f01002f; public static final int backgroundSplit = 0x7f010031; public static final int backgroundStacked = 0x7f010030; public static final int buttonBarButtonStyle = 0x7f010018; public static final int buttonBarStyle = 0x7f010017; public static final int customNavigationLayout = 0x7f010032; public static final int disableChildrenWhenDisabled = 0x7f010054; public static final int displayOptions = 0x7f010028; public static final int divider = 0x7f01002e; public static final int dividerHorizontal = 0x7f01001b; public static final int dividerPadding = 0x7f010056; public static final int dividerVertical = 0x7f01001a; public static final int dropDownListViewStyle = 0x7f010021; public static final int dropdownListPreferredItemHeight = 0x7f010048; public static final int expandActivityOverflowButtonDrawable = 0x7f01006b; public static final int height = 0x7f010026; public static final int homeAsUpIndicator = 0x7f010013; public static final int homeLayout = 0x7f010033; public static final int icon = 0x7f01002c; public static final int iconifiedByDefault = 0x7f01005a; public static final int indeterminateProgressStyle = 0x7f010035; public static final int initialActivityCount = 0x7f01006a; public static final int isLightTheme = 0x7f010059; public static final int itemPadding = 0x7f010037; public static final int listChoiceBackgroundIndicator = 0x7f01004c; public static final int listPopupWindowStyle = 0x7f010022; public static final int listPreferredItemHeight = 0x7f01001c; public static final int listPreferredItemHeightLarge = 0x7f01001e; public static final int listPreferredItemHeightSmall = 0x7f01001d; public static final int listPreferredItemPaddingLeft = 0x7f01001f; public static final int listPreferredItemPaddingRight = 0x7f010020; public static final int logo = 0x7f01002d; public static final int navigationMode = 0x7f010027; public static final int paddingEnd = 0x7f010039; public static final int paddingStart = 0x7f010038; public static final int panelMenuListTheme = 0x7f01004b; public static final int panelMenuListWidth = 0x7f01004a; public static final int popupMenuStyle = 0x7f010049; public static final int popupPromptView = 0x7f010053; public static final int progressBarPadding = 0x7f010036; public static final int progressBarStyle = 0x7f010034; public static final int prompt = 0x7f010051; public static final int queryHint = 0x7f01005b; public static final int searchDropdownBackground = 0x7f01005c; public static final int searchResultListItemHeight = 0x7f010065; public static final int searchViewAutoCompleteTextView = 0x7f010069; public static final int searchViewCloseIcon = 0x7f01005d; public static final int searchViewEditQuery = 0x7f010061; public static final int searchViewEditQueryBackground = 0x7f010062; public static final int searchViewGoIcon = 0x7f01005e; public static final int searchViewSearchIcon = 0x7f01005f; public static final int searchViewTextField = 0x7f010063; public static final int searchViewTextFieldRight = 0x7f010064; public static final int searchViewVoiceIcon = 0x7f010060; public static final int selectableItemBackground = 0x7f010019; public static final int showAsAction = 0x7f01004d; public static final int showDividers = 0x7f010055; public static final int spinnerDropDownItemStyle = 0x7f010058; public static final int spinnerMode = 0x7f010052; public static final int spinnerStyle = 0x7f010057; public static final int subtitle = 0x7f010029; public static final int subtitleTextStyle = 0x7f01002b; public static final int textAllCaps = 0x7f01006d; public static final int textAppearanceLargePopupMenu = 0x7f010014; public static final int textAppearanceListItem = 0x7f010023; public static final int textAppearanceListItemSmall = 0x7f010024; public static final int textAppearanceSearchResultSubtitle = 0x7f010067; public static final int textAppearanceSearchResultTitle = 0x7f010066; public static final int textAppearanceSmallPopupMenu = 0x7f010015; public static final int textColorSearchUrl = 0x7f010068; public static final int title = 0x7f010025; public static final int titleTextStyle = 0x7f01002a; public static final int windowActionBar = 0x7f010000; public static final int windowActionBarOverlay = 0x7f010001; public static final int windowFixedHeightMajor = 0x7f010006; public static final int windowFixedHeightMinor = 0x7f010004; public static final int windowFixedWidthMajor = 0x7f010003; public static final int windowFixedWidthMinor = 0x7f010005; public static final int windowSplitActionBar = 0x7f010002; } public static final class bool { public static final int abc_action_bar_embed_tabs_pre_jb = 0x7f060000; public static final int abc_action_bar_expanded_action_views_exclusive = 0x7f060001; public static final int abc_config_actionMenuItemAllCaps = 0x7f060005; public static final int abc_config_allowActionMenuItemTextWithIcon = 0x7f060004; public static final int abc_config_showMenuShortcutsWhenKeyboardPresent = 0x7f060003; public static final int abc_split_action_bar_is_narrow = 0x7f060002; } public static final class color { public static final int abc_search_url_text_holo = 0x7f070003; public static final int abc_search_url_text_normal = 0x7f070000; public static final int abc_search_url_text_pressed = 0x7f070002; public static final int abc_search_url_text_selected = 0x7f070001; } public static final class dimen { public static final int abc_action_bar_default_height = 0x7f080002; public static final int abc_action_bar_icon_vertical_padding = 0x7f080003; public static final int abc_action_bar_progress_bar_size = 0x7f08000a; public static final int abc_action_bar_stacked_max_height = 0x7f080009; public static final int abc_action_bar_stacked_tab_max_width = 0x7f080001; public static final int abc_action_bar_subtitle_bottom_margin = 0x7f080007; public static final int abc_action_bar_subtitle_text_size = 0x7f080005; public static final int abc_action_bar_subtitle_top_margin = 0x7f080006; public static final int abc_action_bar_title_text_size = 0x7f080004; public static final int abc_action_button_min_width = 0x7f080008; public static final int abc_config_prefDialogWidth = 0x7f080000; public static final int abc_dropdownitem_icon_width = 0x7f080010; public static final int abc_dropdownitem_text_padding_left = 0x7f08000e; public static final int abc_dropdownitem_text_padding_right = 0x7f08000f; public static final int abc_panel_menu_list_width = 0x7f08000b; public static final int abc_search_view_preferred_width = 0x7f08000d; public static final int abc_search_view_text_min_width = 0x7f08000c; public static final int dialog_fixed_height_major = 0x7f080013; public static final int dialog_fixed_height_minor = 0x7f080014; public static final int dialog_fixed_width_major = 0x7f080011; public static final int dialog_fixed_width_minor = 0x7f080012; } public static final class drawable { public static final int abc_ab_bottom_solid_dark_holo = 0x7f020000; public static final int abc_ab_bottom_solid_light_holo = 0x7f020001; public static final int abc_ab_bottom_transparent_dark_holo = 0x7f020002; public static final int abc_ab_bottom_transparent_light_holo = 0x7f020003; public static final int abc_ab_share_pack_holo_dark = 0x7f020004; public static final int abc_ab_share_pack_holo_light = 0x7f020005; public static final int abc_ab_solid_dark_holo = 0x7f020006; public static final int abc_ab_solid_light_holo = 0x7f020007; public static final int abc_ab_stacked_solid_dark_holo = 0x7f020008; public static final int abc_ab_stacked_solid_light_holo = 0x7f020009; public static final int abc_ab_stacked_transparent_dark_holo = 0x7f02000a; public static final int abc_ab_stacked_transparent_light_holo = 0x7f02000b; public static final int abc_ab_transparent_dark_holo = 0x7f02000c; public static final int abc_ab_transparent_light_holo = 0x7f02000d; public static final int abc_cab_background_bottom_holo_dark = 0x7f02000e; public static final int abc_cab_background_bottom_holo_light = 0x7f02000f; public static final int abc_cab_background_top_holo_dark = 0x7f020010; public static final int abc_cab_background_top_holo_light = 0x7f020011; public static final int abc_ic_ab_back_holo_dark = 0x7f020012; public static final int abc_ic_ab_back_holo_light = 0x7f020013; public static final int abc_ic_cab_done_holo_dark = 0x7f020014; public static final int abc_ic_cab_done_holo_light = 0x7f020015; public static final int abc_ic_clear = 0x7f020016; public static final int abc_ic_clear_disabled = 0x7f020017; public static final int abc_ic_clear_holo_light = 0x7f020018; public static final int abc_ic_clear_normal = 0x7f020019; public static final int abc_ic_clear_search_api_disabled_holo_light = 0x7f02001a; public static final int abc_ic_clear_search_api_holo_light = 0x7f02001b; public static final int abc_ic_commit_search_api_holo_dark = 0x7f02001c; public static final int abc_ic_commit_search_api_holo_light = 0x7f02001d; public static final int abc_ic_go = 0x7f02001e; public static final int abc_ic_go_search_api_holo_light = 0x7f02001f; public static final int abc_ic_menu_moreoverflow_normal_holo_dark = 0x7f020020; public static final int abc_ic_menu_moreoverflow_normal_holo_light = 0x7f020021; public static final int abc_ic_menu_share_holo_dark = 0x7f020022; public static final int abc_ic_menu_share_holo_light = 0x7f020023; public static final int abc_ic_search = 0x7f020024; public static final int abc_ic_search_api_holo_light = 0x7f020025; public static final int abc_ic_voice_search = 0x7f020026; public static final int abc_ic_voice_search_api_holo_light = 0x7f020027; public static final int abc_item_background_holo_dark = 0x7f020028; public static final int abc_item_background_holo_light = 0x7f020029; public static final int abc_list_divider_holo_dark = 0x7f02002a; public static final int abc_list_divider_holo_light = 0x7f02002b; public static final int abc_list_focused_holo = 0x7f02002c; public static final int abc_list_longpressed_holo = 0x7f02002d; public static final int abc_list_pressed_holo_dark = 0x7f02002e; public static final int abc_list_pressed_holo_light = 0x7f02002f; public static final int abc_list_selector_background_transition_holo_dark = 0x7f020030; public static final int abc_list_selector_background_transition_holo_light = 0x7f020031; public static final int abc_list_selector_disabled_holo_dark = 0x7f020032; public static final int abc_list_selector_disabled_holo_light = 0x7f020033; public static final int abc_list_selector_holo_dark = 0x7f020034; public static final int abc_list_selector_holo_light = 0x7f020035; public static final int abc_menu_dropdown_panel_holo_dark = 0x7f020036; public static final int abc_menu_dropdown_panel_holo_light = 0x7f020037; public static final int abc_menu_hardkey_panel_holo_dark = 0x7f020038; public static final int abc_menu_hardkey_panel_holo_light = 0x7f020039; public static final int abc_search_dropdown_dark = 0x7f02003a; public static final int abc_search_dropdown_light = 0x7f02003b; public static final int abc_spinner_ab_default_holo_dark = 0x7f02003c; public static final int abc_spinner_ab_default_holo_light = 0x7f02003d; public static final int abc_spinner_ab_disabled_holo_dark = 0x7f02003e; public static final int abc_spinner_ab_disabled_holo_light = 0x7f02003f; public static final int abc_spinner_ab_focused_holo_dark = 0x7f020040; public static final int abc_spinner_ab_focused_holo_light = 0x7f020041; public static final int abc_spinner_ab_holo_dark = 0x7f020042; public static final int abc_spinner_ab_holo_light = 0x7f020043; public static final int abc_spinner_ab_pressed_holo_dark = 0x7f020044; public static final int abc_spinner_ab_pressed_holo_light = 0x7f020045; public static final int abc_tab_indicator_ab_holo = 0x7f020046; public static final int abc_tab_selected_focused_holo = 0x7f020047; public static final int abc_tab_selected_holo = 0x7f020048; public static final int abc_tab_selected_pressed_holo = 0x7f020049; public static final int abc_tab_unselected_pressed_holo = 0x7f02004a; public static final int abc_textfield_search_default_holo_dark = 0x7f02004b; public static final int abc_textfield_search_default_holo_light = 0x7f02004c; public static final int abc_textfield_search_right_default_holo_dark = 0x7f02004d; public static final int abc_textfield_search_right_default_holo_light = 0x7f02004e; public static final int abc_textfield_search_right_selected_holo_dark = 0x7f02004f; public static final int abc_textfield_search_right_selected_holo_light = 0x7f020050; public static final int abc_textfield_search_selected_holo_dark = 0x7f020051; public static final int abc_textfield_search_selected_holo_light = 0x7f020052; public static final int abc_textfield_searchview_holo_dark = 0x7f020053; public static final int abc_textfield_searchview_holo_light = 0x7f020054; public static final int abc_textfield_searchview_right_holo_dark = 0x7f020055; public static final int abc_textfield_searchview_right_holo_light = 0x7f020056; } public static final class id { public static final int action_bar = 0x7f05001c; public static final int action_bar_activity_content = 0x7f050015; public static final int action_bar_container = 0x7f05001b; public static final int action_bar_overlay_layout = 0x7f05001f; public static final int action_bar_root = 0x7f05001a; public static final int action_bar_subtitle = 0x7f050023; public static final int action_bar_title = 0x7f050022; public static final int action_context_bar = 0x7f05001d; public static final int action_menu_divider = 0x7f050016; public static final int action_menu_presenter = 0x7f050017; public static final int action_mode_close_button = 0x7f050024; public static final int activity_chooser_view_content = 0x7f050025; public static final int always = 0x7f05000b; public static final int beginning = 0x7f050011; public static final int checkbox = 0x7f05002d; public static final int collapseActionView = 0x7f05000d; public static final int default_activity_button = 0x7f050028; public static final int dialog = 0x7f05000e; public static final int disableHome = 0x7f050008; public static final int dropdown = 0x7f05000f; public static final int edit_query = 0x7f050030; public static final int end = 0x7f050013; public static final int expand_activities_button = 0x7f050026; public static final int expanded_menu = 0x7f05002c; public static final int home = 0x7f050014; public static final int homeAsUp = 0x7f050005; public static final int icon = 0x7f05002a; public static final int ifRoom = 0x7f05000a; public static final int image = 0x7f050027; public static final int listMode = 0x7f050001; public static final int list_item = 0x7f050029; public static final int middle = 0x7f050012; public static final int never = 0x7f050009; public static final int none = 0x7f050010; public static final int normal = 0x7f050000; public static final int progress_circular = 0x7f050018; public static final int progress_horizontal = 0x7f050019; public static final int radio = 0x7f05002f; public static final int search_badge = 0x7f050032; public static final int search_bar = 0x7f050031; public static final int search_button = 0x7f050033; public static final int search_close_btn = 0x7f050038; public static final int search_edit_frame = 0x7f050034; public static final int search_go_btn = 0x7f05003a; public static final int search_mag_icon = 0x7f050035; public static final int search_plate = 0x7f050036; public static final int search_src_text = 0x7f050037; public static final int search_voice_btn = 0x7f05003b; public static final int shortcut = 0x7f05002e; public static final int showCustom = 0x7f050007; public static final int showHome = 0x7f050004; public static final int showTitle = 0x7f050006; public static final int split_action_bar = 0x7f05001e; public static final int submit_area = 0x7f050039; public static final int tabMode = 0x7f050002; public static final int title = 0x7f05002b; public static final int top_action_bar = 0x7f050020; public static final int up = 0x7f050021; public static final int useLogo = 0x7f050003; public static final int withText = 0x7f05000c; } public static final class integer { public static final int abc_max_action_buttons = 0x7f090000; } public static final class layout { public static final int abc_action_bar_decor = 0x7f030000; public static final int abc_action_bar_decor_include = 0x7f030001; public static final int abc_action_bar_decor_overlay = 0x7f030002; public static final int abc_action_bar_home = 0x7f030003; public static final int abc_action_bar_tab = 0x7f030004; public static final int abc_action_bar_tabbar = 0x7f030005; public static final int abc_action_bar_title_item = 0x7f030006; public static final int abc_action_bar_view_list_nav_layout = 0x7f030007; public static final int abc_action_menu_item_layout = 0x7f030008; public static final int abc_action_menu_layout = 0x7f030009; public static final int abc_action_mode_bar = 0x7f03000a; public static final int abc_action_mode_close_item = 0x7f03000b; public static final int abc_activity_chooser_view = 0x7f03000c; public static final int abc_activity_chooser_view_include = 0x7f03000d; public static final int abc_activity_chooser_view_list_item = 0x7f03000e; public static final int abc_expanded_menu_layout = 0x7f03000f; public static final int abc_list_menu_item_checkbox = 0x7f030010; public static final int abc_list_menu_item_icon = 0x7f030011; public static final int abc_list_menu_item_layout = 0x7f030012; public static final int abc_list_menu_item_radio = 0x7f030013; public static final int abc_popup_menu_item_layout = 0x7f030014; public static final int abc_search_dropdown_item_icons_2line = 0x7f030015; public static final int abc_search_view = 0x7f030016; public static final int abc_simple_decor = 0x7f030017; public static final int support_simple_spinner_dropdown_item = 0x7f030019; } public static final class string { public static final int abc_action_bar_home_description = 0x7f0a0001; public static final int abc_action_bar_up_description = 0x7f0a0002; public static final int abc_action_menu_overflow_description = 0x7f0a0003; public static final int abc_action_mode_done = 0x7f0a0000; public static final int abc_activity_chooser_view_see_all = 0x7f0a000a; public static final int abc_activitychooserview_choose_application = 0x7f0a0009; public static final int abc_searchview_description_clear = 0x7f0a0006; public static final int abc_searchview_description_query = 0x7f0a0005; public static final int abc_searchview_description_search = 0x7f0a0004; public static final int abc_searchview_description_submit = 0x7f0a0007; public static final int abc_searchview_description_voice = 0x7f0a0008; public static final int abc_shareactionprovider_share_with = 0x7f0a000c; public static final int abc_shareactionprovider_share_with_application = 0x7f0a000b; } public static final class style { public static final int TextAppearance_AppCompat_Base_CompactMenu_Dialog = 0x7f0b0063; public static final int TextAppearance_AppCompat_Base_SearchResult = 0x7f0b006d; public static final int TextAppearance_AppCompat_Base_SearchResult_Subtitle = 0x7f0b006f; public static final int TextAppearance_AppCompat_Base_SearchResult_Title = 0x7f0b006e; public static final int TextAppearance_AppCompat_Base_Widget_PopupMenu_Large = 0x7f0b0069; public static final int TextAppearance_AppCompat_Base_Widget_PopupMenu_Small = 0x7f0b006a; public static final int TextAppearance_AppCompat_Light_Base_SearchResult = 0x7f0b0070; public static final int TextAppearance_AppCompat_Light_Base_SearchResult_Subtitle = 0x7f0b0072; public static final int TextAppearance_AppCompat_Light_Base_SearchResult_Title = 0x7f0b0071; public static final int TextAppearance_AppCompat_Light_Base_Widget_PopupMenu_Large = 0x7f0b006b; public static final int TextAppearance_AppCompat_Light_Base_Widget_PopupMenu_Small = 0x7f0b006c; public static final int TextAppearance_AppCompat_Light_SearchResult_Subtitle = 0x7f0b0035; public static final int TextAppearance_AppCompat_Light_SearchResult_Title = 0x7f0b0034; public static final int TextAppearance_AppCompat_Light_Widget_PopupMenu_Large = 0x7f0b0030; public static final int TextAppearance_AppCompat_Light_Widget_PopupMenu_Small = 0x7f0b0031; public static final int TextAppearance_AppCompat_SearchResult_Subtitle = 0x7f0b0033; public static final int TextAppearance_AppCompat_SearchResult_Title = 0x7f0b0032; public static final int TextAppearance_AppCompat_Widget_ActionBar_Menu = 0x7f0b001a; public static final int TextAppearance_AppCompat_Widget_ActionBar_Subtitle = 0x7f0b0006; public static final int TextAppearance_AppCompat_Widget_ActionBar_Subtitle_Inverse = 0x7f0b0008; public static final int TextAppearance_AppCompat_Widget_ActionBar_Title = 0x7f0b0005; public static final int TextAppearance_AppCompat_Widget_ActionBar_Title_Inverse = 0x7f0b0007; public static final int TextAppearance_AppCompat_Widget_ActionMode_Subtitle = 0x7f0b001e; public static final int TextAppearance_AppCompat_Widget_ActionMode_Subtitle_Inverse = 0x7f0b0020; public static final int TextAppearance_AppCompat_Widget_ActionMode_Title = 0x7f0b001d; public static final int TextAppearance_AppCompat_Widget_ActionMode_Title_Inverse = 0x7f0b001f; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Menu = 0x7f0b0054; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Subtitle = 0x7f0b0056; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Subtitle_Inverse = 0x7f0b0058; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Title = 0x7f0b0055; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Title_Inverse = 0x7f0b0057; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Subtitle = 0x7f0b0051; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Subtitle_Inverse = 0x7f0b0053; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Title = 0x7f0b0050; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Title_Inverse = 0x7f0b0052; public static final int TextAppearance_AppCompat_Widget_Base_DropDownItem = 0x7f0b0061; public static final int TextAppearance_AppCompat_Widget_DropDownItem = 0x7f0b0021; public static final int TextAppearance_AppCompat_Widget_PopupMenu_Large = 0x7f0b002e; public static final int TextAppearance_AppCompat_Widget_PopupMenu_Small = 0x7f0b002f; public static final int TextAppearance_Widget_AppCompat_Base_ExpandedMenu_Item = 0x7f0b0062; public static final int TextAppearance_Widget_AppCompat_ExpandedMenu_Item = 0x7f0b0028; public static final int Theme_AppCompat = 0x7f0b0077; public static final int Theme_AppCompat_Base_CompactMenu = 0x7f0b0083; public static final int Theme_AppCompat_Base_CompactMenu_Dialog = 0x7f0b0084; public static final int Theme_AppCompat_CompactMenu = 0x7f0b007c; public static final int Theme_AppCompat_CompactMenu_Dialog = 0x7f0b007d; public static final int Theme_AppCompat_DialogWhenLarge = 0x7f0b007a; public static final int Theme_AppCompat_Light = 0x7f0b0078; public static final int Theme_AppCompat_Light_DarkActionBar = 0x7f0b0079; public static final int Theme_AppCompat_Light_DialogWhenLarge = 0x7f0b007b; public static final int Theme_Base = 0x7f0b007e; public static final int Theme_Base_AppCompat = 0x7f0b0080; public static final int Theme_Base_AppCompat_DialogWhenLarge = 0x7f0b0085; public static final int Theme_Base_AppCompat_DialogWhenLarge_Base = 0x7f0b0089; public static final int Theme_Base_AppCompat_Dialog_FixedSize = 0x7f0b0087; public static final int Theme_Base_AppCompat_Dialog_Light_FixedSize = 0x7f0b0088; public static final int Theme_Base_AppCompat_Light = 0x7f0b0081; public static final int Theme_Base_AppCompat_Light_DarkActionBar = 0x7f0b0082; public static final int Theme_Base_AppCompat_Light_DialogWhenLarge = 0x7f0b0086; public static final int Theme_Base_AppCompat_Light_DialogWhenLarge_Base = 0x7f0b008a; public static final int Theme_Base_Light = 0x7f0b007f; public static final int Widget_AppCompat_ActionBar = 0x7f0b0000; public static final int Widget_AppCompat_ActionBar_Solid = 0x7f0b0002; public static final int Widget_AppCompat_ActionBar_TabBar = 0x7f0b0011; public static final int Widget_AppCompat_ActionBar_TabText = 0x7f0b0017; public static final int Widget_AppCompat_ActionBar_TabView = 0x7f0b0014; public static final int Widget_AppCompat_ActionButton = 0x7f0b000b; public static final int Widget_AppCompat_ActionButton_CloseMode = 0x7f0b000d; public static final int Widget_AppCompat_ActionButton_Overflow = 0x7f0b000f; public static final int Widget_AppCompat_ActionMode = 0x7f0b001b; public static final int Widget_AppCompat_ActivityChooserView = 0x7f0b0038; public static final int Widget_AppCompat_AutoCompleteTextView = 0x7f0b0036; public static final int Widget_AppCompat_Base_ActionBar = 0x7f0b003a; public static final int Widget_AppCompat_Base_ActionBar_Solid = 0x7f0b003c; public static final int Widget_AppCompat_Base_ActionBar_TabBar = 0x7f0b0045; public static final int Widget_AppCompat_Base_ActionBar_TabText = 0x7f0b004b; public static final int Widget_AppCompat_Base_ActionBar_TabView = 0x7f0b0048; public static final int Widget_AppCompat_Base_ActionButton = 0x7f0b003f; public static final int Widget_AppCompat_Base_ActionButton_CloseMode = 0x7f0b0041; public static final int Widget_AppCompat_Base_ActionButton_Overflow = 0x7f0b0043; public static final int Widget_AppCompat_Base_ActionMode = 0x7f0b004e; public static final int Widget_AppCompat_Base_ActivityChooserView = 0x7f0b0075; public static final int Widget_AppCompat_Base_AutoCompleteTextView = 0x7f0b0073; public static final int Widget_AppCompat_Base_DropDownItem_Spinner = 0x7f0b005d; public static final int Widget_AppCompat_Base_ListPopupWindow = 0x7f0b0065; public static final int Widget_AppCompat_Base_ListView_DropDown = 0x7f0b005f; public static final int Widget_AppCompat_Base_ListView_Menu = 0x7f0b0064; public static final int Widget_AppCompat_Base_PopupMenu = 0x7f0b0067; public static final int Widget_AppCompat_Base_ProgressBar = 0x7f0b005a; public static final int Widget_AppCompat_Base_ProgressBar_Horizontal = 0x7f0b0059; public static final int Widget_AppCompat_Base_Spinner = 0x7f0b005b; public static final int Widget_AppCompat_DropDownItem_Spinner = 0x7f0b0024; public static final int Widget_AppCompat_Light_ActionBar = 0x7f0b0001; public static final int Widget_AppCompat_Light_ActionBar_Solid = 0x7f0b0003; public static final int Widget_AppCompat_Light_ActionBar_Solid_Inverse = 0x7f0b0004; public static final int Widget_AppCompat_Light_ActionBar_TabBar = 0x7f0b0012; public static final int Widget_AppCompat_Light_ActionBar_TabBar_Inverse = 0x7f0b0013; public static final int Widget_AppCompat_Light_ActionBar_TabText = 0x7f0b0018; public static final int Widget_AppCompat_Light_ActionBar_TabText_Inverse = 0x7f0b0019; public static final int Widget_AppCompat_Light_ActionBar_TabView = 0x7f0b0015; public static final int Widget_AppCompat_Light_ActionBar_TabView_Inverse = 0x7f0b0016; public static final int Widget_AppCompat_Light_ActionButton = 0x7f0b000c; public static final int Widget_AppCompat_Light_ActionButton_CloseMode = 0x7f0b000e; public static final int Widget_AppCompat_Light_ActionButton_Overflow = 0x7f0b0010; public static final int Widget_AppCompat_Light_ActionMode_Inverse = 0x7f0b001c; public static final int Widget_AppCompat_Light_ActivityChooserView = 0x7f0b0039; public static final int Widget_AppCompat_Light_AutoCompleteTextView = 0x7f0b0037; public static final int Widget_AppCompat_Light_Base_ActionBar = 0x7f0b003b; public static final int Widget_AppCompat_Light_Base_ActionBar_Solid = 0x7f0b003d; public static final int Widget_AppCompat_Light_Base_ActionBar_Solid_Inverse = 0x7f0b003e; public static final int Widget_AppCompat_Light_Base_ActionBar_TabBar = 0x7f0b0046; public static final int Widget_AppCompat_Light_Base_ActionBar_TabBar_Inverse = 0x7f0b0047; public static final int Widget_AppCompat_Light_Base_ActionBar_TabText = 0x7f0b004c; public static final int Widget_AppCompat_Light_Base_ActionBar_TabText_Inverse = 0x7f0b004d; public static final int Widget_AppCompat_Light_Base_ActionBar_TabView = 0x7f0b0049; public static final int Widget_AppCompat_Light_Base_ActionBar_TabView_Inverse = 0x7f0b004a; public static final int Widget_AppCompat_Light_Base_ActionButton = 0x7f0b0040; public static final int Widget_AppCompat_Light_Base_ActionButton_CloseMode = 0x7f0b0042; public static final int Widget_AppCompat_Light_Base_ActionButton_Overflow = 0x7f0b0044; public static final int Widget_AppCompat_Light_Base_ActionMode_Inverse = 0x7f0b004f; public static final int Widget_AppCompat_Light_Base_ActivityChooserView = 0x7f0b0076; public static final int Widget_AppCompat_Light_Base_AutoCompleteTextView = 0x7f0b0074; public static final int Widget_AppCompat_Light_Base_DropDownItem_Spinner = 0x7f0b005e; public static final int Widget_AppCompat_Light_Base_ListPopupWindow = 0x7f0b0066; public static final int Widget_AppCompat_Light_Base_ListView_DropDown = 0x7f0b0060; public static final int Widget_AppCompat_Light_Base_PopupMenu = 0x7f0b0068; public static final int Widget_AppCompat_Light_Base_Spinner = 0x7f0b005c; public static final int Widget_AppCompat_Light_DropDownItem_Spinner = 0x7f0b0025; public static final int Widget_AppCompat_Light_ListPopupWindow = 0x7f0b002a; public static final int Widget_AppCompat_Light_ListView_DropDown = 0x7f0b0027; public static final int Widget_AppCompat_Light_PopupMenu = 0x7f0b002c; public static final int Widget_AppCompat_Light_Spinner_DropDown_ActionBar = 0x7f0b0023; public static final int Widget_AppCompat_ListPopupWindow = 0x7f0b0029; public static final int Widget_AppCompat_ListView_DropDown = 0x7f0b0026; public static final int Widget_AppCompat_ListView_Menu = 0x7f0b002d; public static final int Widget_AppCompat_PopupMenu = 0x7f0b002b; public static final int Widget_AppCompat_ProgressBar = 0x7f0b000a; public static final int Widget_AppCompat_ProgressBar_Horizontal = 0x7f0b0009; public static final int Widget_AppCompat_Spinner_DropDown_ActionBar = 0x7f0b0022; } public static final class styleable { public static final int[] ActionBar = { 0x7f010025, 0x7f010026, 0x7f010027, 0x7f010028, 0x7f010029, 0x7f01002a, 0x7f01002b, 0x7f01002c, 0x7f01002d, 0x7f01002e, 0x7f01002f, 0x7f010030, 0x7f010031, 0x7f010032, 0x7f010033, 0x7f010034, 0x7f010035, 0x7f010036, 0x7f010037 }; public static final int[] ActionBarLayout = { 0x010100b3 }; public static final int ActionBarLayout_android_layout_gravity = 0; public static final int[] ActionBarWindow = { 0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003, 0x7f010004, 0x7f010005, 0x7f010006 }; public static final int ActionBarWindow_windowActionBar = 0; public static final int ActionBarWindow_windowActionBarOverlay = 1; public static final int ActionBarWindow_windowFixedHeightMajor = 6; public static final int ActionBarWindow_windowFixedHeightMinor = 4; public static final int ActionBarWindow_windowFixedWidthMajor = 3; public static final int ActionBarWindow_windowFixedWidthMinor = 5; public static final int ActionBarWindow_windowSplitActionBar = 2; public static final int ActionBar_background = 10; public static final int ActionBar_backgroundSplit = 12; public static final int ActionBar_backgroundStacked = 11; public static final int ActionBar_customNavigationLayout = 13; public static final int ActionBar_displayOptions = 3; public static final int ActionBar_divider = 9; public static final int ActionBar_height = 1; public static final int ActionBar_homeLayout = 14; public static final int ActionBar_icon = 7; public static final int ActionBar_indeterminateProgressStyle = 16; public static final int ActionBar_itemPadding = 18; public static final int ActionBar_logo = 8; public static final int ActionBar_navigationMode = 2; public static final int ActionBar_progressBarPadding = 17; public static final int ActionBar_progressBarStyle = 15; public static final int ActionBar_subtitle = 4; public static final int ActionBar_subtitleTextStyle = 6; public static final int ActionBar_title = 0; public static final int ActionBar_titleTextStyle = 5; public static final int[] ActionMenuItemView = { 0x0101013f }; public static final int ActionMenuItemView_android_minWidth = 0; public static final int[] ActionMenuView = { }; public static final int[] ActionMode = { 0x7f010026, 0x7f01002a, 0x7f01002b, 0x7f01002f, 0x7f010031 }; public static final int ActionMode_background = 3; public static final int ActionMode_backgroundSplit = 4; public static final int ActionMode_height = 0; public static final int ActionMode_subtitleTextStyle = 2; public static final int ActionMode_titleTextStyle = 1; public static final int[] ActivityChooserView = { 0x7f01006a, 0x7f01006b }; public static final int ActivityChooserView_expandActivityOverflowButtonDrawable = 1; public static final int ActivityChooserView_initialActivityCount = 0; public static final int[] CompatTextView = { 0x7f01006d }; public static final int CompatTextView_textAllCaps = 0; public static final int[] LinearLayoutICS = { 0x7f01002e, 0x7f010055, 0x7f010056 }; public static final int LinearLayoutICS_divider = 0; public static final int LinearLayoutICS_dividerPadding = 2; public static final int LinearLayoutICS_showDividers = 1; public static final int[] MenuGroup = { 0x0101000e, 0x010100d0, 0x01010194, 0x010101de, 0x010101df, 0x010101e0 }; public static final int MenuGroup_android_checkableBehavior = 5; public static final int MenuGroup_android_enabled = 0; public static final int MenuGroup_android_id = 1; public static final int MenuGroup_android_menuCategory = 3; public static final int MenuGroup_android_orderInCategory = 4; public static final int MenuGroup_android_visible = 2; public static final int[] MenuItem = { 0x01010002, 0x0101000e, 0x010100d0, 0x01010106, 0x01010194, 0x010101de, 0x010101df, 0x010101e1, 0x010101e2, 0x010101e3, 0x010101e4, 0x010101e5, 0x0101026f, 0x7f01004d, 0x7f01004e, 0x7f01004f, 0x7f010050 }; public static final int MenuItem_actionLayout = 14; public static final int MenuItem_actionProviderClass = 16; public static final int MenuItem_actionViewClass = 15; public static final int MenuItem_android_alphabeticShortcut = 9; public static final int MenuItem_android_checkable = 11; public static final int MenuItem_android_checked = 3; public static final int MenuItem_android_enabled = 1; public static final int MenuItem_android_icon = 0; public static final int MenuItem_android_id = 2; public static final int MenuItem_android_menuCategory = 5; public static final int MenuItem_android_numericShortcut = 10; public static final int MenuItem_android_onClick = 12; public static final int MenuItem_android_orderInCategory = 6; public static final int MenuItem_android_title = 7; public static final int MenuItem_android_titleCondensed = 8; public static final int MenuItem_android_visible = 4; public static final int MenuItem_showAsAction = 13; public static final int[] MenuView = { 0x010100ae, 0x0101012c, 0x0101012d, 0x0101012e, 0x0101012f, 0x01010130, 0x01010131, 0x01010438 }; public static final int MenuView_android_headerBackground = 4; public static final int MenuView_android_horizontalDivider = 2; public static final int MenuView_android_itemBackground = 5; public static final int MenuView_android_itemIconDisabledAlpha = 6; public static final int MenuView_android_itemTextAppearance = 1; public static final int MenuView_android_preserveIconSpacing = 7; public static final int MenuView_android_verticalDivider = 3; public static final int MenuView_android_windowAnimationStyle = 0; public static final int[] SearchView = { 0x0101011f, 0x01010220, 0x01010264, 0x7f01005a, 0x7f01005b }; public static final int SearchView_android_imeOptions = 2; public static final int SearchView_android_inputType = 1; public static final int SearchView_android_maxWidth = 0; public static final int SearchView_iconifiedByDefault = 3; public static final int SearchView_queryHint = 4; public static final int[] Spinner = { 0x010100af, 0x01010175, 0x01010176, 0x01010262, 0x010102ac, 0x010102ad, 0x7f010051, 0x7f010052, 0x7f010053, 0x7f010054 }; public static final int Spinner_android_dropDownHorizontalOffset = 4; public static final int Spinner_android_dropDownSelector = 1; public static final int Spinner_android_dropDownVerticalOffset = 5; public static final int Spinner_android_dropDownWidth = 3; public static final int Spinner_android_gravity = 0; public static final int Spinner_android_popupBackground = 2; public static final int Spinner_disableChildrenWhenDisabled = 9; public static final int Spinner_popupPromptView = 8; public static final int Spinner_prompt = 6; public static final int Spinner_spinnerMode = 7; public static final int[] Theme = { 0x7f010047, 0x7f010048, 0x7f010049, 0x7f01004a, 0x7f01004b, 0x7f01004c }; public static final int Theme_actionDropDownStyle = 0; public static final int Theme_dropdownListPreferredItemHeight = 1; public static final int Theme_listChoiceBackgroundIndicator = 5; public static final int Theme_panelMenuListTheme = 4; public static final int Theme_panelMenuListWidth = 3; public static final int Theme_popupMenuStyle = 2; public static final int[] View = { 0x010100da, 0x7f010038, 0x7f010039 }; public static final int View_android_focusable = 0; public static final int View_paddingEnd = 2; public static final int View_paddingStart = 1; } }
package tlc2.tool; import java.io.IOException; import java.io.Serializable; import java.util.Set; import java.util.HashMap; import tla2sany.semantic.OpDeclNode; import tla2sany.semantic.SemanticNode; import tla2sany.semantic.SymbolNode; import tlc2.value.Value; import tlc2.value.ValueInputStream; import tlc2.value.ValueOutputStream; import util.UniqueString; public abstract class TLCState implements Cloneable, Serializable { public long uid = -1; // Must be set to a non-negative number // Set by subclasses. Cannot set until we know what the variables are. public static TLCState Empty = null; // The state variables. protected static OpDeclNode[] vars = null; public static void setVariables(OpDeclNode[] variables) { vars = variables; // SZ 10.04.2009: since this method is called exactly one from Spec#processSpec // moved the call of UniqueString#setVariables to that place // UniqueString[] varNames = new UniqueString[variables.length]; // for (int i = 0; i < varNames.length; i++) // varNames[i] = variables[i].getName(); //UniqueString.setVariables(varNames); } public void read(ValueInputStream vis) throws IOException { this.uid = vis.readLongNat(); } public void write(ValueOutputStream vos) throws IOException { vos.writeLongNat(this.uid); } public abstract TLCState bind(UniqueString name, Value value, SemanticNode expr); public abstract TLCState bind(SymbolNode id, Value value, SemanticNode expr); public abstract TLCState unbind(UniqueString name); public abstract Value lookup(UniqueString var); public abstract boolean containsKey(UniqueString var); public abstract TLCState copy(); public abstract TLCState deepCopy(); public abstract StateVec addToVec(StateVec states); public abstract void deepNormalize(); public abstract long fingerPrint(); public abstract boolean allAssigned(); public abstract Set<OpDeclNode> getUnassigned(); public abstract TLCState createEmpty(); /** * Returns a mapping of variable names to their assigned values in this state. */ public HashMap<UniqueString, Value> getVals() { HashMap<UniqueString, Value> valMap = new HashMap<UniqueString, Value>(); for(int i = 0; i < vars.length; i++) { UniqueString key = vars[i].getName(); Value val = this.lookup(key); valMap.put(key, val); } return valMap; } /* Returns a string representation of this state. */ public abstract String toString(); public abstract String toString(TLCState lastState); }
package mod._sc; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XIndexAccess; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.sheet.DataPilotFieldOrientation; import com.sun.star.sheet.TableFilterField; import com.sun.star.sheet.XDataPilotDescriptor; import com.sun.star.sheet.XDataPilotTables; import com.sun.star.sheet.XDataPilotTablesSupplier; import com.sun.star.sheet.XSheetFilterDescriptor; import com.sun.star.sheet.XSpreadsheet; import com.sun.star.sheet.XSpreadsheetDocument; import com.sun.star.sheet.XSpreadsheets; import com.sun.star.table.CellAddress; import com.sun.star.table.CellRangeAddress; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import java.io.PrintWriter; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.SOfficeFactory; /** * Test for object which is represented by service * <code>com.sun.star.sheet.DataPilotField</code>. <p> * Object implements the following interfaces : * <ul> * <li> <code>com::sun::star::container::XNamed</code></li> * <li> <code>com::sun::star::sheet::DataPilotField</code></li> * <li> <code>com::sun::star::beans::XPropertySet</code></li> * </ul> * @see com.sun.star.sheet.DataPilotField * @see com.sun.star.container.XNamed * @see com.sun.star.sheet.DataPilotField * @see com.sun.star.beans.XPropertySet * @see ifc.container._XNamed * @see ifc.sheet._DataPilotField * @see ifc.beans._XPropertySet */ public class ScDataPilotFieldObj extends TestCase { XSpreadsheetDocument xSheetDoc = null; /** * A field is filled some values. This integer determines the size of the * field in x and y direction. */ private int mMaxFieldIndex = 6; /** * Creates Spreadsheet document. */ protected void initialize(TestParameters tParam, PrintWriter log) { SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory) tParam.getMSF()); try { log.println("creating a Spreadsheet document"); xSheetDoc = SOF.createCalcDoc(null); } catch (com.sun.star.uno.Exception e) { // Some exception occures.FAILED e.printStackTrace(log); throw new StatusException("Couldn't create document", e); } } /** * Disposes Spreadsheet document. */ protected void cleanup(TestParameters tParam, PrintWriter log) { log.println(" disposing xSheetDoc "); XComponent oComp = (XComponent) UnoRuntime.queryInterface( XComponent.class, xSheetDoc); util.DesktopTools.closeDoc(oComp); } /** * Creating a Testenvironment for the interfaces to be tested. * Retrieves a collection of spreadsheets from a document * and takes one of them. Fills some table in the spreadsheet. * Obtains the collection of data pilot tables using the interface * <code>XDataPilotTablesSupplier</code>. Creates a data pilot descriptor * for the filled table and inserts new data pilot table with this descriptor * to the collection. Obtains the collection of all the data pilot fields * using the interface <code>XDataPilotDescriptor</code>. Retrieves from * the collection the data pilot field with index 0. This data pilot field * is the instance of the service <code>com.sun.star.sheet.DataPilotField</code>. * @see com.sun.star.sheet.DataPilotField * @see com.sun.star.sheet.XDataPilotTablesSupplier * @see com.sun.star.sheet.XDataPilotDescriptor */ protected synchronized TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) { XInterface oObj = null; // creation of testobject here // first we write what we are intend to do to log file log.println("Creating a test environment"); // the cell range CellRangeAddress sCellRangeAdress = new CellRangeAddress(); sCellRangeAdress.Sheet = 0; sCellRangeAdress.StartColumn = 1; sCellRangeAdress.StartRow = 0; sCellRangeAdress.EndColumn = mMaxFieldIndex - 1; sCellRangeAdress.EndRow = mMaxFieldIndex - 1; // position of the data pilot table CellAddress sCellAdress = new CellAddress(); sCellAdress.Sheet = 0; sCellAdress.Column = 7; sCellAdress.Row = 8; log.println("Getting a sheet"); XSpreadsheets xSpreadsheets = (XSpreadsheets) xSheetDoc.getSheets(); XSpreadsheet oSheet = null; XSpreadsheet oSheet2 = null; XIndexAccess oIndexAccess = (XIndexAccess) UnoRuntime.queryInterface( XIndexAccess.class, xSpreadsheets); try { oSheet = (XSpreadsheet) AnyConverter.toObject( new Type(XSpreadsheet.class), oIndexAccess.getByIndex(0)); oSheet2 = (XSpreadsheet) AnyConverter.toObject( new Type(XSpreadsheet.class), oIndexAccess.getByIndex(1)); } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace(); throw new StatusException("Couldn't get a spreadsheet", e); } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(); throw new StatusException("Couldn't get a spreadsheet", e); } catch (com.sun.star.lang.IllegalArgumentException e) { e.printStackTrace(); throw new StatusException("Couldn't get a spreadsheet", e); } try { log.println("Filling a table"); for (int i = 1; i < mMaxFieldIndex; i++) { oSheet.getCellByPosition(i, 0).setFormula("Col" + i); oSheet.getCellByPosition(0, i).setFormula("Row" + i); oSheet2.getCellByPosition(i, 0).setFormula("Col" + i); oSheet2.getCellByPosition(0, i).setFormula("Row" + i); } for (int i = 1; i < mMaxFieldIndex; i++) for (int j = 1; j < mMaxFieldIndex; j++) { oSheet.getCellByPosition(i, j).setValue(i * (j + 1)); oSheet2.getCellByPosition(i, j).setValue(i * (j + 2)); } } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(); throw new StatusException("Couldn't fill some cells", e); } // change a value of a cell and check the change in the data pilot // (for the XDataPilotTable.refresh() test) Object oChangeCell = null; Object oCheckCell = null; Integer aChangeValue = null; try { // cell of data oChangeCell = oSheet.getCellByPosition(1, 5); int x = sCellAdress.Column; int y = sCellAdress.Row + 3; // cell of the data pilot output oCheckCell = oSheet.getCellByPosition(x, y); aChangeValue = new Integer(27); } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(); throw new StatusException("Couldn't get cells for changeing.", e); } // create the test objects log.println("Getting test objects"); XDataPilotTablesSupplier DPTS = (XDataPilotTablesSupplier) UnoRuntime.queryInterface( XDataPilotTablesSupplier.class, oSheet); XDataPilotTables DPT = DPTS.getDataPilotTables(); XDataPilotDescriptor DPDsc = DPT.createDataPilotDescriptor(); DPDsc.setSourceRange(sCellRangeAdress); XPropertySet fieldPropSet = null; try { Object oDataPilotField = DPDsc.getDataPilotFields().getByIndex(0); fieldPropSet = (XPropertySet) UnoRuntime.queryInterface( XPropertySet.class, oDataPilotField); } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace(); throw new StatusException("Couldn't create a test environment", e); } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(); throw new StatusException("Couldn't create a test environment", e); } try { fieldPropSet.setPropertyValue("Function", com.sun.star.sheet.GeneralFunction.SUM); fieldPropSet.setPropertyValue("Orientation", com.sun.star.sheet.DataPilotFieldOrientation.DATA); } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace(); throw new StatusException("Couldn't create a test environment", e); } catch (com.sun.star.lang.IllegalArgumentException e) { e.printStackTrace(); throw new StatusException("Couldn't create a test environment", e); } catch (com.sun.star.beans.PropertyVetoException e) { e.printStackTrace(); throw new StatusException("Couldn't create a test environment", e); } catch (com.sun.star.beans.UnknownPropertyException e) { e.printStackTrace(); throw new StatusException("Couldn't create a test environment", e); } log.println("Insert the DataPilotTable"); if (DPT.hasByName("DataPilotTable")) { DPT.removeByName("DataPilotTable"); } XIndexAccess IA = DPDsc.getDataPilotFields(); getSRange(IA); DPT.insertNewByName("DataPilotTable", sCellAdress, DPDsc); try { oObj = (XInterface) AnyConverter.toObject( new Type(XInterface.class), IA.getByIndex(0)); } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace(); throw new StatusException("Couldn't get data pilot field", e); } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(); throw new StatusException("Couldn't get data pilot field", e); } catch (com.sun.star.lang.IllegalArgumentException e) { e.printStackTrace(); throw new StatusException("Couldn't get data pilot field", e); } log.println("Creating object - " + ((oObj == null) ? "FAILED" : "OK")); TestEnvironment tEnv = new TestEnvironment(oObj); log.println("Implementationname: " + util.utils.getImplName(oObj)); // Other parameters required for interface tests return tEnv; } private void getSRange(XIndexAccess IA) { int fieldsAmount = IA.getCount() + 1; String[] fieldsNames = new String[fieldsAmount]; int i = -1; int cnt = 0; while ((++i) < fieldsAmount) { Object field; try { field = IA.getByIndex(i); } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace(log); return; } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(log); return; } XNamed named = (XNamed) UnoRuntime.queryInterface(XNamed.class, field); String name = named.getName(); log.println("**Field : '" + name + "' ... "); if (!name.equals("Data")) { fieldsNames[cnt] = name; XPropertySet props = (XPropertySet) UnoRuntime.queryInterface( XPropertySet.class, field); try { switch (cnt % 5) { case 0: props.setPropertyValue("Orientation", DataPilotFieldOrientation.COLUMN); log.println(" Column"); break; case 1: props.setPropertyValue("Orientation", DataPilotFieldOrientation.ROW); log.println(" Row"); break; case 2: props.setPropertyValue("Orientation", DataPilotFieldOrientation.DATA); log.println(" Data"); break; case 3: props.setPropertyValue("Orientation", DataPilotFieldOrientation.HIDDEN); log.println(" Hidden"); break; case 4: props.setPropertyValue("Orientation", DataPilotFieldOrientation.PAGE); log.println(" Page"); break; } } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace(log); return; } catch (com.sun.star.lang.IllegalArgumentException e) { e.printStackTrace(log); return; } catch (com.sun.star.beans.PropertyVetoException e) { e.printStackTrace(log); return; } catch (com.sun.star.beans.UnknownPropertyException e) { e.printStackTrace(log); return; } if ((++cnt) > 4) { break; } } else { return; } } } }
package com.victoria.rest; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPatch; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import java.io.*; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; @Path("/") public class ApiRoute { @GET @Path("notes") @Produces(MediaType.APPLICATION_JSON) public String getNotes(@Context HttpServletRequest req, @Context HttpServletResponse res) { try { URL url = new URL("http://localhost:9090/v_notes_etudiants?cip=eq." + req.getRemoteUser() + "&trimestre=eq.H17"); InputStream is = url.openStream(); JSONParser jsonParser = new JSONParser(); JSONArray noteResponse = (JSONArray)jsonParser.parse(new InputStreamReader(is, "UTF-8")); if(noteResponse.size() == 0){ return "null"; } JSONObject evaluations = new JSONObject(); JSONObject aps = new JSONObject(); ArrayList notifications = new ArrayList(); URL urlNotif = new URL("http://127.0.0.1:9090/v_notifications?cip=eq." + req.getRemoteUser()); InputStream isNotif = urlNotif.openStream(); JSONParser jsonParserNotif = new JSONParser(); JSONArray notificationResponse = (JSONArray)jsonParserNotif.parse(new InputStreamReader(isNotif, "UTF-8")); getNotifications(notificationResponse, notifications); for (int i = 0; i < noteResponse.size(); i++) { JSONObject currentLine = (JSONObject)noteResponse.get(i); addEvaluation(currentLine, evaluations); addAp(currentLine, aps); } // TODO: to remove JSONArray evals = object2array(evaluations); for(int j = 0; j < evals.size(); j++){ JSONObject activities = (JSONObject) ((JSONObject) evals.get(j)).get("activites"); JSONArray output = new JSONArray(); for(Iterator iterator = activities.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); JSONObject a = new JSONObject(); a.put(key, activities.get(key)); output.add(a); } ((JSONObject) evals.get(j)).remove("activites"); ((JSONObject) evals.get(j)).put("activites", output); } // Making the response JSONObject returnedJSON = new JSONObject(); returnedJSON.put("aps", object2array(aps)); returnedJSON.put("evaluations", evals); returnedJSON.put("notifications", notifications); return returnedJSON.toJSONString(); } catch (Exception e) { e.printStackTrace(); } return "null"; } private void addEvaluation(JSONObject currentLine, JSONObject evaluations) { //Evaluation check String evalID = currentLine.get("evaluation_id").toString(); JSONObject evaluation = (JSONObject)evaluations.get(evalID); if (evaluation == null) { evaluation = new JSONObject(); evaluation.put("id", evalID); evaluation.put("nom", currentLine.get("evaluation")); evaluation.put("activites", new JSONObject()); evaluations.put(evalID, evaluation); } //Activities check JSONObject activities = (JSONObject)evaluation.get("activites"); String apCode = currentLine.get("ap").toString(); JSONArray activity = (JSONArray)activities.get(apCode); if (activity == null) { activity = new JSONArray(); activities.put(apCode, activity); } JSONObject competenceNote = new JSONObject(); // TODO : clean up rounding competenceNote.put("competenceNumero", currentLine.get("competence")); competenceNote.put("note", (Double)(Math.round((Double) currentLine.get("note")*100)/100.0)); competenceNote.put("ponderation", currentLine.get("ponderation")); competenceNote.put("moyenne", (Double)(Math.round((Double) currentLine.get("moyenne")*100)/100.0)); competenceNote.put("ecartType", (Double)(Math.round((Double) currentLine.get("ecart_type")*100)/100.0)); activity.add(competenceNote); } private void addAp(JSONObject currentLine, JSONObject aps) { //Evaluation check String apCode = currentLine.get("ap").toString(); JSONObject ap = (JSONObject)aps.get(apCode); if (ap == null) { ap = new JSONObject(); ap.put("apCode", apCode); ap.put("titre", currentLine.get("ap_nom")); ap.put("credit", currentLine.get("ap_credit")); ap.put("description", currentLine.get("ap_description")); ap.put("competences", new JSONArray()); aps.put(apCode, ap); } //Activities check JSONArray competences = (JSONArray)ap.get("competences"); int compNumber = Integer.parseInt(currentLine.get("competence").toString()); boolean compExists = false; for (int i = 0; i < competences.size(); i++){ JSONObject competence = (JSONObject)competences.get(i); if(compNumber == Integer.parseInt(competence.get("competenceNumero").toString())){ compExists = true; } } if(!compExists) { JSONObject competence = new JSONObject(); competence.put("competenceNumero", compNumber); competence.put("description", ""); competences.add(competence); } } private void getNotifications (JSONArray notificationResponse, ArrayList notifications) { for (int i = 0; i < notificationResponse.size(); i++) { JSONObject currentLine = (JSONObject) notificationResponse.get(i); String notifID = currentLine.get("notification_id").toString(); //JSONObject notification = (ArrayList) notifications.get(notifID); JSONObject notification = new JSONObject(); notification.put("notificationID", currentLine.get("notification_id")); notification.put("evaluationID", currentLine.get("evaluation_id")); notification.put("evaluationNom", currentLine.get("titre")); notification.put("descriptionNotification", "Nouvelle note : " + currentLine.get("titre")); notification.put("cip", currentLine.get("cip")); notifications.add(notification); } } @GET @Path("/user") @Produces(MediaType.APPLICATION_JSON) public String getUsers(@Context HttpServletRequest req, @Context HttpServletResponse res) { try{ URL url = new URL("http://localhost:9090/membre?cip=eq." + req.getRemoteUser()); InputStream is = url.openStream(); JSONParser jsonParser = new JSONParser(); JSONArray userResponse = (JSONArray)jsonParser.parse(new InputStreamReader(is, "UTF-8")); if(userResponse.size() == 0){ return "null"; } JSONObject userLine = (JSONObject)userResponse.get(0); JSONObject returnedJSON = new JSONObject(); returnedJSON.put("cip", userLine.get("cip")); returnedJSON.put("firstName", userLine.get("prenom")); returnedJSON.put("lastName", userLine.get("nom")); returnedJSON.put("email", userLine.get("courriel")); returnedJSON.put("settings", new JSONObject());//TODO ITERATION 3 : fill json object with user settings return returnedJSON.toJSONString(); } catch (Exception e){ e.printStackTrace(); } return "null"; } private Double toTwoDecimals(Double value){ if(value == null) return -1.00; else return Math.round(value*100)/100.0; } private JSONArray object2array(JSONObject jsonObject) { JSONArray output = new JSONArray(); for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); output.add(jsonObject.get(key)); } return output; } // private void sendNotifications (JSONObject jsonObject) { // //TODO: get real address from notification team @GET @Path("/v2/notes") @Produces(MediaType.APPLICATION_JSON) public String getNotes_v2(@Context HttpServletRequest req, @Context HttpServletResponse res) { try { URL url = new URL("http://localhost:9090/v2_notes_etudiants?cip=eq." + req.getRemoteUser() + "&trimestre=eq.H17"); InputStream is = url.openStream(); JSONParser jsonParser = new JSONParser(); JSONArray noteResponse = (JSONArray)jsonParser.parse(new InputStreamReader(is, "UTF-8")); if(noteResponse.size() == 0){ return "null"; } JSONObject evaluations = new JSONObject(); JSONObject aps = new JSONObject(); for (int i = 0; i < noteResponse.size(); i++) { JSONObject currentLine = (JSONObject)noteResponse.get(i); addEvaluation_v2(currentLine, evaluations); addAp(currentLine, aps); } //evaluation : JSONObject -> JSONArray JSONArray evalArray = object2array(evaluations); // Making the response JSONObject returnedJSON = new JSONObject(); returnedJSON.put("aps", object2array(aps)); returnedJSON.put("evaluations", evalArray); return returnedJSON.toJSONString(); } catch (Exception e) { e.printStackTrace(); } return "null"; } private void addEvaluation_v2(JSONObject currentLine, JSONObject evaluations) { //Evaluation check String evalID = currentLine.get("evaluation_id").toString(); JSONObject evaluation = (JSONObject)evaluations.get(evalID); if (evaluation == null) { evaluation = new JSONObject(); evaluation.put("evaluationId", evalID); evaluation.put("nom", currentLine.get("evaluation")); evaluation.put("individuel", currentLine.get("individuel")); evaluation.put("activites", new JSONObject()); evaluations.put(evalID, evaluation); } //Activities check JSONObject activities = (JSONObject)evaluation.get("activites"); String apCode = currentLine.get("ap").toString(); JSONArray activity = (JSONArray)activities.get(apCode); if (activity == null) { activity = new JSONArray(); activities.put(apCode, activity); } JSONObject competenceNote = new JSONObject(); competenceNote.put("competenceNumero", currentLine.get("competence")); competenceNote.put("note", toTwoDecimals((Double) currentLine.get("note"))); competenceNote.put("ponderation", currentLine.get("ponderation")); activity.add(competenceNote); } @GET @Path("/v2/statistiques") @Produces(MediaType.APPLICATION_JSON) public String getStatistics(@Context HttpServletRequest req, @Context HttpServletResponse res){ try{ URL url = new URL("http://localhost:9090/v_statistiques_etudiants?cip=eq." + req.getRemoteUser()+"&trimestre=eq.H17"); InputStream is = url.openStream(); JSONParser jsonParser = new JSONParser(); JSONArray statisticsResponse = (JSONArray)jsonParser.parse(new InputStreamReader(is, "UTF-8")); if(statisticsResponse.size() == 0){ return "null"; } JSONObject returnedJSON = new JSONObject(); JSONArray stats = new JSONArray(); returnedJSON.put("statistiques", stats); for(int i = 0; i < statisticsResponse.size(); i++){ JSONObject currentLine = (JSONObject)statisticsResponse.get(i); JSONObject tmp = new JSONObject(); tmp.put("evaluationId", currentLine.get("evaluation_id")); tmp.put("apCode", currentLine.get("ap")); tmp.put("competenceNumero", currentLine.get("competence")); tmp.put("moyenne", toTwoDecimals((Double) currentLine.get("moyenne"))); tmp.put("ecartType", toTwoDecimals((Double) currentLine.get("ecart_type"))); stats.add(tmp); } return returnedJSON.toJSONString(); } catch(Exception e){ e.printStackTrace(); } return "null"; } @GET @Path("/notification/{notification_id}") @Produces(MediaType.APPLICATION_JSON) public void markNotificationAsRead(@PathParam("notification_id") Integer notification_id){ try{ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPatch httpPatch = new HttpPatch(new URI("http://localhost:9090/notification?notification_id=eq." + notification_id)); String json = "{ \"est_vu\" : true }"; StringEntity entity = new StringEntity(json); httpPatch.setEntity(entity); httpPatch.setHeader("Accept", "application/json"); httpPatch.setHeader("Content-type", "application/json"); CloseableHttpResponse response = httpClient.execute(httpPatch); System.out.println(response); System.out.println(notification_id); } catch(Exception e){ e.printStackTrace(); } } }
package trikita.anvil; import android.graphics.Typeface; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TableRow; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.util.TypedValue; import android.content.res.Resources; import android.content.res.Configuration; import android.widget.TextView; import android.text.TextWatcher; import android.text.Editable; import java.lang.ref.WeakReference; import android.widget.RelativeLayout; import android.util.Pair; /** * This is a utility class with some handy attribute generators. It servers as * a base class for the generated {@code Attrs} classes for various API levels. */ public class BaseAttrs extends Nodes { /** * <p> * Returns a compound attribute node. Helpful for common widget style * definitions, e.g: * </p> * <pre> * {@code * public AttrNode headerTextStyle() { * return attrs( * textColor(Color.BLACK), * textSize(24), * gravity(CENTER) * ); * } * ... * v(TextView.class, * headerTextStyle(), * text("Hello")); * } * </pre> * <p> * This is useful for constant nodes. For the attributes that change a lot * better use chaining view node API ({@code addAttrs}) * </p> * @param nodes list of attribute nodes * @return a compound node for the given attributes list */ public static AttrNode attrs(final AttrNode ...nodes) { return new SimpleAttrNode(new ArrayList<AttrNode>(Arrays.asList(nodes))) { public void apply(View v) { for (AttrNode n : nodes) { n.apply(v); } } }; } // Some helpers for view resources /** * Returns resources associated with the component currently being rendered * @return current component resources */ public static Resources R() { return Anvil.getCurrentRenderable().getRootView().getResources(); } /** * Returns current screen orientation * @return true if screen is in portrait orientation, false otherwise */ public static boolean isPortrait() { return R().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; } /** * Converts dip to pixels for the current screen density * @param value density-independent value * @return value in pixels for the given density-independent value */ public static float dip(float value) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, R().getDisplayMetrics()); } /** * Converts dip to pixels for the current screen settings. Useful to avoid * casts from float to int in some methods * @param value density-independent value * @return value in pixels for the given density-independent value */ public static int dip(int value) { return Math.round(dip((float) value)); } /** * Returns attribute value in pixels * @param attr attribute ID * @return attribute value in pixels */ public static int attrPx(int attr) { TypedValue tv = attr(attr); return Math.round(R().getDimension(tv.resourceId)); } /** * Returns attribute value as a TypedValue * @param attr attribute ID * @return attribute value as a TypedValue */ public static TypedValue attr(int attr) { TypedValue tv = new TypedValue(); Anvil.getCurrentRenderable().getRootView() .getContext().getTheme().resolveAttribute(attr, tv, true); return tv; } // Shortcuts for common constants // weight constants public final static int FILL = ViewGroup.LayoutParams.FILL_PARENT; public final static int MATCH = ViewGroup.LayoutParams.MATCH_PARENT; public final static int WRAP = ViewGroup.LayoutParams.WRAP_CONTENT; // gravity constants public final static int TOP = 0x30; public final static int BOTTOM = 0x50; public final static int LEFT = 0x03; public final static int RIGHT = 0x05; public final static int CENTER_VERTICAL = 0x10; public final static int GROW_VERTICAL = 0x70; public final static int CENTER_HORIZONTAL = 0x01; public final static int GROW_HORIZONTAL = 0x07; public final static int CENTER = CENTER_VERTICAL|CENTER_HORIZONTAL; public final static int GROW = GROW_VERTICAL|GROW_HORIZONTAL; public final static int CLIP_VERTICAL = 0x80; public final static int CLIP_HORIZONTAL = 0x08; public final static int START = 0x00800003; public final static int END = 0x00800005; // relative layout constants public final static int ALIGN_BASELINE = RelativeLayout.ALIGN_BASELINE; public final static int ALIGN_BOTTOM = RelativeLayout.ALIGN_BOTTOM; public final static int ALIGN_END = RelativeLayout.ALIGN_END; public final static int ALIGN_LEFT = RelativeLayout.ALIGN_LEFT; public final static int ALIGN_PARENT_BOTTOM = RelativeLayout.ALIGN_PARENT_BOTTOM; public final static int ALIGN_PARENT_END = RelativeLayout.ALIGN_PARENT_END; public final static int ALIGN_PARENT_LEFT = RelativeLayout.ALIGN_PARENT_LEFT; public final static int ALIGN_PARENT_RIGHT = RelativeLayout.ALIGN_PARENT_RIGHT; public final static int ALIGN_PARENT_START = RelativeLayout.ALIGN_PARENT_START; public final static int ALIGN_PARENT_TOP = RelativeLayout.ALIGN_PARENT_TOP; public final static int ALIGN_RIGHT = RelativeLayout.ALIGN_RIGHT; public final static int ALIGN_START = RelativeLayout.ALIGN_START; public final static int ALIGN_TOP = RelativeLayout.ALIGN_TOP; public final static int ALIGN_CENTER_HORIZONTAL = RelativeLayout.CENTER_HORIZONTAL; public final static int ALIGN_CENTER_IN_PARENT = RelativeLayout.CENTER_IN_PARENT; public final static int ALIGN_CENTER_VERTICAL = RelativeLayout.CENTER_VERTICAL; public final static int ABOVE = RelativeLayout.ABOVE; public final static int BELOW = RelativeLayout.BELOW; public final static int END_OF = RelativeLayout.END_OF; public final static int LEFT_OF = RelativeLayout.LEFT_OF; public final static int RIGHT_OF = RelativeLayout.RIGHT_OF; public final static int START_OF = RelativeLayout.START_OF; public final static int TRUE = RelativeLayout.TRUE; /** Attribute node that adjusts the LayoutParams of the view */ public static class LayoutNode implements AttrNode { int width; int height; float weight; int gravity; int column; int span; int[] margin = new int[4]; List<Pair<Integer,Integer>> rules = new ArrayList<>(); public LayoutNode() { this(Integer.MIN_VALUE, Integer.MIN_VALUE); } public LayoutNode(int width, int height) { this.width = width; this.height = height; } public LayoutNode weight(float w) { this.weight = w; return this; } public LayoutNode margin(int m) { return margin(m, m, m, m); } public LayoutNode margin(int horizontal, int vertical) { return margin(horizontal, vertical, horizontal, vertical); } public LayoutNode margin(int l, int t, int r, int b) { this.margin[0] = l; this.margin[1] = t; this.margin[2] = r; this.margin[3] = b; return this; } public LayoutNode gravity(int g) { this.gravity = g; return this; } public LayoutNode column(int column) { this.column = column; return this; } public LayoutNode span(int span) { this.span = span; return this; } public LayoutNode align(int verb) { return this.align(verb, -1); } public LayoutNode align(int verb, int anchor) { this.rules.add(new Pair<>(verb, anchor)); return this; } public void apply(View v) { ViewGroup.LayoutParams p = v.getLayoutParams(); if (width != Integer.MIN_VALUE) { p.width = width; } if (height != Integer.MIN_VALUE) { p.height = height; } if (p instanceof ViewGroup.MarginLayoutParams) { ((ViewGroup.MarginLayoutParams) p).leftMargin = this.margin[0]; ((ViewGroup.MarginLayoutParams) p).topMargin = this.margin[1]; ((ViewGroup.MarginLayoutParams) p).rightMargin = this.margin[2]; ((ViewGroup.MarginLayoutParams) p).bottomMargin = this.margin[3]; } if (p instanceof LinearLayout.LayoutParams) { ((LinearLayout.LayoutParams) p).weight = this.weight; ((LinearLayout.LayoutParams) p).gravity = this.gravity; } if (p instanceof FrameLayout.LayoutParams) { ((FrameLayout.LayoutParams) p).gravity = this.gravity; } if (p instanceof TableRow.LayoutParams) { ((TableRow.LayoutParams) p).column = this.column; ((TableRow.LayoutParams) p).span = this.span; } if (p instanceof RelativeLayout.LayoutParams) { for (Pair<Integer, Integer> rule : rules) { ((RelativeLayout.LayoutParams) p).addRule(rule.first, rule.second); } } v.setLayoutParams(p); } public int hashCode() { return this.width + this.height + Float.floatToIntBits(this.weight) + this.gravity + this.column + this.span + this.margin[0] + this.margin[1] + this.margin[2] + this.margin[3]; } public boolean equals(Object obj) { if (getClass() == obj.getClass()) { LayoutNode n = (LayoutNode) obj; return this.width == n.width && this.height == n.height && this.weight == n.weight && this.gravity == n.gravity && this.column == n.column && this.span == n.span && this.margin[0] == n.margin[0] && this.margin[1] == n.margin[1] && this.margin[2] == n.margin[2] && this.margin[3] == n.margin[3]; } return false; } } /** * Creates a new LayoutParam generator chain * @param w width * @param h height * @return layout node */ public static LayoutNode size(int w, int h) { return new LayoutNode(w, h); } /** * Creates a new LayoutParam generator chain with default width/height * @return layout node */ public static LayoutNode size() { return new LayoutNode(); } /** * A helper for padding when each side padding is the same * @param p padding * @return padding node */ public static AttrNode padding(int p) { return padding(p, p, p, p); } /** * A helper for padding when padding is the same for each dimension * @param horizontal horizontal padding * @param vertical vertical padding * @return padding node */ public static AttrNode padding(int horizontal, int vertical) { return padding(horizontal, vertical, horizontal, vertical); } /** * A generic helper for padding * @param left left padding * @param top top padding * @param right right padding * @param bottom bottom padding * @return padding node */ public static AttrNode padding(final int left, final int top, final int right, final int bottom) { final List<Integer> params = new ArrayList<Integer>() {{ add(left); add(top); add(right); add(bottom); }}; return new SimpleAttrNode(params) { public void apply(View v) { v.setPadding(params.get(0), params.get(1), params.get(2), params.get(3)); } }; } /** * A helper for settings custom font from the assets * @param font font path inside the assets directory * @return typeface attribute node */ public static AttrNode typeface(final String font) { return new SimpleAttrNode(font) { public void apply(View v) { if (v instanceof android.widget.TextView) { ((android.widget.TextView) v) .setTypeface(Typeface.createFromAsset(v.getContext().getAssets(), font)); } } }; } private static class TextWatchAttr extends SimpleAttrNode<TextWatcher> { private WeakReference<TextView> viewRef; public TextWatchAttr(TextWatcher value) { super(value); } public int hashCode() { return super.hashCode(); } public boolean equals(Object obj) { boolean res = super.equals(obj); // We know that if the view has the same class, but different value - // apply() will be called for the new value holder. // Which means it's a good place to cleanup the previous value holder if (!res && obj instanceof TextWatchAttr) { ((TextWatchAttr) obj).cleanup(); } return res; } @Override public void apply(View v) { if (v instanceof TextView) { this.viewRef = new WeakReference<>((TextView) v); ((TextView) v).addTextChangedListener(this.value); } } private void cleanup() { TextView v = this.viewRef.get(); if (v != null) { v.removeTextChangedListener(this.value); } } } /** * A helper to listen to TextView changes * @param w Text watcher * @return text watcher attribute node */ public static AttrNode onTextChanged(final TextWatcher w) { return new TextWatchAttr(w); } /** * A simplified TextWatcher interface when you only need to know the text * being entered */ public static interface SimpleTextWatcher { public void onTextChanged(String s); } /** * A helper to listen to TextView changes with simplified interface * @param w Simple text watcher with one method (handy for Java 8) * @return text watcher attribute node */ public static AttrNode onTextChanged(final SimpleTextWatcher w) { return onTextChanged(new TextWatcher() { @Override public void afterTextChanged(Editable s) { w.onTextChanged(s.toString()); } @Override public void beforeTextChanged(CharSequence s, int from, int n, int after) {} @Override public void onTextChanged(CharSequence s, int from, int before, int count) {} }); } }
package mod._sd; import com.sun.star.text.XTextRange; import java.io.PrintWriter; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.DesktopTools; import util.SOfficeFactory; import util.dbg; import util.utils; import com.sun.star.awt.XWindow; import com.sun.star.container.XIndexAccess; import com.sun.star.drawing.XDrawPage; import com.sun.star.drawing.XDrawPages; import com.sun.star.drawing.XDrawPagesSupplier; import com.sun.star.drawing.XShape; import com.sun.star.drawing.XShapes; import com.sun.star.frame.XController; import com.sun.star.frame.XDesktop; import com.sun.star.frame.XDispatch; import com.sun.star.frame.XDispatchProvider; import com.sun.star.frame.XFrame; import com.sun.star.frame.XModel; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import com.sun.star.util.URL; import com.sun.star.util.XURLTransformer; /** * Test for object which is represented by service * <code>com.sun.star.present.OutlineView</code>. <p> * Object implements the following interfaces : * <ul> * <li> <code>com::sun::star::lang::XComponent</code></li> * <li> <code>com::sun::star::lang::XServiceInfo</code></li> * <li> <code>com::sun::star::frame::XController</code></li> * <li> <code>com::sun::star::beans::XPropertySet</code></li> * <li> <code>com::sun::star::presentation::OutlineView</code></li> * <li> <code>com::sun::star::frame::XDispatchProvider</code></li> * <li> <code>com::sun::star::awt::XWindow</code></li> * </ul> * @see com.sun.star.lang.XComponent * @see com.sun.star.lang.XServiceInfo * @see com.sun.star.frame.XController * @see com.sun.star.beans.XPropertySet * @see com.sun.star.presentation.OutlineView * @see com.sun.star.awt.XWindow * @see com.sun.star.frame.XDispatchProvider * @see ifc.lang._XComponent * @see ifc.lang._XServiceInfo * @see ifc.frame._XController * @see ifc.beans._XPropertySet * @see ifc.awt._XWindow * @see ifc.presentation._OutlineView * @see ifc.frame._XDispatchProvider */ public class SdUnoOutlineView extends TestCase { XDesktop the_Desk; XComponent xImpressDoc; XComponent xSecondDrawDoc; /** * Creates the instance of the service <code>com.sun.star.frame.Desktop</code>. * @see com.sun.star.frame.Desktop */ protected void initialize(TestParameters Param, PrintWriter log) { the_Desk = (XDesktop) UnoRuntime.queryInterface( XDesktop.class, DesktopTools.createDesktop( (XMultiServiceFactory)Param.getMSF()) ); } /** * Called while disposing a <code>TestEnvironment</code>. * Disposes Impress documents. * @param tParam test parameters * @param tEnv the environment to cleanup * @param log writer to log information while testing */ protected void cleanup( TestParameters Param, PrintWriter log) { log.println("disposing impress documents"); util.DesktopTools.closeDoc(xImpressDoc);; util.DesktopTools.closeDoc(xSecondDrawDoc);; } /** * Creating a Testenvironment for the interfaces to be tested. * Creates two impress documents. After creating of the documents makes short * wait to allow frames to be loaded. Retrieves the collection of the draw pages * from the first document and takes one of them. Inserts some shapes to the * retrieved draw page. Obtains a current controller from the first document * using the interface <code>XModel</code>. The obtained controller is the * instance of the service <code>com.sun.star.presentation.OutlineView</code>. * Object relations created : * <ul> * <li> <code>'FirstModel'</code> for * {@link ifc.frame._XController}(the interface <code>XModel</code> of * the first created document) </li> * <li> <code>'Frame'</code> for * {@link ifc.frame._XController}(the frame of the created * document) </li> * <li> <code>'SecondModel'</code> for * {@link ifc.frame._XController}(the interface <code>XModel</code> of * the second created document) </li> * <li> <code>'SecondController'</code> for * {@link ifc.frame._XController}(the current controller of the second * created document) </li> * </ul> * @see com.sun.star.frame.XModel */ protected synchronized TestEnvironment createTestEnvironment (TestParameters Param, PrintWriter log) { log.println( "creating a test environment" ); // get a soffice factory object SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)Param.getMSF()); try { log.println( "creating a impress document" ); xImpressDoc = SOF.createImpressDoc(null); shortWait(); } catch (com.sun.star.uno.Exception e) { e.printStackTrace( log ); throw new StatusException("Couldn't create document", e); } XDrawPagesSupplier oDPS = (XDrawPagesSupplier) UnoRuntime.queryInterface(XDrawPagesSupplier.class, xImpressDoc); XDrawPages the_pages = oDPS.getDrawPages(); XIndexAccess oDPi = (XIndexAccess) UnoRuntime.queryInterface(XIndexAccess.class,the_pages); XModel aModel = (XModel) UnoRuntime.queryInterface(XModel.class, xImpressDoc); XInterface oObj = aModel.getCurrentController(); //Change to Outline view try { String aSlotID = "slot:27010"; XDispatchProvider xDispProv = (XDispatchProvider) UnoRuntime.queryInterface( XDispatchProvider.class, oObj ); XURLTransformer xParser = (com.sun.star.util.XURLTransformer) UnoRuntime.queryInterface(XURLTransformer.class, ((XMultiServiceFactory)Param.getMSF()).createInstance("com.sun.star.util.URLTransformer")); // Because it's an in/out parameter we must use an array of URL objects. URL[] aParseURL = new URL[1]; aParseURL[0] = new URL(); aParseURL[0].Complete = aSlotID; xParser.parseStrict(aParseURL); URL aURL = aParseURL[0]; XDispatch xDispatcher = xDispProv.queryDispatch( aURL,"",0); if( xDispatcher != null ) xDispatcher.dispatch( aURL, null ); } catch (com.sun.star.uno.Exception e) { log.println("Couldn't change mode"); } try { log.println( "creating a second impress document" ); xSecondDrawDoc = SOF.createImpressDoc(null); shortWait(); } catch (com.sun.star.uno.Exception e) { e.printStackTrace( log ); throw new StatusException("Couldn't create document", e); } XModel aModel2 = (XModel) UnoRuntime.queryInterface(XModel.class, xSecondDrawDoc); XWindow anotherWindow = (XWindow) UnoRuntime.queryInterface( XWindow.class,aModel2.getCurrentController()); oObj = aModel.getCurrentController(); log.println( "creating a new environment for impress view object" ); TestEnvironment tEnv = new TestEnvironment( oObj ); if (anotherWindow != null) { tEnv.addObjRelation("XWindow.AnotherWindow", anotherWindow); } //Adding ObjRelations for XController tEnv.addObjRelation("FirstModel", aModel); tEnv.addObjRelation("XUserInputInterception.XModel", aModel); XFrame the_frame = the_Desk.getCurrentFrame(); tEnv.addObjRelation("Frame", the_frame); aModel = (XModel) UnoRuntime.queryInterface(XModel.class, xSecondDrawDoc); //Adding ObjRelations for XController tEnv.addObjRelation("SecondModel", aModel); XController secondController = aModel.getCurrentController(); tEnv.addObjRelation("SecondController", secondController); tEnv.addObjRelation("XDispatchProvider.URL", "slot:27069"); log.println("Implementation Name: " + utils.getImplName(oObj)); return tEnv; } // finish method getTestEnvironment private void shortWait() { try { Thread.sleep(5000) ; } catch (InterruptedException e) { System.out.println("While waiting :" + e) ; } } } // finish class SdUnoOutlineView
package org.ocelotds.test; import org.ocelotds.objects.Result; import org.ocelotds.test.dataservices.EJBDataService; import org.ocelotds.test.dataservices.CDIDataService; import org.ocelotds.test.dataservices.SingletonCDIDataService; import org.ocelotds.test.dataservices.PojoDataService; import com.fasterxml.jackson.databind.ObjectMapper; import org.ocelotds.Constants; import org.ocelotds.OcelotServices; import org.ocelotds.messaging.Fault; import org.ocelotds.messaging.MessageFromClient; import org.ocelotds.messaging.MessageToClient; import org.ocelotds.messaging.MessageEvent; import org.ocelotds.messaging.MessageType; import org.ocelotds.resolvers.CdiResolver; import org.ocelotds.spi.DataServiceException; import org.ocelotds.spi.IDataServiceResolver; import org.ocelotds.resolvers.DataServiceResolverIdLitteral; import org.ocelotds.resolvers.EJBResolver; import org.ocelotds.resolvers.PojoResolver; import org.ocelotds.test.dataservices.GetValue; import org.ocelotds.test.dataservices.SessionCDIDataService; import org.ocelotds.test.dataservices.SessionEJBDataService; import org.ocelotds.test.dataservices.SingletonEJBDataService; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.enterprise.event.Event; import javax.enterprise.inject.Any; import javax.enterprise.inject.Instance; import javax.inject.Inject; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.MessageHandler; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import static org.assertj.core.api.Assertions.*; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.FileAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.jboss.weld.exceptions.UnsatisfiedResolutionException; import org.junit.AfterClass; import org.junit.Assert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.ocelotds.ArquillianTestCase; import org.ocelotds.objects.FakeCDI; import org.ocelotds.objects.JsServiceProviderImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author hhfrancois */ //@RunWith(Arquillian.class) public class OcelotTest extends ArquillianTestCase { private final static Logger logger = LoggerFactory.getLogger(OcelotTest.class); private final static long TIMEOUT = 1000; private final static String PORT = "8282"; private final static String ctxpath = "ocelot-test"; @Inject @MessageEvent Event<MessageToClient> wsEvent; @Inject @Any private Instance<IDataServiceResolver> resolvers; @Inject TestTopicAccessControler accessControl; private IDataServiceResolver getResolver(String type) { return resolvers.select(new DataServiceResolverIdLitteral(type)).get(); } private final PojoDataService destination = new PojoDataService(); @Deployment public static WebArchive createWarGlassfishArchive() { return createWarArchive(); } public static WebArchive createWarArchive() { File[] core = Maven.resolver().resolve("org.ocelotds:ocelot-core:2.4.1-SNAPSHOT").withTransitivity().asFile(); File logback = new File("src/test/resources/logback.xml"); File localeFr = new File("src/test/resources/test_fr_FR.properties"); File localeUs = new File("src/test/resources/test_en_US.properties"); WebArchive webArchive = ShrinkWrap.create(WebArchive.class, ctxpath + ".war") .addAsLibraries(core) .addAsLibraries(createOcelotWebJar()) .addPackages(true, OcelotTest.class.getPackage()) .addPackages(true, "org.ocelotds.objects") .deleteClass(JsServiceProviderImpl.class) .deleteClass(FakeCDI.class) .addAsResource(new FileAsset(logback), "logback.xml") .addAsResource(new FileAsset(localeUs), "test_en_US.properties") .addAsResource(new FileAsset(localeFr), "test_fr_FR.properties") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); addJSAndProvider("target/test-classes", webArchive, webArchive); return webArchive; } @BeforeClass public static void setUpClass() { System.out.println("==============================================================================================================="); } @AfterClass public static void tearDownClass() { System.out.println("==============================================================================================================="); } public static Session createAndGetSession() { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); try { StringBuilder sb = new StringBuilder("ws://localhost:"); sb.append(PORT).append(Constants.SLASH).append(ctxpath).append(Constants.SLASH).append("ocelot-endpoint"); URI uri = new URI(sb.toString()); return container.connectToServer(OcelotClientEnpoint.class, uri); } catch (URISyntaxException | DeploymentException | IOException ex) { fail("CONNEXION FAILED " + ex.getMessage()); } return null; } private MessageFromClient getMessageFromClient(String classname, String operation, String... params) { MessageFromClient messageFromClient = new MessageFromClient(); messageFromClient.setId(UUID.randomUUID().toString()); messageFromClient.setDataService(classname); messageFromClient.setOperation(operation); if (params != null) { messageFromClient.getParameters().addAll(Arrays.asList(params)); } return messageFromClient; } private MessageFromClient getMessageFromClient(Class cls, String operation, String paramNames, String... params) { MessageFromClient messageFromClient = getMessageFromClient(cls.getName(), operation, params); messageFromClient.setParameterNames(Arrays.asList(paramNames.split(","))); return messageFromClient; } /** * Transforme un objet en json, attention aux string * * @param obj * @return */ private String getJson(Object obj) { try { if (String.class.isInstance(obj)) { return "\"" + obj + "\""; } ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(obj); } catch (IOException ex) { return null; } } private static class CountDownMessageHandler implements MessageHandler.Whole<String> { private final CountDownLatch lock; private MessageToClient messageToClient = null; private String id = null; CountDownMessageHandler(String id, CountDownLatch lock) { this.lock = lock; this.id = id; } CountDownMessageHandler(CountDownLatch lock) { this.lock = lock; } @Override public void onMessage(String message) { logger.debug("RECEIVE RESPONSE FROM SERVER = {}", message); MessageToClient messageToClientIn = MessageToClient.createFromJson(message); if (id == null || id.equals(messageToClientIn.getId())) { messageToClient = messageToClientIn; lock.countDown(); } } public MessageToClient getMessageToClient() { return messageToClient; } } private Object getResultAfterSendInSession(Session wsSession, Class clazz, String operation, String... params) { return getMessageToClientAfterSendInSession(wsSession, clazz.getName(), operation, params).getResponse(); } private void checkMessageAfterSendInSession(Session session, String className, String operation, String... params) { // contruction de l'objet command MessageFromClient messageFromClient = getMessageFromClient(className, operation, params); // send session.getAsyncRemote().sendText(messageFromClient.toJson()); } private MessageToClient getMessageToClientAfterSendInSession(Session session, String classname, String operation, String... params) { MessageToClient result = null; try { long t0 = System.currentTimeMillis(); // construction de la commande MessageFromClient messageFromClient = getMessageFromClient(classname, operation, params); // on pose un locker CountDownLatch lock = new CountDownLatch(1); CountDownMessageHandler messageHandler = new CountDownMessageHandler(messageFromClient.getId(), lock); session.addMessageHandler(messageHandler); // send session.getAsyncRemote().sendText(messageFromClient.toJson()); // wait le delock ou timeout boolean await = lock.await(TIMEOUT, TimeUnit.MILLISECONDS); long t1 = System.currentTimeMillis(); assertTrue("Timeout. waiting " + (t1 - t0) + " ms. Remain " + lock.getCount() + "/1 msgs", await); // lecture du resultat dans le handler result = messageHandler.getMessageToClient(); assertNotNull(result); session.removeMessageHandler(messageHandler); } catch (InterruptedException ex) { fail("Bean not reached"); } return result; } private void testDifferentInstancesInDifferentThreads(final Class<? extends GetValue> clazz, String resolverId) { final IDataServiceResolver resolver = getResolver(resolverId); try { ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new CallRunnable(clazz, resolver)); executorService.shutdown(); GetValue bean2 = resolver.resolveDataService(clazz); assertNotNull(bean2); Assert.assertNotEquals("two instances of session bean should be differents", bean2.getValue(), 500); } catch (DataServiceException ex) { fail(resolverId + " bean not reached"); } } private static class CallRunnable implements Runnable { private final Class<? extends GetValue> clazz; private final IDataServiceResolver resolver; public CallRunnable(Class<? extends GetValue> clazz, IDataServiceResolver resolver) { this.clazz = clazz; this.resolver = resolver; } @Override public void run() { try { GetValue bean1 = resolver.resolveDataService(clazz); bean1.setValue(500); Thread.sleep(1000); assertNotNull(bean1); assertTrue(clazz.isInstance(bean1)); } catch (DataServiceException | InterruptedException ex) { } } } private void testInstanceRequestScope(Class clazz, String resolverId) { IDataServiceResolver resolver = getResolver(resolverId); try { Object bean1 = resolver.resolveDataService(clazz); assertNotNull(bean1); assertTrue(clazz.isInstance(bean1)); Object bean2 = resolver.resolveDataService(clazz); assertNotNull(bean2); assertFalse("two instances of request bean should be differents", bean1.equals(bean2)); } catch (DataServiceException ex) { fail(resolverId + " bean not reached"); } } public void testResultRequestScope(Class clazz) { // premiere requete Object firstResult = null; try (Session wssession = createAndGetSession()) { firstResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // deuxieme requetesur une autre session Object secondResult = null; try (Session wssession = createAndGetSession()) { secondResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // controle Assert.assertNotEquals("two instances of request bean should be differents", firstResult, secondResult); // doit etre different } private void testInstanceSingletonScope(Class clazz, String resolverId) { IDataServiceResolver resolver = getResolver(resolverId); try { Object singleton1 = resolver.resolveDataService(clazz); assertNotNull(singleton1); Object singleton2 = resolver.resolveDataService(clazz); assertNotNull(singleton2); assertEquals(singleton1, singleton2); } catch (DataServiceException ex) { fail(resolverId + " bean not reached"); } } public void testResultSingletonScope(Class clazz) { // premiere requete Object firstResult = null; try (Session wssession = createAndGetSession()) { firstResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // deuxieme requete sur autre session Object secondResult = null; try (Session wssession = createAndGetSession()) { secondResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // controle, doit etre identique assertEquals(firstResult, secondResult); } private void testInstanceSessionScope(Class clazz, String resolverId) { IDataServiceResolver resolver = getResolver(resolverId); try { Object bean1 = resolver.resolveDataService(clazz); assertNotNull(bean1); assertTrue(clazz.isInstance(bean1)); Object bean2 = resolver.resolveDataService(clazz); assertNotNull(bean2); assertFalse("two instances of session bean should be differents", bean1.equals(bean2)); } catch (DataServiceException ex) { fail(resolverId + " bean not reached"); } } private void testResultSessionScope(Class clazz) { // premiere requete Object firstResult = null; Object secondResult = null; try (Session wssession = createAndGetSession()) { firstResult = getResultAfterSendInSession(wssession, clazz, "getValue"); // deuxieme requete secondResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // controle : sur la meme session cela doit se comporter comme un singleton, donc meme resultat assertEquals(secondResult, firstResult); // troisiement appel sur une session differente Object thirdResult = null; try (Session wssession = createAndGetSession()) { thirdResult = getResultAfterSendInSession(wssession, clazz, "getValue"); } catch (IOException exception) { } // controle : sur != session cela doit etre different Assert.assertNotEquals(secondResult, thirdResult); } public HttpURLConnection getConnectionForResource(String resource, boolean min) throws MalformedURLException, IOException { StringBuilder sb = new StringBuilder("http://localhost:"); sb.append(PORT).append(Constants.SLASH).append(ctxpath).append(Constants.SLASH).append(resource); if (!min) { sb.append("?").append(Constants.MINIFY_PARAMETER).append("=false"); } URL url = new URL(sb.toString()); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); System.out.println("Content-type: " + uc.getContentType()); System.out.println("Content-encoding: " + uc.getContentEncoding()); System.out.println("Date: " + new Date(uc.getDate())); System.out.println("Last modified: " + new Date(uc.getLastModified())); System.out.println("Expiration date: " + new Date(uc.getExpiration())); System.out.println("Content-length: " + uc.getContentLength()); // connection.setRequestMethod("GET"); // connection.connect(); assertEquals("'" + sb.toString() + "' is unreachable", 200, uc.getResponseCode()); return uc; } //@Test public void testJavascriptCoreMinification() { System.out.println("testJavascriptCoreMinification"); String resource = Constants.OCELOT + Constants.JS; HttpURLConnection connection1 = null; HttpURLConnection connection2 = null; try { connection1 = getConnectionForResource(resource, true); int minlength = connection1.getInputStream().available(); // traceFile(connection1.getInputStream()); connection2 = getConnectionForResource(resource, false); int length = connection2.getInputStream().available(); // traceFile(connection2.getInputStream()); assertTrue("Minification of " + resource + " didn't work, same size of file magnifier : " + length + " / minifer : " + minlength, minlength < length); } catch (IOException e) { fail(e.getMessage()); } finally { if (connection1 != null) { connection1.disconnect(); } if (connection2 != null) { connection2.disconnect(); } } } private void traceFile(InputStream input) { try (BufferedReader in = new BufferedReader(new InputStreamReader(input, Constants.UTF_8))) { String inputLine; while ((inputLine = in.readLine()) != null) { System.out.write(inputLine.getBytes(Constants.UTF_8)); System.out.write(Constants.BACKSLASH_N.getBytes(Constants.UTF_8)); } } catch (IOException e) { } } //@Test public void testJavascriptGeneration() { System.out.println("testJavascriptCoreGeneration"); try { HttpURLConnection connection = getConnectionForResource(Constants.OCELOT + Constants.JS, false); boolean replaced; try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), Constants.UTF_8))) { String inputLine; replaced = false; while ((inputLine = in.readLine()) != null) { assertFalse("Dynamic replacement of " + Constants.CTXPATH + " doen't work", inputLine.contains(Constants.CTXPATH)); replaced |= inputLine.contains(ctxpath); } } assertTrue("Dynamic replacement of context doen't work", replaced); } catch (Exception e) { fail(e.getMessage()); } } //@Test(expected = UnsatisfiedResolutionException.class) public void testDataServiceExceptionOnUnknownResolver() { System.out.println("failResolveDataService"); getResolver("foo"); } //@Test public void testGetResolverEjb() { System.out.println("getResolverEjb"); IDataServiceResolver resolver = getResolver(Constants.Resolver.EJB); assertNotNull(resolver); assertTrue(EJBResolver.class.isInstance(resolver)); } //@Test public void testGetEjbs() { System.out.println("getEjbs"); String resolverId = Constants.Resolver.EJB; testDifferentInstancesInDifferentThreads(EJBDataService.class, resolverId); } //@Test public void testGetEJBStatefull() { System.out.println("getEJBSession"); String resolverId = Constants.Resolver.EJB; // testDifferentInstancesInDifferentThreads(SessionEJBDataService.class, resolverId); testInstanceSessionScope(SessionEJBDataService.class, Constants.Resolver.EJB); } //@Test public void testGetResultEJBSession() { System.out.println("getResultEJBSession"); testResultSessionScope(SessionEJBDataService.class); } //@Test public void testGetEJBSingleton() { System.out.println("getEJBSingleton"); testInstanceSingletonScope(SingletonEJBDataService.class, Constants.Resolver.EJB); } //@Test public void testGetResultEjbSingleton() { System.out.println("getResultEjbSingleton"); testResultSingletonScope(SingletonEJBDataService.class); } //@Test public void testGetResolverPojo() { System.out.println("getResolverPojo"); IDataServiceResolver resolver = getResolver(Constants.Resolver.POJO); assertNotNull(resolver); assertTrue(PojoResolver.class.isInstance(resolver)); } //@Test public void testGetPojo() { System.out.println("getPojo"); IDataServiceResolver resolver = getResolver(Constants.Resolver.POJO); try { PojoDataService resolveDataService = resolver.resolveDataService(PojoDataService.class); assertNotNull(resolveDataService); assertEquals(PojoDataService.class, resolveDataService.getClass()); } catch (DataServiceException ex) { fail("Pojo not reached"); } } //@Test public void testGetResolverCdi() { System.out.println("getResolverCdi"); IDataServiceResolver resolver = getResolver(Constants.Resolver.CDI); assertNotNull(resolver); assertTrue(CdiResolver.class.isInstance(resolver)); } //@Test public void testGetCdiBeans() { System.out.println("getCdiBeans"); testInstanceRequestScope(CDIDataService.class, Constants.Resolver.CDI); } //@Test public void testGetResultCdiBeans() { System.out.println("getResultCdiBeans"); testResultRequestScope(CDIDataService.class); } //@Test public void testGetCdiBeanIsManaged() { System.out.println("getCdiBeanIsManaged"); IDataServiceResolver resolver = getResolver(Constants.Resolver.CDI); try { CDIDataService cdids = resolver.resolveDataService(CDIDataService.class); assertNotNull(cdids); assertEquals(CDIDataService.class, cdids.getClass()); assertNotNull(cdids.getBeanManager()); } catch (DataServiceException ex) { fail("Cdi bean not reached"); } } //@Test public void testGetCdiBeanSession() { System.out.println("getCdiBeanSession"); testInstanceSessionScope(SessionCDIDataService.class, Constants.Resolver.CDI); } //@Test public void testGetResultCdiBeanSession() { System.out.println("getResultCdiBeanSession"); testResultSessionScope(SessionCDIDataService.class); } //@Test public void testGetCdiBeanSingleton() { System.out.println("getCdiBeanSingleton"); testInstanceSingletonScope(SingletonCDIDataService.class, Constants.Resolver.CDI); } //@Test public void testGetResultCdiBeanSingleton() { System.out.println("getResultCdiBeanSingleton"); testResultSingletonScope(SingletonCDIDataService.class); } //@Test public void testResolvePojoDataService() { System.out.println("resolveDataService"); try { IDataServiceResolver resolver = getResolver(Constants.Resolver.POJO); Object dest = resolver.resolveDataService(PojoDataService.class); assertNotNull(dest); assertEquals(PojoDataService.class, dest.getClass()); } catch (DataServiceException ex) { fail(ex.getMessage()); } } //@Test public void testMessageIntResultToClientCreator() { System.out.println("MessageToClient.createFromJson"); String uuid = UUID.randomUUID().toString(); Object expectedResult = 1; String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":%s,\"%s\":%s}", Constants.Message.TYPE, MessageType.RESULT, Constants.Message.ID, uuid, Constants.Message.DEADLINE, 5, Constants.Message.RESPONSE, expectedResult); MessageToClient result = MessageToClient.createFromJson(json); assertEquals(MessageType.RESULT, result.getType()); assertEquals(uuid, result.getId()); assertEquals(5, result.getDeadline()); assertEquals(MessageType.RESULT, result.getType()); assertEquals("" + expectedResult, result.getResponse()); } //@Test public void testMessageToTopicCreator() { System.out.println("MessageToTopic.createFromJson"); String uuid = UUID.randomUUID().toString(); Object expectedResult = 1; String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":%s,\"%s\":%s}", Constants.Message.TYPE, MessageType.MESSAGE, Constants.Message.ID, uuid, Constants.Message.DEADLINE, 5, Constants.Message.RESPONSE, expectedResult); MessageToClient result = MessageToClient.createFromJson(json); assertEquals(MessageType.MESSAGE, result.getType()); assertEquals(uuid, result.getId()); assertEquals(5, result.getDeadline()); assertEquals("" + expectedResult, result.getResponse()); } //@Test public void testMessageStringResultToClientCreator() { System.out.println("MessageToClient.createFromJson"); String uuid = UUID.randomUUID().toString(); String expectedResultJS = "\"foo\""; String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":%s,\"%s\":%s}", Constants.Message.TYPE, MessageType.RESULT, Constants.Message.ID, uuid, Constants.Message.DEADLINE, 10, Constants.Message.RESPONSE, expectedResultJS); MessageToClient result = MessageToClient.createFromJson(json); assertEquals(MessageType.RESULT, result.getType()); assertEquals(uuid, result.getId()); assertEquals(10, result.getDeadline()); assertEquals(MessageType.RESULT, result.getType()); assertEquals(expectedResultJS, result.getResponse()); } //@Test public void testMessageObjectResultToClientCreator() { System.out.println("MessageToClient.createFromJson"); String uuid = UUID.randomUUID().toString(); Object expectedResult = "{\"integer\":5,\"foo\":\"foo\"}"; String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":%s,\"%s\":%s}", Constants.Message.TYPE, MessageType.RESULT, Constants.Message.ID, uuid, Constants.Message.DEADLINE, 20, Constants.Message.RESPONSE, expectedResult); MessageToClient result = MessageToClient.createFromJson(json); assertEquals(MessageType.RESULT, result.getType()); assertEquals(uuid, result.getId()); assertEquals(20, result.getDeadline()); assertEquals(MessageType.RESULT, result.getType()); assertEquals(expectedResult, result.getResponse()); } //@Test public void testMessageFaultToClientCreator() { System.out.println("MessageToClient.createFromJson"); String uuid = UUID.randomUUID().toString(); Fault f = new Fault(new NullPointerException("Message d'erreur"), 0); String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":%s,\"%s\":%s}", Constants.Message.TYPE, MessageType.FAULT, Constants.Message.ID, uuid, Constants.Message.DEADLINE, 0, Constants.Message.RESPONSE, f.toJson()); MessageToClient result = MessageToClient.createFromJson(json); assertEquals(MessageType.FAULT, result.getType()); assertEquals(uuid, result.getId()); assertEquals(0, result.getDeadline()); assertEquals(MessageType.FAULT, result.getType()); assertEquals(f.getClassname(), ((Fault) result.getResponse()).getClassname()); } //@Test public void testMessageFromClientCreator() { System.out.println("MessageFromClient.createFromJson"); String uuid = UUID.randomUUID().toString(); String resultJS = getJson(new Result(6)); String mapResultJS = getJson(destination.getMapResult()); String operation = "methodWithResult"; String json = String.format("{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":[\"%s\",\"%s\"],\"%s\":[%s,%s]}", Constants.Message.ID, uuid, Constants.Message.DATASERVICE, PojoDataService.class.getName(), Constants.Message.OPERATION, operation, Constants.Message.ARGUMENTNAMES, "r", "m", Constants.Message.ARGUMENTS, resultJS, mapResultJS); MessageFromClient result = MessageFromClient.createFromJson(json); assertEquals(uuid, result.getId()); assertEquals(PojoDataService.class.getName(), result.getDataService()); assertEquals(operation, result.getOperation()); List<String> parameters = result.getParameters(); assertEquals(resultJS, parameters.get(0)); assertEquals(mapResultJS, parameters.get(1)); } //@Test public void testLocale() { Class clazz = OcelotServices.class; try (Session wssession = createAndGetSession()) { // Par default la locale est US String methodName = "getLocale"; System.out.println(methodName); MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); Object result = messageToClient.getResponse(); assertThat(result).isEqualTo("{\"country\":\"US\",\"language\":\"en\"}"); methodName = "getLocaleHello"; System.out.println(methodName); messageToClient = getMessageToClientAfterSendInSession(wssession, EJBDataService.class.getName(), methodName, getJson("hhfrancois")); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); result = messageToClient.getResponse(); assertThat(result).isEqualTo("\"Hello hhfrancois\""); // On change pour le francais methodName = "setLocale"; System.out.println(methodName); messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, "{\"country\":\"FR\",\"language\":\"fr\"}"); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); methodName = "getLocale"; System.out.println(methodName); messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); result = messageToClient.getResponse(); assertThat(result).isEqualTo("{\"country\":\"FR\",\"language\":\"fr\"}"); methodName = "getLocaleHello"; System.out.println(methodName); messageToClient = getMessageToClientAfterSendInSession(wssession, EJBDataService.class.getName(), methodName, getJson("hhfrancois")); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); result = messageToClient.getResponse(); assertThat(result).isEqualTo("\"Bonjour hhfrancois\""); } catch (IOException exception) { } try (Session wssession = createAndGetSession()) { String methodName = "getLocale"; System.out.println(methodName); MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertThat(messageToClient.getType()).isEqualTo(MessageType.RESULT); Object result = messageToClient.getResponse(); assertThat(result).isEqualTo("{\"country\":\"US\",\"language\":\"en\"}"); } catch (IOException exception) { } } //@Test public void testMethodUnknow() { Class clazz = PojoDataService.class; String methodName = "getUnknownMethod"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.FAULT, messageToClient.getType()); Object fault = messageToClient.getResponse(); assertNotNull(fault); } catch (IOException exception) { } } //@Test public void testMethodNoResult() { Class clazz = PojoDataService.class; String methodName = "getVoid"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); assertEquals("null", messageToClient.getResponse()); } catch (IOException exception) { } } //@Test public void testGetString() { Class clazz = PojoDataService.class; String methodName = "getString"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getString()), result); } catch (IOException exception) { } } //@Test public void testGetNum() { Class clazz = PojoDataService.class; String methodName = "getNum"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getNum()), result); } catch (IOException exception) { } } //@Test public void testGetNumber() { Class clazz = PojoDataService.class; String methodName = "getNumber"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getNumber()), result); } catch (IOException exception) { } } //@Test public void testGetBool() { Class clazz = PojoDataService.class; String methodName = "getBool"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getBool()), result); } catch (IOException exception) { } } //@Test public void testGetBoolean() { Class clazz = PojoDataService.class; String methodName = "getBoolean"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getBoolean()), result); } catch (IOException exception) { } } //@Test public void testGetDate() { System.out.println("getDate"); final Date before = new Date(); System.out.println("BEFORE = " + before.getTime()); try (Session wssession = createAndGetSession()) { Thread.sleep(1000); MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, PojoDataService.class.getName(), "getDate"); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertNotNull(result); Date res = new Date(Long.parseLong(result.toString())); System.out.println("RES = " + res.getTime()); assertTrue(before.before(res)); Thread.sleep(1000); Date after = new Date(); System.out.println("AFTER = " + after.getTime()); assertTrue(after.after(res)); } catch (IOException exception) { } catch (InterruptedException ex) { fail(ex.getMessage()); } } //@Test public void testGetResult() { Class clazz = PojoDataService.class; String methodName = "getResult"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getResult()), result); } catch (IOException exception) { } } //@Test public void testGetCollectionInteger() { Class clazz = PojoDataService.class; String methodName = "getCollectionInteger"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getCollectionInteger()), result); } catch (IOException exception) { } } //@Test public void testGetCollectionResult() { Class clazz = PojoDataService.class; String methodName = "getCollectionResult"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getCollectionResult()), result); } catch (IOException exception) { } } //@Test public void testGetCollectionOfCollectionResult() { Class clazz = PojoDataService.class; String methodName = "getCollectionOfCollectionResult"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getCollectionOfCollectionResult()), result); } catch (IOException exception) { } } //@Test public void testGetMapResult() { Class clazz = PojoDataService.class; String methodName = "getMapResult"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.getMapResult()), result); } catch (IOException exception) { } } //@Test public void testMethodWithNum() { Class clazz = PojoDataService.class; String methodName = "methodWithNum"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(1)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithNum(1)), result); } catch (IOException exception) { } } //@Test public void testMethodWithNumber() { Class clazz = PojoDataService.class; String methodName = "methodWithNumber"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(2)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithNumber(2)), result); } catch (IOException exception) { } } //@Test public void testMethodWithBool() { Class clazz = PojoDataService.class; String methodName = "methodWithBool"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(true)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithBool(true)), result); } catch (IOException exception) { } } //@Test public void testMethodWithBoolean() { Class clazz = PojoDataService.class; String methodName = "methodWithBoolean"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(false)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithBoolean(false)), result); } catch (IOException exception) { } } //@Test public void testMethodWithDate() { Class clazz = PojoDataService.class; String methodName = "methodWithDate"; System.out.println(methodName); Object arg = new Date(); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithDate((Date) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithResult() { Class clazz = PojoDataService.class; String methodName = "methodWithResult"; System.out.println(methodName); Object arg = new Result(6); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithResult((Result) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithArrayInteger() { Class clazz = PojoDataService.class; String methodName = "methodWithArrayInteger"; System.out.println(methodName); Object arg = new Integer[]{1, 2}; try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithArrayInteger((Integer[]) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithCollectionInteger() { Class clazz = PojoDataService.class; String methodName = "methodWithCollectionInteger"; System.out.println(methodName); Object arg = destination.getCollectionInteger(); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithCollectionInteger((Collection<Integer>) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithArrayResult() { Class clazz = PojoDataService.class; String methodName = "methodWithArrayResult"; System.out.println(methodName); Object arg = new Result[]{new Result(1), new Result(2)}; try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithArrayResult((Result[]) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithCollectionResult() { Class clazz = PojoDataService.class; String methodName = "methodWithCollectionResult"; System.out.println(methodName); Object arg = destination.getCollectionResult(); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithCollectionResult((Collection<Result>) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithMapResult() { Class clazz = PojoDataService.class; String methodName = "methodWithMapResult"; System.out.println(methodName); Object arg = destination.getMapResult(); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithMapResult((Map<String, Result>) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithCollectionOfCollectionResult() { Class clazz = PojoDataService.class; String methodName = "methodWithCollectionOfCollectionResult"; System.out.println(methodName); Object arg = destination.getCollectionOfCollectionResult(); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(arg)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithCollectionOfCollectionResult((Collection<Collection<Result>>) arg)), result); } catch (IOException exception) { } } //@Test public void testMethodWithManyParameters() { Class clazz = PojoDataService.class; String methodName = "methodWithManyParameters"; System.out.println(methodName); Collection<String> cl = new ArrayList<>(); cl.add("foo"); cl.add("foo"); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson("foo"), getJson(5), getJson(new Result(3)), getJson(cl)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithManyParameters("foo", 5, new Result(3), cl)), result); } catch (IOException exception) { } } //@Test public void testMethodThatThrowException() { Class clazz = PojoDataService.class; String methodName = "methodThatThrowException"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName); assertEquals(MessageType.FAULT, messageToClient.getType()); Fault fault = (Fault) messageToClient.getResponse(); assertEquals(MethodException.class.getName(), fault.getClassname()); } catch (IOException exception) { } } //@Test public void testMethodWithAlmostSameSignature1() { Class clazz = PojoDataService.class; String methodName = "methodWithAlmostSameSignature"; System.out.println(methodName + "(int)"); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(5)); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithAlmostSameSignature(5)), result); } catch (IOException exception) { } } //@Test public void testMethodWithAlmostSameSignature2() { Class clazz = PojoDataService.class; String methodName = "methodWithAlmostSameSignature"; System.out.println(methodName + "(string)"); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson("foo")); assertEquals(MessageType.RESULT, messageToClient.getType()); Object result = messageToClient.getResponse(); assertEquals(getJson(destination.methodWithAlmostSameSignature("foo")), result); } catch (IOException exception) { } } final int NB_SIMUL_METHODS = 500; //@Test public void testCallMultiMethodsMultiSessions() { int nb = NB_SIMUL_METHODS; System.out.println("call" + nb + "MethodsMultiSession"); ExecutorService executorService = Executors.newFixedThreadPool(nb); final List<Session> sessions = new ArrayList<>(); try { final Class clazz = EJBDataService.class; final String methodName = "getValue"; long t0 = System.currentTimeMillis(); final CountDownLatch lock = new CountDownLatch(nb); for (int i = 0; i < nb; i++) { Session session = OcelotTest.createAndGetSession(); sessions.add(session); session.addMessageHandler(new CountDownMessageHandler(lock)); executorService.execute(new TestThread(clazz, methodName, session)); } boolean await = lock.await(30L * nb, TimeUnit.MILLISECONDS); long t1 = System.currentTimeMillis(); assertTrue("Timeout. waiting " + (t1 - t0) + " ms. Remain " + lock.getCount() + "/" + nb + " msgs", await); } catch (InterruptedException ex) { fail(ex.getMessage()); } finally { for (Session session : sessions) { try { session.close(); } catch (IOException ex) { } } executorService.shutdown(); } } //@Test public void testCallMultiMethodsMonoSessions() { int nb = NB_SIMUL_METHODS; System.out.println("call" + nb + "MethodsMonoSession"); ExecutorService executorService = Executors.newFixedThreadPool(nb); try (Session session = OcelotTest.createAndGetSession()) { final CountDownLatch lock = new CountDownLatch(nb); CountDownMessageHandler messageHandler = new CountDownMessageHandler(lock); session.addMessageHandler(messageHandler); final Class clazz = EJBDataService.class; final String methodName = "getValue"; long t0 = System.currentTimeMillis(); for (int i = 0; i < nb; i++) { executorService.execute(new TestThread(clazz, methodName, session)); } boolean await = lock.await(10L * nb, TimeUnit.MILLISECONDS); long t1 = System.currentTimeMillis(); assertTrue("Timeout. waiting " + (t1 - t0) + " ms. Remain " + lock.getCount() + " msgs", await); } catch (IOException | InterruptedException ex) { fail(ex.getMessage()); } finally { executorService.shutdown(); } } private class TestThread implements Runnable { private final Class clazz; private final String methodName; private final Session wsSession; public TestThread(Class clazz, String methodName, Session wsSession) { this.clazz = clazz; this.methodName = methodName; this.wsSession = wsSession; } @Override public void run() { checkMessageAfterSendInSession(wsSession, clazz.getName(), methodName); } } /** * Test d'envoi d'un message generant un message de suppression de cache */ //@Test public void testSendRemoveCacheMessage() { System.out.println("sendRemoveCacheMessage"); final String topic = "ocelot-cleancache"; System.out.println("Enregistrement au Topic '" + topic + "'"); Class clazz = OcelotServices.class; String methodName = "subscribe"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(topic)); assertEquals(MessageType.RESULT, messageToClient.getType()); long t0 = System.currentTimeMillis(); MessageFromClient messageFromClient = getMessageFromClient(EJBDataService.class, "generateCleanCacheMessage", "\"a\",\"r\"", getJson(""), getJson(new Result(5))); CountDownLatch lock = new CountDownLatch(2); CountDownMessageHandler messageHandler = new CountDownMessageHandler(lock); wssession.addMessageHandler(messageHandler); // send wssession.getAsyncRemote().sendText(messageFromClient.toJson()); // wait le delock ou timeout boolean await = lock.await(TIMEOUT, TimeUnit.MILLISECONDS); long t1 = System.currentTimeMillis(); assertTrue("Timeout. waiting " + (t1 - t0) + " ms. Remain " + lock.getCount() + "/2 msgs", await); wssession.removeMessageHandler(messageHandler); } catch (InterruptedException | IOException ex) { fail(ex.getMessage()); } } //@Test public void testSendMessageToTopic() { System.out.println("sendMessageToTopic"); final String topic = "mytopic"; System.out.println("Enregistrement au Topic '" + topic + "'"); Class clazz = OcelotServices.class; String methodName = "subscribe"; System.out.println(methodName); try (Session wssession = createAndGetSession()) { MessageToClient messageToClient = getMessageToClientAfterSendInSession(wssession, clazz.getName(), methodName, getJson(topic)); assertEquals(MessageType.RESULT, messageToClient.getType()); long t0 = System.currentTimeMillis(); // Thread.sleep(TIMEOUT); int nbMsg = 10; CountDownLatch lock = new CountDownLatch(nbMsg); CountDownMessageHandler messageHandler = new CountDownMessageHandler(topic, lock); wssession.addMessageHandler(messageHandler); MessageToClient toTopic = new MessageToClient(); toTopic.setId(topic); for (int i = 0; i < nbMsg; i++) { System.out.println("Envois d'un message au Topic '" + topic + "'"); toTopic.setResponse(new Result(i)); wsEvent.fire(toTopic); } boolean await = lock.await(TIMEOUT, TimeUnit.MILLISECONDS); long t1 = System.currentTimeMillis(); assertTrue("Timeout. waiting " + (t1 - t0) + " ms. Remain " + lock.getCount() + "/" + nbMsg + " msgs", await); wssession.removeMessageHandler(messageHandler); } catch (InterruptedException | IOException ex) { fail(ex.getMessage()); } } }
package graph; public class ConresRelation { public ConresActivity parent; public ConresActivity child; public Type type; public ConresRelation(ConresActivity parent, ConresActivity child, Type type) { this.child = child; this.parent = parent; this.type = type; } public String toString(){ return " "; } }
package in.sontx.tut.chatsocket.client; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import com.sun.istack.internal.NotNull; import in.sontx.tut.chatsocket.bean.Account; import in.sontx.tut.chatsocket.bean.ChatRequest; import in.sontx.tut.chatsocket.bean.ChatResult; import in.sontx.tut.chatsocket.bo.ITransmission; import in.sontx.tut.chatsocket.bo.ObjectAdapter; import in.sontx.tut.chatsocket.bo.Protocol; import in.sontx.tut.chatsocket.bo.SocketTransmission; import in.sontx.tut.chatsocket.utils.Log; import in.sontx.tut.chatsocket.utils.StreamUtilities; import in.sontx.tut.chatsocket.utils.Task; public final class Client { private static Client instance = null; private ITransmission transmission; private ObjectAdapter objectAdapter; private Protocol protocol; private Account myAccount = new Account(); private List<OnDataReceivedListener> mOnDataReceivedListeners = new ArrayList<>(); private OnConnectionHasProblemListener mOnConnectionHasProblemListener = null; private boolean pendingStop = false; public void addOnDataReceivedListener(OnDataReceivedListener listener) { mOnDataReceivedListeners.add(listener); } public void removeOnDataReceivedListener(OnDataReceivedListener listener) { mOnDataReceivedListeners.remove(listener); } public void setOnConnectionHasProblemListener(OnConnectionHasProblemListener listener) { mOnConnectionHasProblemListener = listener; } public static Client getInstance() { return instance; } public static void createInstance(String serverAddress, int serverPort) throws UnknownHostException, IOException { destroyInstance(); instance = new Client(serverAddress, serverPort); } public static void destroyInstance() { if (instance != null) { instance.release(); instance = null; } } private void release() { pendingStop = true; StreamUtilities.tryCloseStream(transmission); } public String getRemoteAddress() { if (transmission instanceof SocketTransmission) return ((SocketTransmission) transmission).getSocket().getRemoteSocketAddress().toString(); return "somewhere"; } public void startLooper() { Task.run(new Runnable() { @Override public void run() { boolean isCorruptData = false; do { try { //Log.i("Wait for receiving data..."); Object receivedObject = protocol.receiveObject(); //Log.i("Received data!"); if (receivedObject instanceof ChatResult) { for (int i = 0; i < mOnDataReceivedListeners.size(); i++) { OnDataReceivedListener listener = mOnDataReceivedListeners.get(i); if (!listener.onDataReceived(Client.this, (ChatResult) receivedObject)) { isCorruptData = true; break; } } } else { isCorruptData = true; Log.i("Received data is NULL or corrupted"); } } catch (IOException e) { if (!pendingStop && mOnConnectionHasProblemListener != null) mOnConnectionHasProblemListener.onConnectionHasProblem(e.getMessage()); } } while (!isCorruptData && !pendingStop); if (isCorruptData) fireConnectionHasProblemEvent("Received data has been corrupted!"); } }); } private void fireConnectionHasProblemEvent(String message) { if (mOnConnectionHasProblemListener != null) mOnConnectionHasProblemListener.onConnectionHasProblem(message); } public void request(ChatRequest request) { try { protocol.sendObject(request); } catch (IOException e) { fireConnectionHasProblemEvent(e.getMessage()); } } Client(String serverAddress, int serverPort) throws UnknownHostException, IOException { Socket socket = new Socket(serverAddress, serverPort); transmission = new SocketTransmission(socket); objectAdapter = new ObjectAdapter(); protocol = new Protocol(objectAdapter, transmission); } public int getMyId() { return myAccount.getId(); } public void setMyId(int id) { myAccount.setId(id); } public String getMyUsername() { return myAccount.getUsername(); } public void setMyUsername(String myUsername) { myAccount.setUsername(myUsername); } public interface OnDataReceivedListener { boolean onDataReceived(Client sender, @NotNull ChatResult receivedObject); } public interface OnConnectionHasProblemListener { void onConnectionHasProblem(String message); } }
package io.quarkus.container.image.jib.deployment; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import io.quarkus.runtime.annotations.ConfigItem; import io.quarkus.runtime.annotations.ConfigPhase; import io.quarkus.runtime.annotations.ConfigRoot; @ConfigRoot(phase = ConfigPhase.BUILD_TIME) public class JibConfig { public static final String DEFAULT_WORKING_DIR = "/home/jboss"; /** * The base image to be used when a container image is being produced for the jar build. * * When the application is built against Java 17 or higher, {@code registry.access.redhat.com/ubi8/openjdk-17-runtime:1.11} * is used as the default. * Otherwise {@code registry.access.redhat.com/ubi8/openjdk-11-runtime:1.11} is used as the default. */ @ConfigItem public Optional<String> baseJvmImage; /** * The base image to be used when a container image is being produced for the native binary build. * The default is "quay.io/quarkus/quarkus-micro-image". You can also use * "registry.access.redhat.com/ubi8/ubi-minimal" which is a bigger base image, but provide more built-in utilities * such as the microdnf package manager. */ @ConfigItem(defaultValue = "quay.io/quarkus/quarkus-micro-image:1.0") public String baseNativeImage; /** * The JVM arguments to pass to the JVM when starting the application */ @ConfigItem(defaultValue = "-Djava.util.logging.manager=org.jboss.logmanager.LogManager") public List<String> jvmArguments; /** * Additional JVM arguments to pass to the JVM when starting the application */ @ConfigItem public Optional<List<String>> jvmAdditionalArguments; /** * Additional arguments to pass when starting the native application */ @ConfigItem public Optional<List<String>> nativeArguments; @ConfigItem public Optional<List<String>> jvmEntrypoint; @ConfigItem public Optional<List<String>> nativeEntrypoint; /** * Environment variables to add to the container image */ @ConfigItem public Map<String, String> environmentVariables; /** * Custom labels to add to the generated image * * @deprecated Use 'quarkus.container-image.labels' instead */ @ConfigItem @Deprecated public Map<String, String> labels; /** * The username to use to authenticate with the registry used to pull the base JVM image */ @ConfigItem public Optional<String> baseRegistryUsername; /** * The password to use to authenticate with the registry used to pull the base JVM image */ @ConfigItem public Optional<String> baseRegistryPassword; /** * The ports to expose */ @ConfigItem(defaultValue = "${quarkus.http.port:8080}") public List<Integer> ports; /** * The user to use in generated image */ @ConfigItem public Optional<String> user; /** * The working directory to use in the generated image. * The default value is chosen to work in accordance with the default base image. */ @ConfigItem(defaultValue = DEFAULT_WORKING_DIR) public String workingDirectory; /** * Controls the optimization which skips downloading base image layers that exist in a target * registry. If the user does not set this property, then read as false. * * If {@code true}, base image layers are always pulled and cached. If * {@code false}, base image layers will not be pulled/cached if they already exist on the * target registry. */ @ConfigItem(defaultValue = "false") public boolean alwaysCacheBaseImage; @ConfigItem public Optional<Set<String>> platforms; /** * The path of a file in which the digest of the generated image will be written. * If the path is relative, the base path is the output directory of the build tool. */ @ConfigItem(defaultValue = "jib-image.digest") public String imageDigestFile; /** * The path of a file in which the id of the generated image will be written. * If the path is relative, the base path is the output directory of the build tool. */ @ConfigItem(defaultValue = "jib-image.id") public String imageIdFile; /** * Whether or not to operate offline. */ @ConfigItem(defaultValue = "false") public boolean offlineMode; /** * Name of binary used to execute the docker commands. This is only used by Jib * when the container image is being built locally. */ @ConfigItem public Optional<String> dockerExecutableName; /** * Sets environment variables used by the Docker executable. This is only used by Jib * when the container image is being built locally. */ @ConfigItem public Map<String, String> dockerEnvironment; @ConfigItem(defaultValue = "true") public boolean useCurrentTimestamp; /** * Whether to set the modification time (last modified time) of the files put by Jib in the image to the actual * build time. Otherwise, the modification time will be set to the Unix epoch (00:00:00, January 1st, 1970 in UTC). * * If the modification time is constant (flag is set to false so Unix epoch is used) across two consecutive builds, * the docker layer sha256 digest will be different only if the actual files added by Jib to the docker layer were * changed. More exactly, having 2 consecutive builds will generate different docker layers only if the actual * content of the files within the docker layer was changed. * * If the current timestamp is used the sha256 digest of the docker layer will always be different even if the * content of the files didn't change. */ @ConfigItem(defaultValue = "true") public boolean useCurrentTimestampFileModification; }
package com.ibm.bi.dml.lops.compile; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.Vector; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.SequenceFileInputFormat; import com.ibm.bi.dml.api.DMLScript; import com.ibm.bi.dml.lops.CombineBinary; import com.ibm.bi.dml.lops.Data; import com.ibm.bi.dml.lops.Lops; import com.ibm.bi.dml.lops.OutputParameters; import com.ibm.bi.dml.lops.ParameterizedBuiltin; import com.ibm.bi.dml.lops.PartitionLop; import com.ibm.bi.dml.lops.PickByCount; import com.ibm.bi.dml.lops.Unary; import com.ibm.bi.dml.lops.Data.OperationTypes; import com.ibm.bi.dml.lops.LopProperties.ExecLocation; import com.ibm.bi.dml.lops.LopProperties.ExecType; import com.ibm.bi.dml.lops.Lops.Type; import com.ibm.bi.dml.lops.OutputParameters.Format; import com.ibm.bi.dml.meta.PartitionParams; import com.ibm.bi.dml.parser.Expression; import com.ibm.bi.dml.parser.Expression.DataType; import com.ibm.bi.dml.parser.Expression.ValueType; import com.ibm.bi.dml.runtime.controlprogram.parfor.ProgramConverter; import com.ibm.bi.dml.runtime.instructions.CPInstructionParser; import com.ibm.bi.dml.runtime.instructions.Instruction; import com.ibm.bi.dml.runtime.instructions.MRJobInstruction; import com.ibm.bi.dml.runtime.matrix.io.InputInfo; import com.ibm.bi.dml.runtime.matrix.io.OutputInfo; import com.ibm.bi.dml.runtime.matrix.sort.PickFromCompactInputFormat; import com.ibm.bi.dml.utils.DMLRuntimeException; import com.ibm.bi.dml.utils.DMLUnsupportedOperationException; import com.ibm.bi.dml.utils.LopsException; import com.ibm.bi.dml.utils.configuration.DMLConfig; /** * * @author aghoting Class to maintain a DAG and compile it into jobs * @param <N> */ @SuppressWarnings("deprecation") public class Dag<N extends Lops> { static int total_reducers; static String scratch = ""; boolean DEBUG = DMLScript.DEBUG; // hash set for all nodes in dag ArrayList<N> nodes; static int job_id = 0; static int var_index = 0; static final int CHILD_BREAKS_ALIGNMENT = 2; static final int CHILD_DOES_NOT_BREAK_ALIGNMENT = 1; static final int MRCHILD_NOT_FOUND = 0; static final int MR_CHILD_FOUND_BREAKS_ALIGNMENT = 4; static final int MR_CHILD_FOUND_DOES_NOT_BREAK_ALIGNMENT = 5; private class NodeOutput { String fileName; String varName; OutputInfo outInfo; ArrayList<Instruction> preInstructions; ArrayList<Instruction> lastInstructions; NodeOutput() { fileName = null; varName = null; outInfo = null; preInstructions = new ArrayList<Instruction>(); lastInstructions = new ArrayList<Instruction>(); } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getVarName() { return varName; } public void setVarName(String varName) { this.varName = varName; } public OutputInfo getOutInfo() { return outInfo; } public void setOutInfo(OutputInfo outInfo) { this.outInfo = outInfo; } public ArrayList<Instruction> getPreInstructions() { return preInstructions; } public void addPreInstruction(Instruction inst) { preInstructions.add(inst); } public ArrayList<Instruction> getLastInstructions() { return lastInstructions; } public void addLastInstruction(Instruction inst) { lastInstructions.add(inst); } } /** * Constructor */ public Dag() { /** * allocate structures */ nodes = new ArrayList<N>(); /** get number of reducers from job config */ JobConf jConf = new JobConf(); total_reducers = jConf.getInt("mapred.reduce.tasks", DMLConfig.DEFAULT_NUM_REDUCERS); } /** * Method to compile a dag generically * * @param config * @throws LopsException * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException */ public ArrayList<Instruction> getJobs(boolean debug, DMLConfig config) throws LopsException, DMLRuntimeException, DMLUnsupportedOperationException { if (config != null) { if (config.getTextValue("numreducers") != null) total_reducers = Integer.parseInt(config .getTextValue("numreducers")); if (config.getTextValue("scratch") != null) scratch = config.getTextValue("scratch") + "/"; } DEBUG = debug; // hold all nodes in a vector (needed for ordering) Vector<N> node_v = new Vector<N>(); node_v.addAll(nodes); /* * Sort the nodes by topological order. * * 1) All nodes with level i appear prior to the nodes in level i+1. * 2) All nodes within a level are ordered by their ID i.e., in the order * they are created */ doTopologicalSort_strict_order(node_v); // do greedy grouping of operations ArrayList<Instruction> inst = doGreedyGrouping(node_v); return inst; } /** * Method to remove transient reads that do not have a transient write * * @param nodeV * @param inst * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException */ private void deleteUnwantedTransientReadVariables(Vector<N> nodeV, ArrayList<Instruction> inst) throws DMLRuntimeException, DMLUnsupportedOperationException { HashMap<String, N> labelNodeMapping = new HashMap<String, N>(); if(DEBUG) System.out.println("In delete unwanted variables"); // first capture all transient read variables for (int i = 0; i < nodeV.size(); i++) { N node = nodeV.get(i); if (node.getExecLocation() == ExecLocation.Data && ((Data) node).isTransient() && ((Data) node).getOperationType() == OperationTypes.READ) { labelNodeMapping.put(node.getOutputParameters().getLabel(), node); } } // generate delete instructions for all transient read variables without // a transient write // first capture all transient write variables for (int i = 0; i < nodeV.size(); i++) { N node = nodeV.get(i); if (node.getExecLocation() == ExecLocation.Data && ((Data) node).isTransient() && ((Data) node).getOperationType() == OperationTypes.WRITE && labelNodeMapping.containsKey(node.getOutputParameters() .getLabel())) { labelNodeMapping.remove(node.getOutputParameters().getLabel()); } } // generate RM instructions Iterator<String> it = labelNodeMapping.keySet().iterator(); while (it.hasNext()) { String label = it.next(); N node = labelNodeMapping.get(label); if (((Data) node).get_dataType() == DataType.SCALAR) { // if(DEBUG) // System.out.println("rmvar" + Lops.OPERAND_DELIMITOR + label); // inst.add(new VariableSimpleInstructions("rmvar" + // Lops.OPERAND_DELIMITOR + label)); } else { if (DEBUG) System.out.println("CP" + Lops.OPERAND_DELIMITOR + "rmfilevar" + Lops.OPERAND_DELIMITOR + label + Lops.VALUETYPE_PREFIX + Expression.ValueType.UNKNOWN + Lops.OPERAND_DELIMITOR + "true" + Lops.VALUETYPE_PREFIX + Expression.ValueType.BOOLEAN); inst.add(CPInstructionParser .parseSingleInstruction("CP" + Lops.OPERAND_DELIMITOR + "rmfilevar" + Lops.OPERAND_DELIMITOR + label + Lops.VALUETYPE_PREFIX + Expression.ValueType.UNKNOWN + Lops.OPERAND_DELIMITOR + "true" + Lops.VALUETYPE_PREFIX + Expression.ValueType.BOOLEAN)); } } } /** * Method to add a node to the DAG. * * @param node * @return true if node was not already present, false if not. */ public boolean addNode(N node) { if (nodes.contains(node)) return false; else { nodes.add(node); return true; } } private ArrayList<Vector<N>> createNodeVectors(int size) { ArrayList<Vector<N>> arr = new ArrayList<Vector<N>>(); // for each job type, we need to create a vector. // additionally, create another vector for execNodes for (int i = 0; i < size; i++) { arr.add(new Vector<N>()); } return arr; } private void clearNodeVectors(ArrayList<Vector<N>> arr) { for (int i = 0; i < arr.size(); i++) { arr.get(i).clear(); } } private boolean isCompatible(Vector<N> nodes, JobType jt, int from, int to) throws LopsException { int base = jt.getBase(); for (int i = from; i < to; i++) { if ((nodes.get(i).getCompatibleJobs() & base) == 0) { if (DEBUG) System.out.println("Not compatible " + nodes.get(i).toString()); return false; } } return true; } private boolean isCompatible(N node, JobType jt) { return ((node.getCompatibleJobs() & jt.getBase()) > 0); } /* * Add node, and its relevant children to job-specific node vectors. */ private void addNodeByJobType(N node, ArrayList<Vector<N>> arr, Vector<N> execNodes, boolean eliminate) throws LopsException { if (eliminate == false) { // Check if this lop defines a MR job. if ( node.definesMRJob() ) { // find the corresponding JobType JobType jt = JobType.findJobTypeFromLopType(node.getType()); if ( jt == null ) { // In case of Reblock, jobType depends not only on LopType but also on the format if ( node.getType() == Lops.Type.ReBlock ) { // must differentiate between reblock lops that operate on text // and binary input if (getChildFormat(node) == Format.BINARY) { jt = JobType.REBLOCK_BINARY; } else { jt = JobType.REBLOCK_TEXT; } } else { throw new LopsException("No matching JobType is found for a the lop type: " + node.getType()); } } // Add "node" to corresponding job vector if ( jt == JobType.GMR ) { // if "node" (in this case, a group lop) has any inputs from RAND // then add it to RAND job. Otherwise, create a GMR job if (hasChildNode(node, arr.get(JobType.RAND.getId()) )) { arr.get(JobType.RAND.getId()).add(node); // we should NOT call 'addChildren' because appropriate // child nodes would have got added to RAND job already } else { int gmr_index = JobType.GMR.getId(); arr.get(gmr_index).add(node); int from = arr.get(gmr_index).size(); addChildren(node, arr.get(gmr_index), execNodes); int to = arr.get(gmr_index).size(); if (!isCompatible(arr.get(gmr_index),JobType.GMR, from, to)) { throw new LopsException("Error during compatibility check"); } } } else { int index = jt.getId(); arr.get(index).add(node); int from = arr.get(index).size(); addChildren(node, arr.get(index), execNodes); int to = arr.get(index).size(); // check if all added nodes are compatible with current job if (!isCompatible(arr.get(index), jt, from, to)) { throw new LopsException( "Unexpected error in addNodeByType."); } } return; } } /* * If this lop does not define a job, check if it uses the output of any * specialized job. i.e., if this lop has a child node in any of the * job-specific vector, then add it to the vector. Note: This lop must * be added to ONLY ONE of the job-specific vectors. */ int numAdded = 0; for ( JobType j : JobType.values() ) { if ( j.getId() > 0 && hasChildNode(node, arr.get(j.getId()))) { if (eliminate || isCompatible(node, j)) { arr.get(j.getId()).add(node); numAdded += 1; } } } if (numAdded > 1) { throw new LopsException("Unexpected error in addNodeByJobType(): A given lop can ONLY be added to a single job vector (numAdded = " + numAdded + ")." ); } } /* * Remove the node from all job-specific node vectors. This method is * invoked from removeNodesForNextIteration(). */ private void removeNodeByJobType(N node, ArrayList<Vector<N>> arr) { for ( JobType jt : JobType.values()) if ( jt.getId() > 0 ) arr.get(jt.getId()).remove(node); } /** * As some jobs only write one output, all operations in the mapper need to * be redone and cannot be marked as finished. * * @param execNodes * @param jobNodes * @throws LopsException */ private void handleSingleOutputJobs(Vector<N> execNodes, ArrayList<Vector<N>> jobNodes, Vector<N> finishedNodes) throws LopsException { /* * If the input of a MMCJ/MMRJ job (must have executed in a Mapper) is used * by multiple lops then we should mark it as not-finished. */ Vector<N> nodesWithUnfinishedOutputs = new Vector<N>(); int[] jobIndices = {JobType.MMCJ.getId(), JobType.MMRJ.getId()}; Lops.Type[] lopTypes = { Lops.Type.MMCJ, Lops.Type.MMRJ }; // TODO: SortByValue should be treated similar to MMCJ, since it can // only sort one file now for ( int jobi=0; jobi < jobIndices.length; jobi++ ) { int jindex = jobIndices[jobi]; if (jobNodes.get(jindex).size() > 0) { Vector<N> vec = jobNodes.get(jindex); // first find all nodes with more than one parent that is not // finished. for (int i = 0; i < vec.size(); i++) { N node = vec.get(i); if (node.getExecLocation() == ExecLocation.MapOrReduce || node.getExecLocation() == ExecLocation.Map) { N MRparent = getParentNode(node, execNodes, ExecLocation.MapAndReduce); if ( MRparent != null && MRparent.getType() == lopTypes[jobi]) { int numParents = node.getOutputs().size(); if (numParents > 1) { for (int j = 0; j < numParents; j++) { if (!finishedNodes.contains(node.getOutputs() .get(j))) nodesWithUnfinishedOutputs.add(node); } } } } /* // Following condition will not work for MMRJ because execNodes may contain non-MapAndReduce // lops that are compatible with MMRJ (e.g., Data-WRITE) else if (!(node.getExecLocation() == ExecLocation.MapAndReduce && node.getType() == lopTypes[jobi])) { throw new LopsException( "Error in handleSingleOutputJobs(): encountered incompatible execLocation='" + node.getExecLocation() + "' for lop (ID=" + node.getID() + ")."); } */ } // need to redo all nodes in nodesWithOutput as well as their // children for (int i = 0; i < vec.size(); i++) { N node = vec.get(i); if (node.getExecLocation() == ExecLocation.MapOrReduce || node.getExecLocation() == ExecLocation.Map) { if (nodesWithUnfinishedOutputs.contains(node)) finishedNodes.remove(node); if (hasParentNode(node, nodesWithUnfinishedOutputs)) finishedNodes.remove(node); } } } } } /** Method to check if a lop can be eliminated from checking **/ private boolean canEliminateLop(N node, Vector<N> execNodes) { // this function can only eliminate "aligner" lops such a group if (!node.isAligner()) return false; // find the child whose execLoc = 'MapAndReduce' int ret = getChildAlignment(node, execNodes, ExecLocation.MapAndReduce); if (ret == CHILD_BREAKS_ALIGNMENT) return false; else if (ret == CHILD_DOES_NOT_BREAK_ALIGNMENT) return true; else if (ret == MRCHILD_NOT_FOUND) return false; else if (ret == MR_CHILD_FOUND_BREAKS_ALIGNMENT) return false; else if (ret == MR_CHILD_FOUND_DOES_NOT_BREAK_ALIGNMENT) return true; else throw new RuntimeException("Should not happen."); } /** * Method to generate instructions that create variables. * i.e., each instructions creates a new entry in the symbol table. * Every "data" input node in a LOPs DAG is translated into an instruction. * * @param nodes * @throws LopsException */ private void generateInstructionsForInputVariables(Vector<N> nodes_v, ArrayList<Instruction> inst) throws LopsException { for(N n : nodes_v) { /* * ONLY persistent reads must be considered. For transient reads, previous program block * would have already created appropriate entires in the symbol table. * Therefore, no explicit createvar instruction is required. */ if (n.getExecLocation() == ExecLocation.Data && !((Data) n).isTransient() && ((Data) n).getOperationType() == OperationTypes.READ && n.get_dataType() == DataType.MATRIX) { if ( !((Data)n).isLiteral() ) { try { String inst_string = n.getInstructions(); inst.add(CPInstructionParser.parseSingleInstruction(inst_string)); } catch (DMLUnsupportedOperationException e) { throw new LopsException(e); } catch (DMLRuntimeException e) { throw new LopsException(e); } } } } } private boolean sendWriteLopToMR(N node) { if( node.getInputs().get(0).getExecType() == ExecType.MR || (node.getInputs().get(0).getExecLocation() == ExecLocation.Data && node.getInputs().get(0).get_dataType() == DataType.MATRIX) ) return true; else return false; } /** * Method to group a vector of sorted lops. * * @param node_v * @throws LopsException * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException */ private ArrayList<Instruction> doGreedyGrouping(Vector<N> node_v) throws LopsException, DMLRuntimeException, DMLUnsupportedOperationException { if (DEBUG) System.out.println("Grouping DAG ============"); // nodes to be executed in current iteration Vector<N> execNodes = new Vector<N>(); // nodes that have already been processed Vector<N> finishedNodes = new Vector<N>(); // nodes that are queued for the following iteration Vector<N> queuedNodes = new Vector<N>(); ArrayList<Vector<N>> jobNodes = createNodeVectors(JobType.getNumJobTypes()); // list of instructions ArrayList<Instruction> inst = new ArrayList<Instruction>(); ArrayList<Instruction> preWriteDeleteInst = new ArrayList<Instruction>(); ArrayList<Instruction> deleteInst = new ArrayList<Instruction>(); ArrayList<Instruction> writeInst = new ArrayList<Instruction>(); // delete transient variables that are no longer needed deleteUnwantedTransientReadVariables(node_v, deleteInst); // remove files for transient reads that are updated. deleteUpdatedTransientReadVariables(node_v, preWriteDeleteInst); generateInstructionsForInputVariables(node_v, inst); boolean done = false; String indent = " "; while (!done) { if (DEBUG) System.out.println("Grouping nodes in DAG"); execNodes.clear(); queuedNodes.clear(); clearNodeVectors(jobNodes); for (int i = 0; i < node_v.size(); i++) { N node = node_v.elementAt(i); // finished nodes don't need to be processed if (finishedNodes.contains(node)) continue; if (DEBUG) System.out.println("Processing node (" + node.getID() + ") " + node.toString() + " exec nodes size is " + execNodes.size()); //if node defines MR job, make sure it is compatible with all //its children nodes in execNodes if(node.definesMRJob() && !compatibleWithChildrenInExecNodes(execNodes, node)) { if (DEBUG) System.out.println(indent + "Queueing node " + node.toString() + " (code 1)"); queuedNodes.add(node); continue; //no other nodes need to be dropped. //hence we do not need to invoke removeNodesForNextIteration } // if child is queued, this node will be processed in the later // iteration if (hasChildNode(node, queuedNodes)) { if (DEBUG) System.out.println(indent + "Queueing node " + node.toString() + " (code 2)"); queuedNodes.add(node); // if node has more than two inputs, // remove children that will be needed in a future // iterations // may also have to remove parent nodes of these children removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); continue; } // if inputs come from different jobs, then queue if (node.getInputs().size() == 2) { int j1 = jobType(node.getInputs().get(0), jobNodes); int j2 = jobType(node.getInputs().get(1), jobNodes); if (j1 != -1 && j2 != -1 && j1 != j2) { if (DEBUG) System.out.println(indent + "Queueing node " + node.toString() + " (code 3)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); continue; } } // See if this lop can be eliminated // This check is for "aligner" lops (e.g., group) boolean eliminate = false; eliminate = canEliminateLop(node, execNodes); if (eliminate) { if (DEBUG) System.out.println(indent + "Adding -" + node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, eliminate); continue; } // If the node defines a MR Job then make sure none of its // children that defines a MR Job are present in execNodes if (node.definesMRJob()) { if (hasMRJobChildNode(node, execNodes)) { // "node" must NOT be queued when node=group and the child that defines job is Rand // this is because "group" can be pushed into the "Rand" job. if (! (node.getType() == Lops.Type.Grouping && getMRJobChildNode(node,execNodes).getType() == Lops.Type.RandLop) ) { if (DEBUG) System.out.println(indent + "Queueing node " + node.toString() + " (code 4)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); continue; } } } // if "node" has more than one input, and has a descendant lop // in execNodes that is of type RecordReader // then all its inputs must be ancestors of RecordReader. If // not, queue "node" if (node.getInputs().size() > 1 && hasChildNode(node, execNodes, ExecLocation.RecordReader)) { // get the actual RecordReader lop N rr_node = getChildNode(node, execNodes, ExecLocation.RecordReader); // all inputs of "node" must be ancestors of rr_node boolean queue_it = false; for (int in = 0; in < node.getInputs().size(); in++) { // each input should be ancestor of RecordReader lop N n = (N) node.getInputs().get(in); if (!n.equals(rr_node) && !isChild(rr_node, n)) { queue_it = true; // i.e., "node" must be queued break; } } if (queue_it) { // queue node if (DEBUG) System.out.println(indent + "Queueing -" + node.toString() + " (code 5)"); queuedNodes.add(node); // TODO: does this have to be modified to handle // recordreader lops? removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); continue; } else { // nothing here.. subsequent checks have to be performed // on "node" ; } } // data node, always add if child not queued // only write nodes are kept in execnodes if (node.getExecLocation() == ExecLocation.Data) { if (DEBUG) System.out.println(indent + "Adding Data -" + node.toString()); finishedNodes.add(node); Data.OperationTypes op = ((Data) node).getOperationType(); if ( op == OperationTypes.READ ) { // TODO: avoid readScalar instruction, and read it on-demand just like the way Matrices are read in control program if ( node.get_dataType() == DataType.SCALAR && node.getOutputParameters().getFile_name() != null ) { // this lop corresponds to reading a scalar from HDFS file // add it to execNodes so that "readScalar" instruction gets generated execNodes.add(node); // note: no need to add it to any job vector } } else if (op == OperationTypes.WRITE) { execNodes.add(node); /* WRITE lop must go into a mapreduce job if * a) its input executes in MR; or * b) its input is a Matrix Data READ * */ if ( sendWriteLopToMR(node) ) { addNodeByJobType(node, jobNodes, execNodes, false); } } continue; } // map or reduce node, can always be piggybacked with parent if (node.getExecLocation() == ExecLocation.MapOrReduce) { if (DEBUG) System.out.println(indent + "Adding -" + node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, false); continue; } // RecordReader node, add, if no parent needs reduce, else queue if (node.getExecLocation() == ExecLocation.RecordReader) { // "node" should not have any children in // execNodes .. it has to be the first one in the job! if (!hasChildNode(node, execNodes, ExecLocation.Map) && !hasChildNode(node, execNodes, ExecLocation.MapAndReduce)) { if (DEBUG) System.out.println(indent + "Adding -" + node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, false); } else { if (DEBUG) System.out.println(indent + "Queueing -" + node.toString() + " (code 6)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); } continue; } // map node, add, if no parent needs reduce, else queue if (node.getExecLocation() == ExecLocation.Map) { if (!hasChildNode(node, execNodes, ExecLocation.MapAndReduce)) { if (DEBUG) System.out.println(indent + "Adding -" + node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, false); } else { if (DEBUG) System.out.println(indent + "Queueing -" + node.toString() + " (code 7)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); } continue; } // reduce node, make sure no parent needs reduce, else queue if (node.getExecLocation() == ExecLocation.MapAndReduce) { // boolean eliminate = false; // eliminate = canEliminateLop(node, execNodes); // if (eliminate || (!hasChildNode(node, execNodes, // ExecLocation.MapAndReduce)) && // !hasMRJobChildNode(node,execNodes)) { // TODO: statiko -- keep the middle condition // discuss about having a lop that is MapAndReduce but does // not define a job if (DEBUG) System.out.println(indent + "Adding -" + node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, eliminate); // } else { // if (DEBUG) // System.out.println("Queueing -" + node.toString()); // queuedNodes.add(node); // removeNodesForNextIteration(node, finishedNodes, // execNodes, queuedNodes, jobNodes); continue; } // aligned reduce, make sure a parent that is reduce exists if (node.getExecLocation() == ExecLocation.Reduce) { if (hasChildNode(node, execNodes, ExecLocation.MapAndReduce)) { if (DEBUG) System.out.println(indent + "Adding -" + node.toString()); execNodes.add(node); finishedNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, false); } else { if (DEBUG) System.out.println(indent + "Queueing -" + node.toString() + " (code 8)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); } continue; } // add Scalar to execNodes if it has no child in exec nodes // that will be executed in a MR job. if (node.getExecLocation() == ExecLocation.ControlProgram) { for (int j = 0; j < node.getInputs().size(); j++) { if (execNodes.contains(node.getInputs().get(j)) && !(node.getInputs().get(j).getExecLocation() == ExecLocation.Data) && !(node.getInputs().get(j).getExecLocation() == ExecLocation.ControlProgram)) { if (DEBUG) System.out.println(indent + "Queueing -" + node.toString() + " (code 9)"); queuedNodes.add(node); removeNodesForNextIteration(node, finishedNodes, execNodes, queuedNodes, jobNodes); break; } } if (queuedNodes.contains(node)) continue; if (DEBUG) System.out.println(indent + "Adding - scalar" + node.toString()); execNodes.add(node); addNodeByJobType(node, jobNodes, execNodes, false); finishedNodes.add(node); continue; } } // no work to do if (execNodes.size() == 0) { if(queuedNodes.size() != 0) { if(DEBUG) { //System.err.println("Queued nodes should be 0"); throw new LopsException("Queued nodes should not be 0 at this point"); } } if (DEBUG) System.out.println("All done! queuedNodes = " + queuedNodes.size()); done = true; } else { // work to do if (DEBUG) System.out .println("Generating jobs for group -- Node count=" + execNodes.size()); // first process scalar instructions generateControlProgramJobs(execNodes, inst, writeInst, deleteInst); // next generate MR instructions if (execNodes.size() > 0) generateMRJobs(execNodes, inst, writeInst, deleteInst, jobNodes); handleSingleOutputJobs(execNodes, jobNodes, finishedNodes); } } // add write and delete inst at the very end. inst.addAll(preWriteDeleteInst); inst.addAll(writeInst); inst.addAll(deleteInst); return inst; } private boolean compatibleWithChildrenInExecNodes(Vector<N> execNodes, N node) { for(int i=0; i < execNodes.size(); i++) { N tmpNode = execNodes.elementAt(i); // for lops that execute in control program, compatibleJobs property is set to LopProperties.INVALID // we should not consider such lops in this check if (isChild(tmpNode, node) && tmpNode.getExecLocation() != ExecLocation.ControlProgram //&& tmpNode.getCompatibleJobs() != LopProperties.INVALID && (tmpNode.getCompatibleJobs() & node.getCompatibleJobs()) == 0) return false; } return true; } private void deleteUpdatedTransientReadVariables(Vector<N> nodeV, ArrayList<Instruction> inst) throws DMLRuntimeException, DMLUnsupportedOperationException { HashMap<String, N> labelNodeMapping = new HashMap<String, N>(); HashSet<String> updatedLabels = new HashSet<String>(); if(DEBUG) System.out.println("In delete updated variables"); // first capture all transient read variables for (int i = 0; i < nodeV.size(); i++) { N node = nodeV.get(i); if (node.getExecLocation() == ExecLocation.Data && ((Data) node).isTransient() && ((Data) node).getOperationType() == OperationTypes.READ && ((Data) node).get_dataType() == DataType.MATRIX) { labelNodeMapping.put(node.getOutputParameters().getLabel(), node); } } // capture updated transient write variables for (int i = 0; i < nodeV.size(); i++) { N node = nodeV.get(i); if (node.getExecLocation() == ExecLocation.Data && ((Data) node).isTransient() && ((Data) node).getOperationType() == OperationTypes.WRITE && ((Data) node).get_dataType() == DataType.MATRIX && labelNodeMapping.containsKey(node.getOutputParameters() .getLabel()) && !labelNodeMapping.containsValue(node.getInputs().get(0))) { updatedLabels.add(node.getOutputParameters().getLabel()); } } // generate RM instructions Iterator<String> it = updatedLabels.iterator(); while (it.hasNext()) { String label = it.next(); if (DEBUG) System.out.println("CP" + Lops.OPERAND_DELIMITOR + "rmfilevar" + Lops.OPERAND_DELIMITOR + label + Lops.VALUETYPE_PREFIX + Expression.ValueType.UNKNOWN + Lops.OPERAND_DELIMITOR + "true" + Lops.VALUETYPE_PREFIX + Expression.ValueType.BOOLEAN); inst.add(CPInstructionParser.parseSingleInstruction("CP" + Lops.OPERAND_DELIMITOR + "rmfilevar" + Lops.OPERAND_DELIMITOR + label + Lops.VALUETYPE_PREFIX + Expression.ValueType.UNKNOWN + Lops.OPERAND_DELIMITOR + "true" + Lops.VALUETYPE_PREFIX + Expression.ValueType.BOOLEAN)); } } String prepareVariableInstruction(String opcode, String varName, DataType dt, ValueType vt, String fileName, OutputParameters oparams, OutputInfo oinfo) { StringBuilder inst = new StringBuilder(); inst.append("CP" + Lops.OPERAND_DELIMITOR + opcode); if ( opcode == "createvar" ) { inst.append(Lops.OPERAND_DELIMITOR + varName + Lops.DATATYPE_PREFIX + dt + Lops.VALUETYPE_PREFIX + vt); inst.append(Lops.OPERAND_DELIMITOR + fileName + Lops.DATATYPE_PREFIX + DataType.SCALAR + Lops.VALUETYPE_PREFIX + ValueType.STRING); inst.append(Lops.OPERAND_DELIMITOR + oparams.getNum_rows()); inst.append(Lops.OPERAND_DELIMITOR + oparams.getNum_cols()); inst.append(Lops.OPERAND_DELIMITOR + oparams.getNum_rows_per_block()); inst.append(Lops.OPERAND_DELIMITOR + oparams.getNum_cols_per_block()); inst.append(Lops.OPERAND_DELIMITOR + "0"); // TODO: should pass on correct NNZs inst.append(Lops.OPERAND_DELIMITOR + OutputInfo.outputInfoToString(oinfo) ) ; } return inst.toString(); } String prepareVariableInstruction(String opcode, N node) { OutputParameters oparams = node.getOutputParameters(); return prepareVariableInstruction(opcode, oparams.getLabel(), node.get_dataType(), node.get_valueType(), oparams.getFile_name(), oparams, getOutputInfo(node)); } /** * Method to generate instructions that are executed in Control Program. At * this point, this DAG has no dependencies on the MR dag. ie. none of the * inputs are outputs of MR jobs * * @param execNodes * @param inst * @param writeInst * @param deleteInst * @throws LopsException * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ @SuppressWarnings("unchecked") private void generateControlProgramJobs(Vector<N> execNodes, ArrayList<Instruction> inst, ArrayList<Instruction> writeInst, ArrayList<Instruction> deleteInst) throws LopsException, DMLUnsupportedOperationException, DMLRuntimeException { // nodes to be deleted from execnodes Vector<N> markedNodes = new Vector<N>(); // variable names to be deleted Vector<String> var_deletions = new Vector<String>(); for (int i = 0; i < execNodes.size(); i++) { N node = execNodes.get(i); // mark input scalar read nodes for deletion // TODO: statiko -- check if this condition ever evaluated to TRUE if (node.getExecLocation() == ExecLocation.Data && ((Data) node).getOperationType() == Data.OperationTypes.READ && ((Data) node).get_dataType() == DataType.SCALAR && node.getOutputParameters().getFile_name() == null ) { markedNodes.add(node); continue; } // output scalar instructions and mark nodes for deletion if (node.getExecLocation() == ExecLocation.ControlProgram) { if (node.get_dataType() == DataType.SCALAR) { // Output from lops with SCALAR data type must // go into Temporary Variables (Var0, Var1, etc.) NodeOutput out = setupNodeOutputs(node, ExecType.CP); inst.addAll(out.getPreInstructions()); // dummy deleteInst.addAll(out.getLastInstructions()); } else { // Output from lops with non-SCALAR data type must // go into Temporary Files (temp0, temp1, etc.) NodeOutput out = setupNodeOutputs(node, ExecType.CP); inst.addAll(out.getPreInstructions()); boolean hasTransientWriteParent = false; for ( int pid=0; pid < node.getOutputs().size(); pid++ ) { N parent = (N)node.getOutputs().get(pid); if ( parent.getExecLocation() == ExecLocation.Data && ((Data)parent).getOperationType() == Data.OperationTypes.WRITE && ((Data)parent).isTransient() ) { hasTransientWriteParent = true; break; } } if ( !hasTransientWriteParent ) deleteInst.addAll(out.getLastInstructions()); } String inst_string = ""; // Since ParameterizedBuiltins have arbitrary number of inputs, we handle it separately if (node.getType() == Lops.Type.ParameterizedBuiltin){ // TODO NEW: check why SCALAR and MATRIX have to be differentiated if ( node.get_dataType() == DataType.SCALAR ) { inst_string = ((ParameterizedBuiltin) node).getInstructions(node.getOutputParameters().getLabel()); } else { inst_string = ((ParameterizedBuiltin) node).getInstructions(node.getOutputParameters().getFile_name()); } } else { if ( node.getInputs().size() == 0 ) { // currently, such a case exists only for Rand lop inst_string = node.getInstructions(node.getOutputParameters().getLabel()); } else if (node.getInputs().size() == 1) { inst_string = node.getInstructions(node.getInputs() .get(0).getOutputParameters().getLabel(), node.getOutputParameters().getLabel()); } else if (node.getInputs().size() == 2) { inst_string = node.getInstructions( node.getInputs().get(0).getOutputParameters().getLabel(), node.getInputs().get(1).getOutputParameters().getLabel(), node.getOutputParameters().getLabel()); } else if (node.getInputs().size() == 3) { inst_string = node.getInstructions( node.getInputs().get(0).getOutputParameters().getLabel(), node.getInputs().get(1).getOutputParameters().getLabel(), node.getInputs().get(2).getOutputParameters().getLabel(), node.getOutputParameters().getLabel()); } else if (node.getInputs().size() == 5) { inst_string = node.getInstructions( node.getInputs().get(0).getOutputParameters().getLabel(), node.getInputs().get(1).getOutputParameters().getLabel(), node.getInputs().get(2).getOutputParameters().getLabel(), node.getInputs().get(3).getOutputParameters().getLabel(), node.getInputs().get(4).getOutputParameters().getLabel(), node.getOutputParameters().getLabel()); } else { throw new LopsException("Node with " + node.getInputs().size() + " inputs is not supported in CP yet!"); } } try { if (DEBUG) System.out.println("Generating simple instruction - " + inst_string); inst.add(CPInstructionParser .parseSingleInstruction(inst_string)); } catch (Exception e) { e.printStackTrace(); throw new LopsException("Problem generating simple inst - " + inst_string); } markedNodes.add(node); continue; } else if (node.getExecLocation() == ExecLocation.Data ) { Data dnode = (Data)node; Data.OperationTypes op = dnode.getOperationType(); if ( op == Data.OperationTypes.WRITE ) { NodeOutput out = null; if ( sendWriteLopToMR(node) ) { // In this case, Data WRITE lop goes into MR, and // we don't have to do anything here } else { out = setupNodeOutputs(node, ExecType.CP); if ( dnode.get_dataType() == DataType.SCALAR ) { // processing is same for both transient and persistent scalar writes writeInst.addAll(out.getLastInstructions()); } else { // setupNodeOutputs() handles both transient and persistent matrix writes if ( dnode.isTransient() ) { //inst.addAll(out.getPreInstructions()); // dummy ? deleteInst.addAll(out.getLastInstructions()); } else { // In case of persistent write lop, write() instruction will be generated // and that instruction must be added to <code>inst</code> so that it gets // executed immediately. If it is added to <code>deleteInst</code> then it // gets executed at the end of program block's execution inst.addAll(out.getLastInstructions()); } } markedNodes.add(node); continue; } } else { // generate a temp label to hold the value that is read from HDFS if ( node.get_dataType() == DataType.SCALAR ) { node.getOutputParameters().setLabel("Var" + var_index++); String io_inst = node.getInstructions(node.getOutputParameters().getLabel(), node.getOutputParameters().getFile_name()); inst.add(CPInstructionParser.parseSingleInstruction(io_inst)); deleteInst.add(CPInstructionParser.parseSingleInstruction( "CP" + Lops.OPERAND_DELIMITOR + "rmvar" + Lops.OPERAND_DELIMITOR + node.getLevel())); } else { throw new LopsException("Matrix READs are not handled in CP yet!"); } markedNodes.add(node); continue; } } } // delete all marked nodes for (int i = 0; i < markedNodes.size(); i++) { execNodes.remove(markedNodes.elementAt(i)); } } /** * Method to remove all child nodes of a queued node that should be executed * in a following iteration. * * @param node * @param finishedNodes * @param execNodes * @param queuedNodes * @throws LopsException */ private void removeNodesForNextIteration(N node, Vector<N> finishedNodes, Vector<N> execNodes, Vector<N> queuedNodes, ArrayList<Vector<N>> jobvec) throws LopsException { // only queued nodes with two inputs need to be handled. // TODO: statiko -- this should be made == 1 if (node.getInputs().size() != 2) return; //if both children are queued, nothing to do. if (queuedNodes.contains(node.getInputs().get(0)) && queuedNodes.contains(node.getInputs().get(1))) return; if(DEBUG) System.out.println("Before remove nodes for next iteration -- size of execNodes " + execNodes.size()); boolean inputs_in_same_job = false; // TODO: handle tertiary if (jobType(node.getInputs().get(0), jobvec) != -1 && jobType(node.getInputs().get(0), jobvec) == jobType(node .getInputs().get(1), jobvec)) { inputs_in_same_job = true; } boolean unassigned_inputs = false; // here.. scalars shd be ignored if ((node.getInputs().get(0).getExecLocation() != ExecLocation.ControlProgram && jobType( node.getInputs().get(0), jobvec) == -1) || (node.getInputs().get(1).getExecLocation() != ExecLocation.ControlProgram && jobType( node.getInputs().get(1), jobvec) == -1)) { unassigned_inputs = true; } boolean child_queued = false; // check if atleast one child was queued. if (queuedNodes.contains(node.getInputs().get(0)) || queuedNodes.contains(node.getInputs().get(1))) child_queued = true; // nodes to be dropped Vector<N> markedNodes = new Vector<N>(); for (int i = 0; i < execNodes.size(); i++) { N tmpNode = execNodes.elementAt(i); if (DEBUG) { System.out.println("Checking for removal (" + tmpNode.getID() + ") " + tmpNode.toString()); System.out.println("Inputs in same job " + inputs_in_same_job); System.out.println("Unassigned inputs " + unassigned_inputs); System.out.println("Child queued " + child_queued); } //if(node.definesMRJob() && isChild(tmpNode,node) && (tmpNode.getCompatibleJobs() & node.getCompatibleJobs()) == 0) // continue; // TODO: statiko -- check if this is too conservative? if (child_queued) { // if one of the children are queued, // remove some child nodes on other leg that may be needed later on. // For e.g. Group lop. if((tmpNode == node.getInputs().get(0) || tmpNode == node.getInputs().get(1)) && tmpNode.isAligner()) { markedNodes.add(tmpNode); if (DEBUG) System.out.println("Removing for next iteration: (" + tmpNode.getID() + ") " + tmpNode.toString()); } else if (!hasOtherQueuedParentNode(tmpNode, queuedNodes, node) && isChild(tmpNode, node) && branchHasNoOtherUnExecutedParents(tmpNode, node, execNodes, finishedNodes)) if( //e.g. MMCJ (node.getExecLocation() == ExecLocation.MapAndReduce && branchCanBePiggyBackedMapAndReduce(tmpNode, node, execNodes, finishedNodes) && !tmpNode.definesMRJob() ) || //e.g. Binary (node.getExecLocation() == ExecLocation.Reduce && branchCanBePiggyBackedReduce(tmpNode, node, execNodes, finishedNodes)) ) { if (DEBUG) System.out.println("Removing for next iteration: (" + tmpNode.getID() + ") " + tmpNode.toString()); markedNodes.add(tmpNode); } } else { /* * "node" has no other queued children. * * If inputs are in the same job and "node" is of type * MapAndReduce, then remove nodes of all types other than * Reduce, MapAndReduce, and the ones that define a MR job as * they can be piggybacked later. * * e.g: A=Rand, B=Rand, C=A%*%B Here, both inputs of MMCJ lop * come from Rand job, and they should not be removed. * * Other examples: -- MMCJ whose children are of type * MapAndReduce (say GMR) -- Inputs coming from two different * jobs .. GMR & REBLOCK */ if ((inputs_in_same_job || unassigned_inputs) && node.getExecLocation() == ExecLocation.MapAndReduce && !hasOtherMapAndReduceParentNode(tmpNode, execNodes, node) && isChild(tmpNode, node) && branchCanBePiggyBackedMapAndReduce(tmpNode, node, execNodes, finishedNodes) && tmpNode.definesMRJob() != true) { if (DEBUG) System.out.println("Removing for next iteration:: (" + tmpNode.getID() + ") " + tmpNode.toString()); markedNodes.add(tmpNode); } // as this node has inputs coming from different jobs, need to // free up everything // below and include the closest MapAndReduce lop if this is of // type Reduce. // if it is of type MapAndReduce, don't need to free any nodes if (!inputs_in_same_job && !unassigned_inputs && isChild(tmpNode, node) && (tmpNode == node.getInputs().get(0) || tmpNode == node.getInputs().get(1)) && tmpNode.isAligner()) { if (DEBUG) System.out .println("Removing for next iteration (" + tmpNode.getID() + ") " + tmpNode.toString()); markedNodes.add(tmpNode); } } } // we also need to delete all parent nodes of marked nodes for (int i = 0; i < execNodes.size(); i++) { if (DEBUG) System.out.println("Checking for removal - (" + execNodes.elementAt(i).getID() + ") " + execNodes.elementAt(i).toString()); if (hasChildNode(execNodes.elementAt(i), markedNodes)) { markedNodes.add(execNodes.elementAt(i)); if (DEBUG) System.out.println("Removing for next iteration - (" + execNodes.elementAt(i).getID() + ") " + execNodes.elementAt(i).toString()); } } // delete marked nodes from finishedNodes and execNodes // add to queued nodes for (int i = 0; i < markedNodes.size(); i++) { finishedNodes.remove(markedNodes.elementAt(i)); execNodes.remove(markedNodes.elementAt(i)); removeNodeByJobType(markedNodes.elementAt(i), jobvec); queuedNodes.add(markedNodes.elementAt(i)); } } private boolean branchCanBePiggyBackedReduce(N tmpNode, N node, Vector<N> execNodes, Vector<N> finishedNodes) { for(int i=0; i < execNodes.size(); i++) { N n = execNodes.elementAt(i); if(n.equals(node)) continue; if(n.equals(tmpNode) && n.getExecLocation() != ExecLocation.Map && n.getExecLocation() != ExecLocation.MapOrReduce) return false; if(isChild(n, node) && isChild(tmpNode, n) && !node.getInputs().contains(tmpNode) && n.getExecLocation() != ExecLocation.Map && n.getExecLocation() != ExecLocation.MapOrReduce) return false; } return true; } private boolean branchCanBePiggyBackedMapAndReduce(N tmpNode, N node, Vector<N> execNodes, Vector<N> finishedNodes) { for(int i=0; i < execNodes.size(); i++) { N n = execNodes.elementAt(i); if(n.equals(node)) continue; if(n.equals(tmpNode) && n.getExecLocation() != ExecLocation.Map && n.getExecLocation() != ExecLocation.MapOrReduce) return false; if(isChild(n, node) && isChild(tmpNode, n) && n.getExecLocation() != ExecLocation.Map && n.getExecLocation() != ExecLocation.MapOrReduce) return false; } return true; } private boolean branchHasNoOtherUnExecutedParents(N tmpNode, N node, Vector<N> execNodes, Vector <N> finishedNodes) { //if tmpNode has more than one unfinished output, return false if(tmpNode.getOutputs().size() > 1) { int cnt = 0; for (int j = 0; j < tmpNode.getOutputs().size(); j++) { if (!finishedNodes.contains(tmpNode.getOutputs().get(j))) cnt++; } if(cnt != 1) return false; } //check to see if any node between node and tmpNode has more than one unfinished output for(int i=0; i < execNodes.size(); i++) { N n = execNodes.elementAt(i); if(n.equals(node) || n.equals(tmpNode)) continue; if(isChild(n, node) && isChild(tmpNode, n)) { int cnt = 0; for (int j = 0; j < n.getOutputs().size(); j++) { if (!finishedNodes.contains(n.getOutputs().get(j))) cnt++; } if(cnt != 1) return false; } } return true; } /** * Method to check of there is a node of type MapAndReduce between a child * (tmpNode) and its parent (node) * * @param tmpNode * @param execNodes * @param node * @return */ private boolean hasMapAndReduceParentNode(N tmpNode, Vector<N> execNodes, N node) { for (int i = 0; i < tmpNode.getOutputs().size(); i++) { N n = (N) tmpNode.getOutputs().get(i); if (execNodes.contains(n) && n.getExecLocation() == ExecLocation.MapAndReduce && isChild(n, node)) { return true; } else { if (hasMapAndReduceParentNode(n, execNodes, node)) return true; } } return false; } /** * Method to return the job index for a lop. * * @param lops * @param jobvec * @return * @throws LopsException */ private int jobType(Lops lops, ArrayList<Vector<N>> jobvec) throws LopsException { for ( JobType jt : JobType.values()) { int i = jt.getId(); if (i > 0 && jobvec.get(i) != null && jobvec.get(i).contains(lops)) { return i; } } return -1; } /** * Method to see if there is a node of type Reduce between tmpNode and node * in execNodes * * @param tmpNode * @param execNodes * @param node * @return */ @SuppressWarnings("unchecked") private boolean hasOtherMapAndReduceParentNode(N tmpNode, Vector<N> execNodes, N node) { for (int i = 0; i < tmpNode.getOutputs().size(); i++) { N n = (N) tmpNode.getOutputs().get(i); if (execNodes.contains(n) && !n.equals(node) && n.getExecLocation() == ExecLocation.MapAndReduce && isChild(n, node)) { return true; } else { if (hasOtherMapAndReduceParentNode(n, execNodes, node)) return true; } } return false; } /** * Method to check if there is a queued node between tmpNode and node * * @param tmpNode * @param queuedNodes * @param node * @return */ @SuppressWarnings("unchecked") private boolean hasOtherQueuedParentNode(N tmpNode, Vector<N> queuedNodes, N node) { for (int i = 0; i < tmpNode.getOutputs().size(); i++) { N n = (N) tmpNode.getOutputs().get(i); if (queuedNodes.contains(n) && !n.equals(node) && isChild(n, node)) { return true; } else { if (hasOtherQueuedParentNode(n, queuedNodes, node)) return true; } } return false; } /** * Method to print the lops grouped by job type * * @param jobNodes * @throws DMLRuntimeException */ void printJobNodes(ArrayList<Vector<N>> jobNodes) throws DMLRuntimeException { if (!DEBUG) return; for ( JobType jt : JobType.values() ) { int i = jt.getId(); if (i > 0 && jobNodes.get(i) != null && jobNodes.get(i).size() > 0) { System.out.println(jt.getName() + " Job Nodes:"); for (int j = 0; j < jobNodes.get(i).size(); j++) { System.out.println(" " + jobNodes.get(i).elementAt(j).getID() + ") " + jobNodes.get(i).elementAt(j).toString()); } } } } /** * Method to check if there exists any lops with ExecLocation=RecordReader * * @param nodes * @param loc * @return */ boolean hasANode(Vector<N> nodes, ExecLocation loc) { for (int i = 0; i < nodes.size(); i++) { if (nodes.get(i).getExecLocation() == ExecLocation.RecordReader) return true; } return false; } ArrayList<Vector<N>> splitGMRNodesByRecordReader(Vector<N> gmrnodes) { // obtain the list of record reader nodes ArrayList<N> rrnodes = new ArrayList<N>(); for (int i = 0; i < gmrnodes.size(); i++) { if (gmrnodes.get(i).getExecLocation() == ExecLocation.RecordReader) rrnodes.add(gmrnodes.get(i)); } /* * We allocate one extra vector to hold lops that do not depend on any * recordreader lops */ ArrayList<Vector<N>> splitGMR = createNodeVectors(rrnodes.size() + 1); // flags to indicate whether a lop has been added to one of the node // vectors boolean[] flags = new boolean[gmrnodes.size()]; for (int i = 0; i < gmrnodes.size(); i++) { flags[i] = false; } // first, obtain all ancestors of recordreader lops for (int rrid = 0; rrid < rrnodes.size(); rrid++) { // prepare node list for i^th record reader lop // add record reader lop splitGMR.get(rrid).add(rrnodes.get(rrid)); for (int j = 0; j < gmrnodes.size(); j++) { if (rrnodes.get(rrid).equals(gmrnodes.get(j))) flags[j] = true; else if (isChild(rrnodes.get(rrid), gmrnodes.get(j))) { splitGMR.get(rrid).add(gmrnodes.get(j)); flags[j] = true; } } } // add all remaining lops to a separate job int jobindex = rrnodes.size(); // the last node vector for (int i = 0; i < gmrnodes.size(); i++) { if (flags[i] == false) { splitGMR.get(jobindex).add(gmrnodes.get(i)); flags[i] = true; } } return splitGMR; } /** * Method to generate hadoop jobs. Exec nodes can contains a mixture of node * types requiring different mr jobs. This method breaks the job into * sub-types and then invokes the appropriate method to generate * instructions. * * @param execNodes * @param inst * @param writeInst * @param deleteinst * @param jobNodes * @throws LopsException * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public void generateMRJobs(Vector<N> execNodes, ArrayList<Instruction> inst, ArrayList<Instruction> writeInst, ArrayList<Instruction> deleteinst, ArrayList<Vector<N>> jobNodes) throws LopsException, DMLUnsupportedOperationException, DMLRuntimeException { // copy unassigned lops in execnodes to gmrnodes for (int i = 0; i < execNodes.size(); i++) { N node = execNodes.elementAt(i); if (jobType(node, jobNodes) == -1) { jobNodes.get(JobType.GMR.getId()).add(node); addChildren(node, jobNodes.get(JobType.GMR.getId()), execNodes); } } if (DEBUG) { printJobNodes(jobNodes); } for (JobType jt : JobType.values()) { // do nothing, if jt = INVALID or ANY if ( jt == JobType.INVALID || jt == JobType.ANY ) continue; // TODO: Following hardcoding of JobType.PARTITION must be removed if ( jt == JobType.PARTITION ) { if ( jobNodes.get(jt.getId()).size() > 0 ) generatePartitionJob(jobNodes.get(jt.getId()), inst, deleteinst); continue; } int index = jt.getId(); // job id is used as an index into jobNodes Vector<N> currNodes = jobNodes.get(index); // generate MR job if (currNodes != null && currNodes.size() > 0) { if (DEBUG) System.out.println("Generating " + jt.getName() + " job"); if (jt.allowsRecordReaderInstructions() && hasANode(jobNodes.get(index), ExecLocation.RecordReader)) { // split the nodes by recordReader lops ArrayList<Vector<N>> rrlist = splitGMRNodesByRecordReader(jobNodes.get(index)); for (int i = 0; i < rrlist.size(); i++) { generateMapReduceInstructions(rrlist.get(i), inst, deleteinst, jt); } } else if ( jt.allowsSingleShuffleInstruction() ) { // These jobs allow a single shuffle instruction. // We should split the nodes so that a separate job is produced for each shuffle instruction. Lops.Type splittingLopType = jt.getShuffleLopType(); Vector<N> nodesForASingleJob = new Vector<N>(); for (int i = 0; i < jobNodes.get(index).size(); i++) { if (jobNodes.get(index).elementAt(i).getType() == splittingLopType) { nodesForASingleJob.clear(); // Add the lop that defines the split nodesForASingleJob.add(jobNodes.get(index).elementAt(i)); /* * Add the splitting lop's children. This call is redundant when jt=SORT * because a sort job ALWAYS has a SINGLE lop in the entire job * i.e., there are no children to add when jt=SORT. */ addChildren(jobNodes.get(index).elementAt(i), nodesForASingleJob, jobNodes.get(index)); if ( jt.isCompatibleWithParentNodes() ) { /* * If the splitting lop is compatible with parent nodes * then they must be added to the job. For example, MMRJ lop * may have a Data(Write) lop as its parent, which can be * executed along with MMRJ. */ addParents(jobNodes.get(index).elementAt(i), nodesForASingleJob, jobNodes.get(index)); } generateMapReduceInstructions(nodesForASingleJob, inst, deleteinst, jt); } } } else { // the default case generateMapReduceInstructions(jobNodes.get(index), inst, deleteinst, jt); } } } } /** * Method to get the input format for a lop * * @param elementAt * @return * @throws LopsException */ // This code is replicated in ReBlock.java private Format getChildFormat(N node) throws LopsException { if (node.getOutputParameters().getFile_name() != null || node.getOutputParameters().getLabel() != null) { return node.getOutputParameters().getFormat(); } else { if (node.getInputs().size() > 1) throw new LopsException("Should only have one child!"); /* * Return the format of the child node (i.e., input lop) No need of * recursion here.. because 1) Reblock lop's input can either be * DataLop or some intermediate computation If it is Data then we * just take its format (TEXT or BINARY) If it is intermediate lop * then it is always BINARY since we assume that all intermediate * computations will be in Binary format 2) Note that Reblock job * will never have any instructions in the mapper => the input lop * (if it is other than Data) is always executed in a different job */ return node.getInputs().get(0).getOutputParameters().getFormat(); // return getChildFormat((N) node.getInputs().get(0)); } } /** * Method to add all parents of "node" in exec_n to node_v. * * @param node * @param node_v * @param exec_n */ private void addParents(N node, Vector<N> node_v, Vector<N> exec_n) { for (int i = 0; i < exec_n.size(); i++) { if (isChild(node, exec_n.elementAt(i))) { if (!node_v.contains(exec_n.elementAt(i))) { if (DEBUG) { System.out.println("Adding parent - " + exec_n.elementAt(i).toString()); } node_v.add(exec_n.elementAt(i)); } } } } /** * Method to add all relevant data nodes for set of exec nodes. * * @param node * @param node_v * @param exec_n */ @SuppressWarnings("unchecked") private void addChildren(N node, Vector<N> node_v, Vector<N> exec_n) { if (node != null && DEBUG) System.out.println("Adding children " + node.toString()); /** add child in exec nodes that is not of type scalar **/ if (exec_n.contains(node) && node.getExecLocation() != ExecLocation.ControlProgram) { if (!node_v.contains(node)) node_v.add(node); } if (!exec_n.contains(node)) return; /** * recurse */ for (int i = 0; i < node.getInputs().size(); i++) { N n = (N) node.getInputs().get(i); addChildren(n, node_v, exec_n); } } private void generatePartitionJob(Vector<N> execNodes, ArrayList<Instruction> inst, ArrayList<Instruction> deleteinst) throws LopsException { ArrayList<Byte> resultIndices = new ArrayList<Byte>(); ArrayList<String> inputs = new ArrayList<String>(); ArrayList<String> outputs = new ArrayList<String>(); ArrayList<InputInfo> inputInfos = new ArrayList<InputInfo>(); ArrayList<OutputInfo> outputInfos = new ArrayList<OutputInfo>(); ArrayList<Long> numRows = new ArrayList<Long>(); ArrayList<Long> numCols = new ArrayList<Long>(); ArrayList<Long> numRowsPerBlock = new ArrayList<Long>(); ArrayList<Long> numColsPerBlock = new ArrayList<Long>(); ArrayList<String> inputLabels = new ArrayList<String>(); ArrayList<String> outputLabels = new ArrayList<String>(); HashMap<String, com.ibm.bi.dml.runtime.instructions.CPInstructions.Data> outputLabelValueMapping = new HashMap<String, com.ibm.bi.dml.runtime.instructions.CPInstructions.Data>(); HashMap<N, Integer> nodeIndexMapping = new HashMap<N, Integer>(); int numReducers = total_reducers; int replication = 1; Vector<N> rootNodes = new Vector<N>(); // find all root nodes getOutputNodes(execNodes, rootNodes, false); if (DEBUG) { System.out.println("rootNodes.size() = " + rootNodes.size() + ", execNodes.size() = " + execNodes.size()); rootNodes.get(0).printMe(); } for (int i = 0; i < rootNodes.size(); i++) getInputPathsAndParameters(rootNodes.elementAt(i), execNodes, inputs, inputInfos, numRows, numCols, numRowsPerBlock, numColsPerBlock, nodeIndexMapping, inputLabels); Vector<N> partitionNodes = new Vector<N>(); getPartitionNodes(execNodes, partitionNodes); PartitionParams pp = ((PartitionLop) partitionNodes.get(0)).getPartitionParams(); InputInfo[] inputInfo = new InputInfo[inputs.size()]; for (int i = 0; i < inputs.size(); i++) inputInfo[i] = inputInfos.get(i); MRJobInstruction mr = new MRJobInstruction(JobType.PARTITION); // update so folds are only reset for submatrix if (pp.isEL == false && pp.pt.name().equals("submatrix")) pp.numFoldsForSubMatrix(getLongArray(numRows)[0],getLongArray(numCols)[0]); outputLabelValueMapping = pp.getOutputLabelValueMapping(); String[] outputStrings = pp.getOutputStrings(); mr.setPartitionInstructions(getStringArray(inputs), inputInfo, outputStrings, numReducers, replication, getLongArray(numRows), getLongArray(numCols), getIntArray(numRowsPerBlock), getIntArray(numColsPerBlock), pp.getResultIndexes(), pp .getResultDimsUnknown(), pp, inputLabels, outputLabels, outputLabelValueMapping); inst.add(mr); } /** * Method that determines the output format for a given node. * * @param node * @return */ OutputInfo getOutputInfo(N node) { OutputInfo oinfo = null; if ( node.get_dataType() == DataType.SCALAR && node.getExecType() == ExecType.CP) return null; if (node.getOutputParameters().isBlocked_representation()) { oinfo = OutputInfo.BinaryBlockOutputInfo; } else { if (node.getOutputParameters().getFormat() == Format.TEXT) oinfo = OutputInfo.TextCellOutputInfo; else { oinfo = OutputInfo.BinaryCellOutputInfo; } } /* Instead of following hardcoding, one must get this information from Lops */ if (node.getType() == Type.SortKeys && node.getExecType() == ExecType.MR) { oinfo = OutputInfo.OutputInfoForSortOutput; //new OutputInfo(CompactOutputFormat.class, //DoubleWritable.class, IntWritable.class); } else if (node.getType() == Type.CombineBinary) { // Output format of CombineBinary (CB) depends on how the output is consumed CombineBinary combine = (CombineBinary) node; if ( combine.getOperation() == com.ibm.bi.dml.lops.CombineBinary.OperationTypes.PreSort ) { oinfo = OutputInfo.OutputInfoForSortInput; //new OutputInfo(SequenceFileOutputFormat.class, //DoubleWritable.class, IntWritable.class); } else if ( combine.getOperation() == com.ibm.bi.dml.lops.CombineBinary.OperationTypes.PreCentralMoment || combine.getOperation() == com.ibm.bi.dml.lops.CombineBinary.OperationTypes.PreCovUnweighted || combine.getOperation() == com.ibm.bi.dml.lops.CombineBinary.OperationTypes.PreGroupedAggUnweighted ) { oinfo = OutputInfo.WeightedPairOutputInfo; } } else if ( node.getType() == Type.CombineTertiary) { oinfo = OutputInfo.WeightedPairOutputInfo; } else if (node.getType() == Type.CentralMoment || node.getType() == Type.CoVariance || node.getType() == Type.GroupedAgg ) { // CMMR ang GroupedAggMR always operate in "cell mode", // and the output is always in cell format oinfo = OutputInfo.BinaryCellOutputInfo; } return oinfo; } /** * Method that determines the output format for a given node, * and returns a string representation of OutputInfo. This * method is primarily used while generating instructions that * execute in the control program. * * @param node * @return */ String getOutputFormat(N node) { return OutputInfo.outputInfoToString(getOutputInfo(node)); } /** * Method to setup output filenames and outputInfos, and to generate related instructions * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException * @throws LopsException */ private NodeOutput setupNodeOutputs(N node, ExecType et) throws DMLUnsupportedOperationException, DMLRuntimeException, LopsException { OutputParameters oparams = node.getOutputParameters(); NodeOutput out = new NodeOutput(); // Compute the output format for this node out.setOutInfo(getOutputInfo(node)); // If node is NOT of type Data then we must generate // a variable to hold the value produced by this node if (node.getExecLocation() != ExecLocation.Data) { if ( node.get_dataType() == DataType.SCALAR ) { oparams.setLabel("Var"+ var_index++); out.setVarName(oparams.getLabel()); out.addLastInstruction( CPInstructionParser.parseSingleInstruction( "CP" + Lops.OPERAND_DELIMITOR + "rmvar" + Lops.OPERAND_DELIMITOR + oparams.getLabel() ) ); } else { // generate temporary filename and a variable name to hold the output produced by "rootNode" oparams.setFile_name(scratch + ProgramConverter.CP_ROOT_THREAD_SEPARATOR + ProgramConverter.CP_ROOT_THREAD_ID + ProgramConverter.CP_ROOT_THREAD_SEPARATOR + "temp" + job_id++); oparams.setLabel("mVar" + var_index++ ); // generate an instruction that creates a symbol table entry for the new variable String createInst = prepareVariableInstruction("createvar", node); out.addPreInstruction(CPInstructionParser.parseSingleInstruction(createInst)); // temp file as well as the variable has to be deleted at the end out.addLastInstruction(CPInstructionParser.parseSingleInstruction( "CP" + Lops.OPERAND_DELIMITOR + "rmfilevar" + Lops.OPERAND_DELIMITOR + oparams.getLabel() + Lops.VALUETYPE_PREFIX + Expression.ValueType.UNKNOWN + Lops.OPERAND_DELIMITOR + "true" + Lops.VALUETYPE_PREFIX + "BOOLEAN")); // finally, add the generated filename and variable name to the list of outputs out.setFileName(oparams.getFile_name()); out.setVarName(oparams.getLabel()); } } // rootNode is of type Data else { if ( node.get_dataType() == DataType.SCALAR ) { // generate assignment operations for final and transient writes if ( oparams.getFile_name() == null ) { String io_inst = "CP" + Lops.OPERAND_DELIMITOR + "assignvar" + Lops.OPERAND_DELIMITOR + node.getInputs().get(0).getOutputParameters().getLabel() + Lops.DATATYPE_PREFIX + node.getInputs().get(0).get_dataType() + Lops.VALUETYPE_PREFIX + node.getInputs().get(0).get_valueType() + Lops.OPERAND_DELIMITOR + node.getOutputParameters().getLabel() + Lops.DATATYPE_PREFIX + node.get_dataType() + Lops.VALUETYPE_PREFIX + node.get_valueType(); out.addLastInstruction(CPInstructionParser.parseSingleInstruction(io_inst)); } else { String io_inst = node.getInstructions(node.getInputs().get(0).getOutputParameters().getLabel(), oparams.getFile_name()); out.addLastInstruction(CPInstructionParser.parseSingleInstruction(io_inst)); } } else { if ( ((Data)node).isTransient() ) { if ( et == ExecType.CP ) { // If transient matrix write is in CP then its input MUST be executed in CP as well. // get variable and filename associated with the input String inputFileName = node.getInputs().get(0).getOutputParameters().getFile_name(); String inputVarName = node.getInputs().get(0).getOutputParameters().getLabel(); String constVarName = oparams.getLabel(); String constFileName = inputFileName + constVarName; /* * Symbol Table state must change as follows: * * FROM: * mvar1 -> temp21 * * TO: * tVarH -> temp21tVarH */ // rename the temp variable to constant variable (e.g., mvvar mVar1 tVarH) out.addLastInstruction(CPInstructionParser .parseSingleInstruction("CP" + Lops.OPERAND_DELIMITOR + "mvvar" + Lops.OPERAND_DELIMITOR + inputVarName + Lops.OPERAND_DELIMITOR + constVarName)); // remove the old copy of transient file (rm temp21tVarH) out.addLastInstruction(CPInstructionParser .parseSingleInstruction("CP" + Lops.OPERAND_DELIMITOR + "rm" + Lops.OPERAND_DELIMITOR + constFileName)); // rename the new copy's name (e.g., mv temp21 temp21tVarA) out.addLastInstruction(CPInstructionParser .parseSingleInstruction("CP" + Lops.OPERAND_DELIMITOR + "mv" + Lops.OPERAND_DELIMITOR + inputFileName + Lops.OPERAND_DELIMITOR + constFileName)); // Now, tVarA refers to temporary filename temp21 // we need to update the file name (e.g., setfilename tVarA temp21tVarA remote) out.addLastInstruction(CPInstructionParser .parseSingleInstruction("CP" + Lops.OPERAND_DELIMITOR + "setfilename" + Lops.OPERAND_DELIMITOR + constVarName + Lops.DATATYPE_PREFIX + node.get_dataType() + Lops.VALUETYPE_PREFIX + node.get_valueType() + Lops.OPERAND_DELIMITOR + constFileName + Lops.OPERAND_DELIMITOR + "remote")); out.setFileName(constFileName); } else { /* * Since the "rootNode" is a transient data node, we first need to generate a * temporary filename as well as a variable name to hold the <i>immediate</i> * output produced by "rootNode". These generated HDFS filename and the * variable name must be changed at the end of an iteration/program block * so that the subsequent iteration/program block can correctly access the * generated data. Therefore, we need to distinguish between the following: * * 1) Temporary file name & variable name: They hold the immediate output * produced by "rootNode". Both names are generated below. * * 2) Constant file name & variable name: They are constant across iterations. * Variable name is given by rootNode's label that is created in the upper layers. * File name is generated by concatenating "temporary file name" and "constant variable name". * * Temporary files must be moved to constant files at the end of the iteration/program block. */ // generate temporary filename & var name String tempVarName = oparams.getLabel() + "temp"; String tempFileName = scratch + ProgramConverter.CP_ROOT_THREAD_SEPARATOR + ProgramConverter.CP_ROOT_THREAD_ID + ProgramConverter.CP_ROOT_THREAD_SEPARATOR + "temp" + job_id++; String createInst = prepareVariableInstruction("createvar", tempVarName, node.get_dataType(), node.get_valueType(), tempFileName, oparams, out.getOutInfo()); out.addPreInstruction(CPInstructionParser.parseSingleInstruction(createInst)); String constVarName = oparams.getLabel(); String constFileName = tempFileName + constVarName; oparams.setFile_name(scratch + ProgramConverter.CP_ROOT_THREAD_SEPARATOR + ProgramConverter.CP_ROOT_THREAD_ID + ProgramConverter.CP_ROOT_THREAD_SEPARATOR + constFileName); /* * Since this is a node that denotes a transient read/write, we need to make sure * that the data computed for a given variable in a given iteration is passed on * to the next iteration. This is done by generating miscellaneous instructions * that gets executed at the end of the program block. * * The state of the symbol table must change * * FROM: * tVarA -> temp21tVarA (old copy of temp21) * tVarAtemp -> temp21 (new copy that should override the old copy) * * TO: * tVarA -> temp21tVarA */ // rename the temp variable to constant variable (e.g., mvvar tVarAtemp tVarA) out.addLastInstruction(CPInstructionParser .parseSingleInstruction("CP" + Lops.OPERAND_DELIMITOR + "mvvar" + Lops.OPERAND_DELIMITOR + tempVarName + Lops.OPERAND_DELIMITOR + constVarName)); // remove the old copy of transient file (rm temp21tVarA) out.addLastInstruction(CPInstructionParser .parseSingleInstruction("CP" + Lops.OPERAND_DELIMITOR + "rm" + Lops.OPERAND_DELIMITOR + constFileName)); // rename the new copy's name (e.g., mv temp21 temp21tVarA) out.addLastInstruction(CPInstructionParser .parseSingleInstruction("CP" + Lops.OPERAND_DELIMITOR + "mv" + Lops.OPERAND_DELIMITOR + tempFileName + Lops.OPERAND_DELIMITOR + constFileName)); // Now, tVarA refers to temporary filename temp21 // we need to update the file name (e.g., setfilename tVarA temp21tVarA remote) out.addLastInstruction(CPInstructionParser .parseSingleInstruction("CP" + Lops.OPERAND_DELIMITOR + "setfilename" + Lops.OPERAND_DELIMITOR + constVarName + Lops.DATATYPE_PREFIX + node.get_dataType() + Lops.VALUETYPE_PREFIX + node.get_valueType() + Lops.OPERAND_DELIMITOR + constFileName + Lops.OPERAND_DELIMITOR + "remote")); // finally, add the temporary filename and variable name to the list of outputs out.setFileName(tempFileName); out.setVarName(tempVarName); } } // rootNode is not a transient write. It is a persistent write. else { if(et == ExecType.MR) { // create a variable to hold the result produced by this "rootNode" oparams.setLabel("pVar" + var_index++ ); String createInst = prepareVariableInstruction("createvar", node); out.addPreInstruction(CPInstructionParser.parseSingleInstruction(createInst)); // remove the variable out.addLastInstruction(CPInstructionParser.parseSingleInstruction( "CP" + Lops.OPERAND_DELIMITOR + "rmfilevar" + Lops.OPERAND_DELIMITOR + oparams.getLabel() + Lops.VALUETYPE_PREFIX + Expression.ValueType.UNKNOWN + Lops.OPERAND_DELIMITOR + "false" + Lops.VALUETYPE_PREFIX + "BOOLEAN")); // finally, add the filename and variable name to the list of outputs out.setFileName(oparams.getFile_name()); out.setVarName(oparams.getLabel()); } else { // generate a write instruction that writes matrix to HDFS String io_inst = node.getInstructions( node.getInputs().get(0).getOutputParameters().getLabel(), node.getOutputParameters().getFile_name()); out.addLastInstruction(CPInstructionParser.parseSingleInstruction(io_inst)); } } } } return out; } /** * Method to generate MapReduce job instructions from a given set of nodes. * * @param execNodes * @param inst * @param deleteinst * @param jobType * @throws LopsException * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException */ public void generateMapReduceInstructions(Vector<N> execNodes, ArrayList<Instruction> inst, ArrayList<Instruction> deleteinst, JobType jt) throws LopsException, DMLUnsupportedOperationException, DMLRuntimeException { ArrayList<Byte> resultIndices = new ArrayList<Byte>(); ArrayList<String> inputs = new ArrayList<String>(); ArrayList<String> outputs = new ArrayList<String>(); ArrayList<InputInfo> inputInfos = new ArrayList<InputInfo>(); ArrayList<OutputInfo> outputInfos = new ArrayList<OutputInfo>(); ArrayList<Long> numRows = new ArrayList<Long>(); ArrayList<Long> numCols = new ArrayList<Long>(); ArrayList<Long> numRowsPerBlock = new ArrayList<Long>(); ArrayList<Long> numColsPerBlock = new ArrayList<Long>(); ArrayList<String> mapperInstructions = new ArrayList<String>(); ArrayList<String> randInstructions = new ArrayList<String>(); ArrayList<String> recordReaderInstructions = new ArrayList<String>(); int numReducers = 0; int replication = 1; ArrayList<String> inputLabels = new ArrayList<String>(); ArrayList<String> outputLabels = new ArrayList<String>(); ArrayList<Instruction> renameInstructions = new ArrayList<Instruction>(); ArrayList<Instruction> variableInstructions = new ArrayList<Instruction>(); /* Find the nodes that produce an output */ Vector<N> rootNodes = new Vector<N>(); getOutputNodes(execNodes, rootNodes, !jt.producesIntermediateOutput()); if (DEBUG) { System.out.println("# of root nodes = " + rootNodes.size()); } /* Remove transient writes that are simple copy of transient reads */ if (jt == JobType.GMR) { Vector<N> markedNodes = new Vector<N>(); // only keep data nodes that are results of some computation. for (int i = 0; i < rootNodes.size(); i++) { N node = rootNodes.elementAt(i); if (node.getExecLocation() == ExecLocation.Data && ((Data) node).isTransient() && ((Data) node).getOperationType() == OperationTypes.WRITE && ((Data) node).get_dataType() == DataType.MATRIX) { // no computation, just a copy if (node.getInputs().get(0).getExecLocation() == ExecLocation.Data && ((Data) node.getInputs().get(0)).isTransient() && node.getOutputParameters().getLabel().compareTo( node.getInputs().get(0) .getOutputParameters().getLabel()) == 0) { markedNodes.add(node); } } } // delete marked nodes rootNodes.removeAll(markedNodes); markedNodes.clear(); if (rootNodes.size() == 0) return; } // structure that maps node to their indices that will be used in the instructions HashMap<N, Integer> nodeIndexMapping = new HashMap<N, Integer>(); /* Determine all input data files */ for (int i = 0; i < rootNodes.size(); i++) { getInputPathsAndParameters(rootNodes.elementAt(i), execNodes, inputs, inputInfos, numRows, numCols, numRowsPerBlock, numColsPerBlock, nodeIndexMapping, inputLabels); } // In case of RAND job, instructions are defined in the input file if (jt == JobType.RAND) randInstructions = inputs; int[] start_index = new int[1]; start_index[0] = inputs.size(); /* Get RecordReader Instructions */ // currently, recordreader instructions are allowed only in GMR jobs if (jt == JobType.GMR) { for (int i = 0; i < rootNodes.size(); i++) { getRecordReaderInstructions(rootNodes.elementAt(i), execNodes, inputs, recordReaderInstructions, nodeIndexMapping, start_index, inputLabels); } } /* Get Mapper Instructions */ for (int i = 0; i < rootNodes.size(); i++) { getMapperInstructions(rootNodes.elementAt(i), execNodes, inputs, mapperInstructions, nodeIndexMapping, start_index, inputLabels); } if (DEBUG) { System.out.println(" Input strings: " + inputs.toString()); if (jt == JobType.RAND) System.out.println(" Rand instructions: " + getCSVString(randInstructions)); if (jt == JobType.GMR) System.out.println(" RecordReader instructions: " + getCSVString(recordReaderInstructions)); System.out.println(" Mapper instructions: " + getCSVString(mapperInstructions)); } /* Get Shuffle and Reducer Instructions */ ArrayList<String> shuffleInstructions = new ArrayList<String>(); ArrayList<String> aggInstructionsReducer = new ArrayList<String>(); ArrayList<String> otherInstructionsReducer = new ArrayList<String>(); for (int i = 0; i < rootNodes.size(); i++) { int resultIndex = getAggAndOtherInstructions( rootNodes.elementAt(i), execNodes, shuffleInstructions, aggInstructionsReducer, otherInstructionsReducer, nodeIndexMapping, start_index, inputLabels); resultIndices.add(new Byte((byte) resultIndex)); // setup output filenames and outputInfos and generate related instructions NodeOutput out = setupNodeOutputs(rootNodes.elementAt(i), ExecType.MR); outputLabels.add(out.getVarName()); outputs.add(out.getFileName()); //if ( out.getFileName() == null ) // System.err.println("error here .. "); outputInfos.add(out.getOutInfo()); renameInstructions.addAll(out.getLastInstructions()); variableInstructions.addAll(out.getPreInstructions()); } // a sanity check if (resultIndices.size() != rootNodes.size()) { throw new LopsException("Unexected error in piggybacking: " + resultIndices.size() + " != " + rootNodes.size()); } /* Determine if the output dimensions are known */ byte[] resultIndicesByte = new byte[resultIndices.size()]; byte[] resultDimsUnknown = new byte[resultIndices.size()]; for (int i = 0; i < resultIndicesByte.length; i++) { resultIndicesByte[i] = resultIndices.get(i).byteValue(); // check if the output matrix dimensions are known at compile time if (rootNodes.elementAt(i).getOutputParameters().getNum_rows() == -1 && rootNodes.elementAt(i).getOutputParameters() .getNum_cols() == -1) { resultDimsUnknown[i] = (byte) 1; } else { resultDimsUnknown[i] = (byte) 0; } } if (DEBUG) { System.out.println(" Shuffle/Aggregate Instructions: " + getCSVString(aggInstructionsReducer)); System.out.println(" Other instructions =" + getCSVString(otherInstructionsReducer)); System.out.println(" Output strings: " + outputs.toString()); System.out.println(" ResultIndices = " + resultIndices.toString()); System.out.println(" ResultDimsUnknown = " + resultDimsUnknown.toString()); } /* Prepare the MapReduce job instruction */ MRJobInstruction mr = new MRJobInstruction(jt); // check if this is a map-only job. If not, set the number of reducers //if (getCSVString(shuffleInstructions).compareTo("") != 0 || getCSVString(aggInstructionsReducer).compareTo("") != 0 // || getCSVString(otherInstructionsReducer).compareTo("") != 0) // numReducers = total_reducers; if ( shuffleInstructions.size() > 0 || aggInstructionsReducer.size() > 0 || otherInstructionsReducer.size() > 0 ) numReducers = total_reducers; // set inputs, outputs, and other other properties for the job mr.setInputs(getStringArray(inputs),getInputInfoArray(inputInfos)); mr.setInputDimensions(getLongArray(numRows), getIntArray(numRowsPerBlock), getLongArray(numCols), getIntArray(numColsPerBlock)); mr.setOutputs(getStringArray(outputs), getOutputInfoArray(outputInfos), resultIndicesByte); mr.setOutputDimensions(resultDimsUnknown); mr.setNumberOfReducers(numReducers); mr.setReplication(replication); mr.setInputOutputLabels(inputLabels, outputLabels); // set instructions for recordReader and mapper mr.setRecordReaderInstructions(getCSVString(recordReaderInstructions)); mr.setMapperInstructions(getCSVString(mapperInstructions)); if ( jt == JobType.RAND ) mr.setRandInstructions(getCSVString(randInstructions)); // set shuffle instructions mr.setShuffleInstructions(getCSVString(shuffleInstructions)); // set reducer instruction mr.setAggregateInstructionsInReducer(getCSVString(aggInstructionsReducer)); mr.setOtherInstructionsInReducer(getCSVString(otherInstructionsReducer)); /* Add the prepared instructions to output set */ inst.addAll(variableInstructions); inst.add(mr); deleteinst.addAll(renameInstructions); } /** * Convert a byte array into string * * @param arr * @return none */ public String getString(byte[] arr) { String s = ""; for (int i = 0; i < arr.length; i++) s = s + "," + Byte.toString(arr[i]); return s; } /** * converts an array list into a comma separated string * * @param inputStrings * @return */ private String getCSVString(ArrayList<String> inputStrings) { String s = ""; for (int i = 0; i < inputStrings.size(); i++) { if (inputStrings.get(i) != null) { if (s.compareTo("") == 0) s = inputStrings.get(i); else s += "," + inputStrings.get(i); } } return s; } /** * converts an array list of strings into an array of string * * @param list * @return */ private String[] getStringArray(ArrayList<String> list) { String[] arr = new String[list.size()]; for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i); } return arr; } /** * converts an array list of OutputInfo into an array of OutputInfo * * @param infos * @return */ private OutputInfo[] getOutputInfoArray(ArrayList<OutputInfo> infos) { OutputInfo[] arr = new OutputInfo[infos.size()]; for (int i = 0; i < arr.length; i++) { arr[i] = infos.get(i); } return arr; } /** * converts an array list of InputInfo into an array of InputInfo * * @param infos * @return */ private InputInfo[] getInputInfoArray(ArrayList<InputInfo> infos) { InputInfo[] arr = new InputInfo[infos.size()]; for (int i = 0; i < arr.length; i++) { arr[i] = infos.get(i); } return arr; } /** * converts an array list of long into an array of long * * @param list * @return */ private long[] getLongArray(ArrayList<Long> list) { long[] arr = new long[list.size()]; for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i); } return arr; } /** * converts an array of longs into an array of int * * @param list * @return */ private int[] getIntArray(ArrayList<Long> list) { int[] arr = new int[list.size()]; for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i).intValue(); } return arr; } /** * Method to populate aggregate and other instructions in reducer. * * @param node * @param execNodes * @param aggInstructionsReducer * @param otherInstructionsReducer * @param nodeIndexMapping * @param start_index * @param inputLabels * @return * @throws LopsException */ @SuppressWarnings("unchecked") private int getAggAndOtherInstructions(N node, Vector<N> execNodes, ArrayList<String> shuffleInstructions, ArrayList<String> aggInstructionsReducer, ArrayList<String> otherInstructionsReducer, HashMap<N, Integer> nodeIndexMapping, int[] start_index, ArrayList<String> inputLabels) throws LopsException { int ret_val = -1; if (nodeIndexMapping.containsKey(node)) return nodeIndexMapping.get(node); // if not an input source and not in exec nodes, return. if (!execNodes.contains(node)) return ret_val; ArrayList<Integer> inputIndices = new ArrayList<Integer>(); // recurse for (int i = 0; i < node.getInputs().size(); i++) { ret_val = getAggAndOtherInstructions((N) node.getInputs().get(i), execNodes, shuffleInstructions, aggInstructionsReducer, otherInstructionsReducer, nodeIndexMapping, start_index, inputLabels); inputIndices.add(ret_val); } // have to verify if this is needed if (node.getExecLocation() == ExecLocation.Data) { return ret_val; } if (node.getExecLocation() == ExecLocation.MapAndReduce) { /* Generate Shuffle Instruction for "node", and return the index associated with produced output */ boolean flag = false; int output_index = start_index[0]; switch(node.getType()) { /* Lop types that take a single input */ case ReBlock: case SortKeys: case CentralMoment: case CoVariance: case GroupedAgg: shuffleInstructions.add(node.getInstructions(inputIndices.get(0), output_index)); break; /* Lop types that take two inputs */ case MMCJ: case MMRJ: case CombineBinary: shuffleInstructions.add(node.getInstructions(inputIndices.get(0), inputIndices.get(1), output_index)); break; /* Lop types that take three inputs */ case CombineTertiary: shuffleInstructions.add(node.getInstructions(inputIndices .get(0), inputIndices.get(1), inputIndices.get(2), output_index)); break; default: flag = true; break; } if ( !flag ) { nodeIndexMapping.put(node, output_index); start_index[0]++; return output_index; } else { return inputIndices.get(0); } } /* Get instructions for aligned reduce and other lops below the reduce. */ if (node.getExecLocation() == ExecLocation.Reduce || hasChildNode(node, execNodes, ExecLocation.MapAndReduce)) { if (inputIndices.size() == 1) { int output_index = start_index[0]; start_index[0]++; if (node.getType() == Type.Aggregate) aggInstructionsReducer.add(node.getInstructions( inputIndices.get(0), output_index)); else otherInstructionsReducer.add(node.getInstructions( inputIndices.get(0), output_index)); nodeIndexMapping.put(node, output_index); return output_index; } else if (inputIndices.size() == 2) { int output_index = start_index[0]; start_index[0]++; otherInstructionsReducer.add(node.getInstructions(inputIndices .get(0), inputIndices.get(1), output_index)); nodeIndexMapping.put(node, output_index); // populate list of input labels. // only Unary lops can contribute to labels if (node instanceof Unary && node.getInputs().size() > 1) { int index = 0; for (int i = 0; i < node.getInputs().size(); i++) { if (node.getInputs().get(i).get_dataType() == DataType.SCALAR) { index = i; break; } } if (node.getInputs().get(index).getExecLocation() == ExecLocation.Data && !((Data) (node.getInputs().get(index))) .isLiteral()) inputLabels.add(node.getInputs().get(index) .getOutputParameters().getLabel()); if (node.getInputs().get(index).getExecLocation() != ExecLocation.Data) inputLabels.add(node.getInputs().get(index) .getOutputParameters().getLabel()); } return output_index; } else if (inputIndices.size() == 3) { int output_index = start_index[0]; start_index[0]++; if (node.getType() == Type.Tertiary ) { //Tertiary.OperationTypes op = ((Tertiary<?, ?, ?, ?>) node).getOperationType(); //if ( op == Tertiary.OperationTypes.CTABLE_TRANSFORM ) { // in case of CTABLE_TRANSFORM_SCALAR_WEIGHT: inputIndices.get(2) would be -1 otherInstructionsReducer.add(node.getInstructions( inputIndices.get(0), inputIndices.get(1), inputIndices.get(2), output_index)); nodeIndexMapping.put(node, output_index); } return output_index; } else throw new LopsException("Invalid number of inputs to a lop: " + inputIndices.size()); } return -1; } /** * Method to get record reader instructions for a MR job. * * @param node * @param execNodes * @param inputStrings * @param recordReaderInstructions * @param nodeIndexMapping * @param start_index * @param inputLabels * @return * @throws LopsException */ @SuppressWarnings("unchecked") private int getRecordReaderInstructions(N node, Vector<N> execNodes, ArrayList<String> inputStrings, ArrayList<String> recordReaderInstructions, HashMap<N, Integer> nodeIndexMapping, int[] start_index, ArrayList<String> inputLabels) throws LopsException { // if input source, return index if (nodeIndexMapping.containsKey(node)) return nodeIndexMapping.get(node); // not input source and not in exec nodes, then return. if (!execNodes.contains(node)) return -1; ArrayList<Integer> inputIndices = new ArrayList<Integer>(); int max_input_index = -1; N child_for_max_input_index = null; // get mapper instructions for (int i = 0; i < node.getInputs().size(); i++) { // recurse N childNode = (N) node.getInputs().get(i); int ret_val = getRecordReaderInstructions(childNode, execNodes, inputStrings, recordReaderInstructions, nodeIndexMapping, start_index, inputLabels); inputIndices.add(ret_val); if (ret_val > max_input_index) { max_input_index = ret_val; child_for_max_input_index = childNode; } } // only lops with execLocation as RecordReader can contribute // instructions if ((node.getExecLocation() == ExecLocation.RecordReader)) { int output_index = max_input_index; // cannot reuse index if this is true // need to add better indexing schemes // if (child_for_max_input_index.getOutputs().size() > 1) { output_index = start_index[0]; start_index[0]++; nodeIndexMapping.put(node, output_index); // populate list of input labels. // only Ranagepick lop can contribute to labels if (node.getType() == Type.PickValues) { PickByCount pbc = (PickByCount) node; if (pbc.getOperationType() == PickByCount.OperationTypes.RANGEPICK) { int scalarIndex = 1; // always the second input is a scalar // if data lop not a literal -- add label if (node.getInputs().get(scalarIndex).getExecLocation() == ExecLocation.Data && !((Data) (node.getInputs().get(scalarIndex))) .isLiteral()) inputLabels.add(node.getInputs().get(scalarIndex) .getOutputParameters().getLabel()); // if not data lop, then this is an intermediate variable. if (node.getInputs().get(scalarIndex).getExecLocation() != ExecLocation.Data) inputLabels.add(node.getInputs().get(scalarIndex) .getOutputParameters().getLabel()); } } // get recordreader instruction. if (node.getInputs().size() == 2) recordReaderInstructions.add(node.getInstructions(inputIndices .get(0), inputIndices.get(1), output_index)); else throw new LopsException( "Unexpected number of inputs while generating a RecordReader Instruction"); return output_index; } return -1; } /** * Method to get mapper instructions for a MR job. * * @param node * @param execNodes * @param inputStrings * @param instructionsInMapper * @param nodeIndexMapping * @param start_index * @param inputLabels * @return * @throws LopsException */ @SuppressWarnings("unchecked") private int getMapperInstructions(N node, Vector<N> execNodes, ArrayList<String> inputStrings, ArrayList<String> instructionsInMapper, HashMap<N, Integer> nodeIndexMapping, int[] start_index, ArrayList<String> inputLabels) throws LopsException { // if input source, return index if (nodeIndexMapping.containsKey(node)) return nodeIndexMapping.get(node); // not input source and not in exec nodes, then return. if (!execNodes.contains(node)) return -1; ArrayList<Integer> inputIndices = new ArrayList<Integer>(); int max_input_index = -1; // get mapper instructions for (int i = 0; i < node.getInputs().size(); i++) { // recurse N childNode = (N) node.getInputs().get(i); int ret_val = getMapperInstructions(childNode, execNodes, inputStrings, instructionsInMapper, nodeIndexMapping, start_index, inputLabels); inputIndices.add(ret_val); if (ret_val > max_input_index) { max_input_index = ret_val; } } // only map and map-or-reduce without a reduce child node can contribute // to mapper instructions. if ((node.getExecLocation() == ExecLocation.Map || node .getExecLocation() == ExecLocation.MapOrReduce) && !hasChildNode(node, execNodes, ExecLocation.MapAndReduce)) { int output_index = max_input_index; // cannot reuse index if this is true // need to add better indexing schemes // if (child_for_max_input_index.getOutputs().size() > 1) { output_index = start_index[0]; start_index[0]++; nodeIndexMapping.put(node, output_index); // populate list of input labels. // only Unary lops can contribute to labels if (node instanceof Unary && node.getInputs().size() > 1) { // Following code must be executed only for those Unary // operators that have more than one input // It should not be executed for "true" unary operators like // cos(A). int index = 0; for (int i1 = 0; i1 < node.getInputs().size(); i1++) { if (node.getInputs().get(i1).get_dataType() == DataType.SCALAR) { index = i1; break; } } // if data lop not a literal -- add label if (node.getInputs().get(index).getExecLocation() == ExecLocation.Data && !((Data) (node.getInputs().get(index))).isLiteral()) inputLabels.add(node.getInputs().get(index) .getOutputParameters().getLabel()); // if not data lop, then this is an intermediate variable. if (node.getInputs().get(index).getExecLocation() != ExecLocation.Data) inputLabels.add(node.getInputs().get(index) .getOutputParameters().getLabel()); } // get mapper instruction. if (node.getInputs().size() == 1) instructionsInMapper.add(node.getInstructions(inputIndices .get(0), output_index)); if (node.getInputs().size() == 2) instructionsInMapper.add(node.getInstructions(inputIndices .get(0), inputIndices.get(1), output_index)); if (node.getInputs().size() == 3) instructionsInMapper.add(node.getInstructions(inputIndices.get(0), inputIndices.get(1), inputIndices.get(2), output_index)); if ( node.getInputs().size() == 5) { // Example: RangeBasedReIndex A[row_l:row_u, col_l:col_u] instructionsInMapper.add(node.getInstructions( inputIndices.get(0), inputIndices.get(1), inputIndices.get(2), inputIndices.get(3), inputIndices.get(4), output_index )); } return output_index; } return -1; } // Method to populate inputs and also populates node index mapping. @SuppressWarnings("unchecked") private void getInputPathsAndParameters(N node, Vector<N> execNodes, ArrayList<String> inputStrings, ArrayList<InputInfo> inputInfos, ArrayList<Long> numRows, ArrayList<Long> numCols, ArrayList<Long> numRowsPerBlock, ArrayList<Long> numColsPerBlock, HashMap<N, Integer> nodeIndexMapping, ArrayList<String> inputLabels) throws LopsException { // treat rand as an input. if (node.getType() == Type.RandLop && execNodes.contains(node) && !nodeIndexMapping.containsKey(node)) { numRows.add(node.getOutputParameters().getNum_rows()); numCols.add(node.getOutputParameters().getNum_cols()); numRowsPerBlock.add(node.getOutputParameters() .getNum_rows_per_block()); numColsPerBlock.add(node.getOutputParameters() .getNum_cols_per_block()); inputStrings.add(node.getInstructions(inputStrings.size(), inputStrings.size())); inputInfos.add(InputInfo.TextCellInputInfo); nodeIndexMapping.put(node, inputStrings.size() - 1); return; } // && ( !(node.getExecLocation() == ExecLocation.ControlProgram) // || (node.getExecLocation() == ExecLocation.ControlProgram && // node.get_dataType() != DataType.SCALAR ) // get input file names if (!execNodes.contains(node) && !nodeIndexMapping.containsKey(node) && !(node.getExecLocation() == ExecLocation.Data) && (!(node.getExecLocation() == ExecLocation.ControlProgram && node .get_dataType() == DataType.SCALAR)) || (!execNodes.contains(node) && node.getExecLocation() == ExecLocation.Data && ((Data) node).getOperationType() == Data.OperationTypes.READ && ((Data) node).get_dataType() == DataType.MATRIX && !nodeIndexMapping .containsKey(node))) { if (node.getOutputParameters().getFile_name() != null) { inputStrings.add(node.getOutputParameters().getFile_name()); } else { // use label name inputStrings.add(Lops.VARIABLE_NAME_PLACEHOLDER + node.getOutputParameters().getLabel() + Lops.VARIABLE_NAME_PLACEHOLDER); } //if ( node.getType() == Lops.Type.Data && ((Data)node).isTransient()) // inputStrings.add("##" + node.getOutputParameters().getLabel() + "##"); //else // inputStrings.add(node.getOutputParameters().getLabel()); inputLabels.add(node.getOutputParameters().getLabel()); numRows.add(node.getOutputParameters().getNum_rows()); numCols.add(node.getOutputParameters().getNum_cols()); numRowsPerBlock.add(node.getOutputParameters() .getNum_rows_per_block()); numColsPerBlock.add(node.getOutputParameters() .getNum_cols_per_block()); InputInfo nodeInputInfo = null; // Check if file format type is binary or text and update infos if (node.getOutputParameters().isBlocked_representation()) { if (node.getOutputParameters().getFormat() == Format.BINARY) nodeInputInfo = InputInfo.BinaryBlockInputInfo; else throw new LopsException("Invalid format (" + node.getOutputParameters().getFormat() + ") encountered for a node/lop with blocked output."); // inputInfos.add(InputInfo.BinaryBlockInputInfo); } else { if (node.getOutputParameters().getFormat() == Format.TEXT) nodeInputInfo = InputInfo.TextCellInputInfo; // inputInfos.add(InputInfo.TextCellInputInfo); else { nodeInputInfo = InputInfo.BinaryCellInputInfo; // inputInfos.add(InputInfo.BinaryCellInputInfo); } } /* * Hardcode output Key and Value Classes for SortKeys */ // TODO: statiko -- remove this hardcoding -- i.e., lops must encode // the information on key/value classes if (node.getType() == Type.SortKeys) { // SortKeys is the input to some other lop (say, L) // InputInfo of L is the ouputInfo of SortKeys, which is // (compactformat, doubleWriteable, IntWritable) nodeInputInfo = new InputInfo(PickFromCompactInputFormat.class, DoubleWritable.class, IntWritable.class); } else if (node.getType() == Type.CombineBinary) { // CombineBinary is the input to some other lop (say, L) // InputInfo of L is the ouputInfo of CombineBinary // And, the outputInfo of CombineBinary depends on the operation! CombineBinary combine = (CombineBinary) node; if ( combine.getOperation() == com.ibm.bi.dml.lops.CombineBinary.OperationTypes.PreSort ) { nodeInputInfo = new InputInfo(SequenceFileInputFormat.class, DoubleWritable.class, IntWritable.class); } else if ( combine.getOperation() == com.ibm.bi.dml.lops.CombineBinary.OperationTypes.PreCentralMoment || combine.getOperation() == com.ibm.bi.dml.lops.CombineBinary.OperationTypes.PreCovUnweighted || combine.getOperation() == com.ibm.bi.dml.lops.CombineBinary.OperationTypes.PreGroupedAggUnweighted ) { nodeInputInfo = InputInfo.WeightedPairInputInfo; } } else if ( node.getType() == Type.CombineTertiary ) { nodeInputInfo = InputInfo.WeightedPairInputInfo; } inputInfos.add(nodeInputInfo); nodeIndexMapping.put(node, inputStrings.size() - 1); return; } // if exec nodes does not contain node at this point, return. if (!execNodes.contains(node)) return; // process children recursively for (int i = 0; i < node.getInputs().size(); i++) { N childNode = (N) node.getInputs().get(i); getInputPathsAndParameters(childNode, execNodes, inputStrings, inputInfos, numRows, numCols, numRowsPerBlock, numColsPerBlock, nodeIndexMapping, inputLabels); } } /** * Method to find all terminal nodes. * * @param execNodes * @param rootNodes */ private void getOutputNodes(Vector<N> execNodes, Vector<N> rootNodes, boolean include_intermediate) { for (int i = 0; i < execNodes.size(); i++) { N node = execNodes.elementAt(i); // terminal node if (node.getOutputs().size() == 0 && !rootNodes.contains(node)) { rootNodes.add(node); } else { // check for nodes with at least one child outside execnodes int cnt = 0; for (int j = 0; j < node.getOutputs().size(); j++) { if (!execNodes.contains(node.getOutputs().get(j))) { cnt++; } } if (cnt != 0 && cnt <= node.getOutputs().size() && !rootNodes.contains(node) && !(node.getExecLocation() == ExecLocation.Data && ((Data) node).getOperationType() == OperationTypes.READ && ((Data) node) .get_dataType() == DataType.MATRIX)) { if (cnt < node.getOutputs().size()) { if (include_intermediate) rootNodes.add(node); } else rootNodes.add(node); } } } } private void getPartitionNodes(Vector<N> execNodes, Vector<N> partitionNodes) { for (int i = 0; i < execNodes.size(); i++) { N node = execNodes.elementAt(i); if (node.getType() == Lops.Type.PartitionLop) partitionNodes.add(node); } } /** * check to see if a is the child of b * * @param a * @param b */ public static boolean isChild(Lops a, Lops b) { for (int i = 0; i < b.getInputs().size(); i++) { if (b.getInputs().get(i).equals(a)) return true; /** * dfs search */ boolean return_val = isChild(a, b.getInputs().get(i)); /** * return true, if matching parent found, else continue */ if (return_val) return true; } return false; } @SuppressWarnings("unchecked") /** * Method to topologically sort lops * * @param v */ private void doTopologicalSort_strict_order(Vector<N> v) { int numNodes = v.size(); /* * Step 1: compute the level for each node in the DAG. * Step 2: sort the nodes by level, and within a level by node ID. */ /* * Source nodes with no inputs are at level zero. * level(v) = max( levels(v.inputs) ) + 1. */ // initialize for (int i = 0; i < numNodes; i++) { v.get(i).setLevel(-1); } // BFS (breadth-first) style of algorithm. Queue<N> q = new LinkedList<N>(); /* * A node is marked visited only afterall its inputs are visited. * A node is added to sortedNodes and its levelmap is updated only when * it is visited. */ int numSourceNodes = 0; for (int i = 0; i < numNodes; i++) { if (v.get(i).getInputs().size() == 0) { v.get(i).setLevel(0); q.add(v.get(i)); // add to queue numSourceNodes++; } } N n, parent; int maxLevel, inputLevel; boolean markAsVisited; while (q.size() != 0) { n = q.remove(); // check if outputs of "n" can be marked as visited for (int i = 0; i < n.getOutputs().size(); i++) { parent = (N) n.getOutputs().get(i); markAsVisited = true; maxLevel = -1; for (int j = 0; j < parent.getInputs().size(); j++) { inputLevel = parent.getInputs().get(j).getLevel(); if (inputLevel == -1) { // "parent" can not be visited if any of its inputs are // not visited markAsVisited = false; break; } if (maxLevel < inputLevel) maxLevel = inputLevel; } if (markAsVisited == true) { // mark "parent" as visited parent.setLevel(maxLevel + 1); q.add(parent); } } } // Step2: sort nodes by level, and then by node ID Object[] nodearray = v.toArray(); Arrays.sort(nodearray, new LopComparator()); // Copy sorted nodes into "v" v.clear(); for (int i = 0; i < nodearray.length; i++) { v.add((N) nodearray[i]); } // Sanity check -- can be removed for (int i = 1; i < v.size(); i++) { if (v.get(i).getLevel() < v.get(i - 1).getLevel() || (v.get(i).getLevel() == v.get(i - 1).getLevel() && v .get(i).getID() <= v.get(i - 1).getID())) { try { throw new DMLRuntimeException( "Unexpected error in topological sort."); } catch (DMLRuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // print the nodes in sorted order if (DEBUG) { for (int i = 0; i < v.size(); i++) { // System.out.print(sortedNodes.get(i).getID() + "(" // + levelmap.get(sortedNodes.get(i).getID()) + "), "); System.out.print(v.get(i).getID() + "(" + v.get(i).getLevel() + "), "); } System.out.println(""); System.out.println("topological sort -- done"); } } @SuppressWarnings("unchecked") private boolean hasChildNode(N node, Vector<N> childNodes, ExecLocation type) { for (int i = 0; i < node.getInputs().size(); i++) { N n = (N) node.getInputs().get(i); if (childNodes.contains(n) && n.getExecLocation() == type) { return true; } else { if (hasChildNode(n, childNodes, type)) return true; } } return false; } @SuppressWarnings("unchecked") private N getChildNode(N node, Vector<N> childNodes, ExecLocation type) { for (int i = 0; i < node.getInputs().size(); i++) { N n = (N) node.getInputs().get(i); if (childNodes.contains(n) && n.getExecLocation() == type) { return n; } else { return getChildNode(n, childNodes, type); } } return null; } /* * Returns a node "n" such that * 1) n \in parentNodes * 2) n is an ancestor of "node" * 3) n.ExecLocation = type * * Returns null if no such "n" exists * */ @SuppressWarnings("unchecked") private N getParentNode(N node, Vector<N> parentNodes, ExecLocation type) { for (int i = 0; i < node.getOutputs().size(); i++) { N n = (N) node.getOutputs().get(i); if (parentNodes.contains(n) && n.getExecLocation() == type) { return n; } else { return getParentNode(n, parentNodes, type); } } return null; } // Checks if "node" has any descendants in nodesVec with definedMRJob flag // set to true @SuppressWarnings("unchecked") private boolean hasMRJobChildNode(N node, Vector<N> nodesVec) { for (int i = 0; i < node.getInputs().size(); i++) { N n = (N) node.getInputs().get(i); if (nodesVec.contains(n) && n.definesMRJob()) { return true; } else { if (hasMRJobChildNode(n, nodesVec)) return true; } } return false; } // Find the descendant of "node" in "nodeVec" that has its definedMRJob flag set to true // returns null if no such descendant exists in nodeVec @SuppressWarnings("unchecked") private N getMRJobChildNode(N node, Vector<N> nodesVec) { for (int i = 0; i < node.getInputs().size(); i++) { N n = (N) node.getInputs().get(i); if (nodesVec.contains(n) && n.definesMRJob()) { return n; } else { N ret = getMRJobChildNode(n, nodesVec); if ( ret != null ) return ret; } } return null; } private int getChildAlignment(N node, Vector<N> execNodes, ExecLocation type) { for (int i = 0; i < node.getInputs().size(); i++) { N n = (N) node.getInputs().get(i); if (!execNodes.contains(n)) continue; if (execNodes.contains(n) && n.getExecLocation() == type) { if (n.getBreaksAlignment()) return MR_CHILD_FOUND_BREAKS_ALIGNMENT; else return MR_CHILD_FOUND_DOES_NOT_BREAK_ALIGNMENT; } else { int ret = getChildAlignment(n, execNodes, type); if (ret == MR_CHILD_FOUND_DOES_NOT_BREAK_ALIGNMENT || ret == CHILD_DOES_NOT_BREAK_ALIGNMENT) { if (n.getBreaksAlignment()) return CHILD_BREAKS_ALIGNMENT; else return CHILD_DOES_NOT_BREAK_ALIGNMENT; } else if (ret == MRCHILD_NOT_FOUND || ret == CHILD_BREAKS_ALIGNMENT || ret == MR_CHILD_FOUND_BREAKS_ALIGNMENT) return ret; else throw new RuntimeException( "Something wrong in getChildAlignment()."); } } return MRCHILD_NOT_FOUND; } @SuppressWarnings("unchecked") private boolean hasChildNode(N node, Vector<N> nodes) { for (int i = 0; i < node.getInputs().size(); i++) { N n = (N) node.getInputs().get(i); if (nodes.contains(n)) { return true; } else { if (hasChildNode(n, nodes)) return true; } } return false; } @SuppressWarnings("unchecked") private boolean hasParentNode(N node, Vector<N> childNodes) { for (int i = 0; i < node.getOutputs().size(); i++) { N n = (N) node.getOutputs().get(i); if (childNodes.contains(n)) { return true; } else { if (hasParentNode(n, childNodes)) return true; } } return false; } }
package org.eclipse.persistence.testing.tests.jpa.fieldaccess.advanced; import java.util.HashMap; import java.util.Vector; import junit.framework.*; import javax.persistence.EntityManager; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.expressions.Expression; import org.eclipse.persistence.expressions.ExpressionBuilder; import org.eclipse.persistence.expressions.ExpressionMath; import org.eclipse.persistence.queries.DeleteAllQuery; import org.eclipse.persistence.queries.UpdateAllQuery; import org.eclipse.persistence.sessions.DatabaseSession; import org.eclipse.persistence.sessions.UnitOfWork; import org.eclipse.persistence.testing.framework.junit.JUnitTestCase; import org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.*; import org.eclipse.persistence.testing.framework.UpdateAllQueryTestHelper; public class UpdateAllQueryAdvancedJunitTest extends JUnitTestCase { static protected Class[] classes = {Employee.class, Address.class, PhoneNumber.class, Project.class}; static protected Vector[] objectVectors = {null, null, null, null}; static protected EmployeePopulator populator = new EmployeePopulator(); public UpdateAllQueryAdvancedJunitTest() { super(); } public UpdateAllQueryAdvancedJunitTest(String name) { super(name); } public void setUp() { clearCache("fieldaccess"); super.setUp(); if(!compare()) { clear(); populate(); } } protected static DatabaseSession getDbSession() { return getServerSession("fieldaccess"); } protected static UnitOfWork acquireUnitOfWork() { return getDbSession().acquireUnitOfWork(); } protected static void clear() { UnitOfWork uow = acquireUnitOfWork(); UpdateAllQuery updateEmployees = new UpdateAllQuery(Employee.class); updateEmployees.addUpdate("manager", null); updateEmployees.addUpdate("address", null); uow.executeQuery(updateEmployees); UpdateAllQuery updateProjects = new UpdateAllQuery(Project.class); updateProjects.addUpdate("teamLeader", null); uow.executeQuery(updateProjects); uow.executeQuery(new DeleteAllQuery(PhoneNumber.class)); uow.executeQuery(new DeleteAllQuery(Address.class)); uow.executeQuery(new DeleteAllQuery(Employee.class)); uow.executeQuery(new DeleteAllQuery(Project.class)); uow.commit(); clearCache("fieldaccess"); } protected static void populate() { populator.buildExamples(); populator.persistExample(getDbSession()); clearCache("fieldaccess"); for(int i=0; i < classes.length; i++) { objectVectors[i] = getDbSession().readAllObjects(classes[i]); } clearCache("fieldaccess"); } public static Test suite() { TestSuite suite = new TestSuite(); suite.setName("UpdateAllQueryAdvancedJunitTest (fieldaccess)"); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testSetup")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testFirstNamePrefixBLAForAll")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testFirstNamePrefixBLAForSalary")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testDoubleSalaryForAll")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testDoubleSalaryForSalary")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testFirstNamePrefixBLADoubleSalaryForAll")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testFirstNamePrefixBLADoubleSalaryForSalary")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testFirstNamePrefixBLADoubleSalaryForSalaryForFirstName")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testAssignManagerName")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testAssignNullToAddress")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testAssignObjectToAddress")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testAssignExpressionToAddress")); suite.addTest(new UpdateAllQueryAdvancedJunitTest("testAggregate")); return suite; } /** * The setup is done as a test, both to record its failure, and to allow execution in the server. */ public void testSetup() { new AdvancedTableCreator().replaceTables(JUnitTestCase.getServerSession("fieldaccess")); clearCache("fieldaccess"); } public void testFirstNamePrefixBLAForAll() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ ExpressionBuilder builder = new ExpressionBuilder(); UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class); updateQuery.addUpdate("firstName", Expression.fromLiteral("'BLA'", null).concat(builder.get("firstName"))); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } public void testFirstNamePrefixBLAForSalary() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ ExpressionBuilder builder = new ExpressionBuilder(); Expression selectionExpression = builder.get("salary").lessThan(20000); UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class, selectionExpression); updateQuery.addUpdate("firstName", Expression.fromLiteral("'BLA'", null).concat(builder.get("firstName"))); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } public void testDoubleSalaryForAll() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ ExpressionBuilder builder = new ExpressionBuilder(); UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class); updateQuery.addUpdate("salary", ExpressionMath.multiply(builder.get("salary"), new Integer(2))); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } public void testDoubleSalaryForSalary() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ ExpressionBuilder builder = new ExpressionBuilder(); Expression selectionExpression = builder.get("salary").lessThan(20000); UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class, selectionExpression); updateQuery.addUpdate("salary", ExpressionMath.multiply(builder.get("salary"), new Integer(2))); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } public void testFirstNamePrefixBLADoubleSalaryForAll() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ ExpressionBuilder builder = new ExpressionBuilder(); UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class); updateQuery.addUpdate("firstName", Expression.fromLiteral("'BLA'", null).concat(builder.get("firstName"))); updateQuery.addUpdate("salary", ExpressionMath.multiply(builder.get("salary"), new Integer(2))); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } public void testFirstNamePrefixBLADoubleSalaryForSalary() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ ExpressionBuilder builder = new ExpressionBuilder(); Expression selectionExpression = builder.get("salary").lessThan(20000); UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class, selectionExpression); updateQuery.addUpdate("firstName", Expression.fromLiteral("'BLA'", null).concat(builder.get("firstName"))); updateQuery.addUpdate("salary", ExpressionMath.multiply(builder.get("salary"), new Integer(2))); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } public void testFirstNamePrefixBLADoubleSalaryForSalaryForFirstName() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ ExpressionBuilder builder = new ExpressionBuilder(); Expression selectionExpression = builder.get("salary").lessThan(20000).and(builder.get("firstName").like("J%")); UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class, selectionExpression); updateQuery.addUpdate("firstName", Expression.fromLiteral("'BLA'", null).concat(builder.get("firstName"))); updateQuery.addUpdate("salary", ExpressionMath.multiply(builder.get("salary"), new Integer(2))); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } public void testAssignManagerName() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ ExpressionBuilder builder = new ExpressionBuilder(); Expression selectionExpression = builder.get("manager").notNull(); UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class, selectionExpression); updateQuery.addUpdate("firstName", builder.get("manager").get("firstName")); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } public void testAssignNullToAddress() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class); updateQuery.addUpdate("address", null); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } public void testAssignObjectToAddress() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ Address address = new Address(); address.setCountry("Canada"); address.setProvince("Ontario"); address.setCity("Ottawa"); address.setStreet("O'Connor"); UnitOfWork uow = acquireUnitOfWork(); uow.registerNewObject(address); uow.commit(); UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class); updateQuery.addUpdate("address", address); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } public void testAssignExpressionToAddress() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ ExpressionBuilder builder = new ExpressionBuilder(); Expression selectionExpression = builder.get("manager").notNull(); UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class, selectionExpression); updateQuery.addUpdate("address", builder.get("manager").get("address")); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } public void testAggregate() { EntityManager em = createEntityManager("fieldaccess"); beginTransaction(em); try{ ExpressionBuilder builder = new ExpressionBuilder(); Expression selectionExpression = builder.get("manager").notNull(); UpdateAllQuery updateQuery = new UpdateAllQuery(Employee.class, selectionExpression); updateQuery.addUpdate(builder.get("period").get("startDate"), builder.get("period").get("endDate")); updateQuery.addUpdate(builder.get("period").get("endDate"), builder.get("period").get("startDate")); updateAllQueryInternal(updateQuery); }finally{ if (isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } } protected static void updateAllQueryInternal(Class referenceClass, HashMap updateClauses, Expression selectionExpression) { String errorMsg = UpdateAllQueryTestHelper.execute(getDbSession(), referenceClass, updateClauses, selectionExpression); if(errorMsg != null) { fail(errorMsg); } } protected static void updateAllQueryInternal(UpdateAllQuery uq) { String errorMsg = UpdateAllQueryTestHelper.execute(getDbSession(), uq); if(errorMsg != null) { fail(errorMsg); } } protected static boolean compare() { for(int i=0; i < classes.length; i++) { if(!compare(i)) { return false; } } return true; } protected static boolean compare(int i) { if(objectVectors[i] == null) { return false; } Vector currentVector = getDbSession().readAllObjects(classes[i]); if(currentVector.size() != objectVectors[i].size()) { return false; } ClassDescriptor descriptor = getDbSession().getDescriptor(classes[i]); for(int j=0; j < currentVector.size(); j++) { Object obj1 = objectVectors[i].elementAt(j); Object obj2 = currentVector.elementAt(j); if(!descriptor.getObjectBuilder().compareObjects(obj1, obj2, (org.eclipse.persistence.internal.sessions.AbstractSession)getDbSession())) { return false; } } return true; } }
package org.safehaus.subutai.core.env.impl; import java.sql.SQLException; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import org.safehaus.subutai.common.dao.DaoManager; import org.safehaus.subutai.common.peer.ContainerHost; import org.safehaus.subutai.common.peer.PeerException; import org.safehaus.subutai.core.env.api.Environment; import org.safehaus.subutai.core.env.api.EnvironmentManager; import org.safehaus.subutai.core.env.api.EnvironmentStatus; import org.safehaus.subutai.core.env.api.build.Blueprint; import org.safehaus.subutai.core.env.api.build.Topology; import org.safehaus.subutai.core.env.api.exception.ContainerHostNotFoundException; import org.safehaus.subutai.core.env.api.exception.EnvironmentCreationException; import org.safehaus.subutai.core.env.api.exception.EnvironmentDestructionException; import org.safehaus.subutai.core.env.api.exception.EnvironmentManagerException; import org.safehaus.subutai.core.env.api.exception.EnvironmentModificationException; import org.safehaus.subutai.core.env.api.exception.EnvironmentNotFoundException; import org.safehaus.subutai.core.env.impl.builder.TopologyBuilder; import org.safehaus.subutai.core.env.impl.dao.BlueprintDataService; import org.safehaus.subutai.core.env.impl.dao.EnvironmentContainerDataService; import org.safehaus.subutai.core.env.impl.dao.EnvironmentDataService; import org.safehaus.subutai.core.env.impl.entity.EnvironmentContainerImpl; import org.safehaus.subutai.core.env.impl.entity.EnvironmentImpl; import org.safehaus.subutai.core.env.impl.exception.EnvironmentBuildException; import org.safehaus.subutai.core.env.impl.exception.ResultHolder; import org.safehaus.subutai.core.network.api.NetworkManager; import org.safehaus.subutai.core.network.api.NetworkManagerException; import org.safehaus.subutai.core.peer.api.PeerManager; import org.safehaus.subutai.core.registry.api.TemplateRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** * Environment manager implementation */ public class EnvironmentManagerImpl implements EnvironmentManager { private static final Logger LOG = LoggerFactory.getLogger( EnvironmentManagerImpl.class.getName() ); private final PeerManager peerManager; private final NetworkManager networkManager; private final TopologyBuilder topologyBuilder; private final ExecutorService executor = Executors.newCachedThreadPool();
package org.mifosplatform.accounting.producttoaccountmapping.service; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.mifosplatform.accounting.common.AccountingConstants.CASH_ACCOUNTS_FOR_LOAN; import org.mifosplatform.accounting.common.AccountingConstants.LOAN_PRODUCT_ACCOUNTING_PARAMS; import org.mifosplatform.accounting.glaccount.domain.GLAccount; import org.mifosplatform.accounting.glaccount.domain.GLAccountRepository; import org.mifosplatform.accounting.glaccount.domain.GLAccountRepositoryWrapper; import org.mifosplatform.accounting.glaccount.domain.GLAccountType; import org.mifosplatform.accounting.producttoaccountmapping.domain.PortfolioProductType; import org.mifosplatform.accounting.producttoaccountmapping.domain.ProductToGLAccountMapping; import org.mifosplatform.accounting.producttoaccountmapping.domain.ProductToGLAccountMappingRepository; import org.mifosplatform.accounting.producttoaccountmapping.exception.ProductToGLAccountMappingInvalidException; import org.mifosplatform.accounting.producttoaccountmapping.exception.ProductToGLAccountMappingNotFoundException; import org.mifosplatform.infrastructure.codes.domain.CodeValue; import org.mifosplatform.infrastructure.codes.domain.CodeValueRepositoryWrapper; import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper; import org.mifosplatform.portfolio.charge.domain.Charge; import org.mifosplatform.portfolio.charge.domain.ChargeRepositoryWrapper; import org.mifosplatform.portfolio.paymentdetail.PaymentDetailConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @Component public class ProductToGLAccountMappingHelper { protected final GLAccountRepository accountRepository; protected final GLAccountRepositoryWrapper accountRepositoryWrapper; protected final ProductToGLAccountMappingRepository accountMappingRepository; protected final FromJsonHelper fromApiJsonHelper; private final CodeValueRepositoryWrapper codeValueRepositoryWrapper; private final ChargeRepositoryWrapper chargeRepositoryWrapper; @Autowired public ProductToGLAccountMappingHelper(final GLAccountRepository glAccountRepository, final ProductToGLAccountMappingRepository glAccountMappingRepository, final FromJsonHelper fromApiJsonHelper, final CodeValueRepositoryWrapper codeValueRepositoryWrapper, final ChargeRepositoryWrapper chargeRepositoryWrapper, final GLAccountRepositoryWrapper accountRepositoryWrapper) { this.accountRepository = glAccountRepository; this.accountMappingRepository = glAccountMappingRepository; this.fromApiJsonHelper = fromApiJsonHelper; this.codeValueRepositoryWrapper = codeValueRepositoryWrapper; this.chargeRepositoryWrapper = chargeRepositoryWrapper; this.accountRepositoryWrapper = accountRepositoryWrapper; } public void saveProductToAccountMapping(final JsonElement element, final String paramName, final Long productId, final int placeHolderTypeId, final GLAccountType expectedAccountType, final PortfolioProductType portfolioProductType) { final Long accountId = this.fromApiJsonHelper.extractLongNamed(paramName, element); final GLAccount glAccount = getAccountByIdAndType(paramName, expectedAccountType, accountId); final ProductToGLAccountMapping accountMapping = new ProductToGLAccountMapping(glAccount, productId, portfolioProductType.getValue(), placeHolderTypeId); this.accountMappingRepository.save(accountMapping); } public void mergeProductToAccountMappingChanges(final JsonElement element, final String paramName, final Long productId, final int accountTypeId, final String accountTypeName, final Map<String, Object> changes, final GLAccountType expectedAccountType, final PortfolioProductType portfolioProductType) { final Long accountId = this.fromApiJsonHelper.extractLongNamed(paramName, element); // get the existing product if (accountId != null) { final ProductToGLAccountMapping accountMapping = this.accountMappingRepository.findCoreProductToFinAccountMapping(productId, portfolioProductType.getValue(), accountTypeId); if (accountMapping == null) { throw new ProductToGLAccountMappingNotFoundException(portfolioProductType, productId, accountTypeName); } if (accountMapping.getGlAccount().getId() != accountId) { final GLAccount glAccount = getAccountByIdAndType(paramName, expectedAccountType, accountId); changes.put(paramName, accountId); accountMapping.setGlAccount(glAccount); this.accountMappingRepository.save(accountMapping); } } } /** * Saves the payment type to Fund source mappings for a particular * product/product type (also populates the changes array if passed in) * * @param command * @param element * @param productId * @param changes */ public void savePaymentChannelToFundSourceMappings(final JsonCommand command, final JsonElement element, final Long productId, final Map<String, Object> changes, final PortfolioProductType portfolioProductType) { final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); if (paymentChannelMappingArray != null) { if (changes != null) { changes.put(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), command.jsonFragment(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue())); } for (int i = 0; i < paymentChannelMappingArray.size(); i++) { final JsonObject jsonObject = paymentChannelMappingArray.get(i).getAsJsonObject(); final Long paymentTypeId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_TYPE.getValue()).getAsLong(); final Long paymentSpecificFundAccountId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).getAsLong(); savePaymentChannelToFundSourceMapping(productId, paymentTypeId, paymentSpecificFundAccountId, portfolioProductType); } } } /** * Saves the Charge to Income / Liability account mappings for a particular * product/product type (also populates the changes array if passed in) * * @param command * @param element * @param productId * @param changes */ public void saveChargesToIncomeOrLiabilityAccountMappings(final JsonCommand command, final JsonElement element, final Long productId, final Map<String, Object> changes, final PortfolioProductType portfolioProductType, final boolean isPenalty) { String arrayName; if (isPenalty) { arrayName = LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(); } else { arrayName = LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(); } final JsonArray chargeToIncomeAccountMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed(arrayName, element); if (chargeToIncomeAccountMappingArray != null) { if (changes != null) { changes.put(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(), command.jsonFragment(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue())); } for (int i = 0; i < chargeToIncomeAccountMappingArray.size(); i++) { final JsonObject jsonObject = chargeToIncomeAccountMappingArray.get(i).getAsJsonObject(); final Long chargeId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.CHARGE_ID.getValue()).getAsLong(); final Long incomeAccountId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue()).getAsLong(); saveChargeToFundSourceMapping(productId, chargeId, incomeAccountId, portfolioProductType, isPenalty); } } } /** * @param command * @param element * @param productId * @param changes */ public void updateChargeToIncomeAccountMappings(final JsonCommand command, final JsonElement element, final Long productId, final Map<String, Object> changes, final PortfolioProductType portfolioProductType, final boolean isPenalty) { // find all existing payment Channel to Fund source Mappings List<ProductToGLAccountMapping> existingChargeToIncomeAccountMappings; String arrayFragmentName; if (isPenalty) { existingChargeToIncomeAccountMappings = this.accountMappingRepository.findAllPenaltyToIncomeAccountMappings(productId, portfolioProductType.getValue()); arrayFragmentName = LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(); } else { existingChargeToIncomeAccountMappings = this.accountMappingRepository.findAllFeeToIncomeAccountMappings(productId, portfolioProductType.getValue()); arrayFragmentName = LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(); } final JsonArray chargeToIncomeAccountMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed(arrayFragmentName, element); /** * Variable stores a map representation of charges (key) and their * associated income Id's (value) extracted from the passed in * Jsoncommand **/ final Map<Long, Long> inputChargeToIncomeAccountMap = new HashMap<>(); /*** * Variable stores all charges which have already been mapped to Income * Accounts in the system **/ final Set<Long> existingCharges = new HashSet<>(); if (chargeToIncomeAccountMappingArray != null) { if (changes != null) { changes.put(arrayFragmentName, command.jsonFragment(arrayFragmentName)); } for (int i = 0; i < chargeToIncomeAccountMappingArray.size(); i++) { final JsonObject jsonObject = chargeToIncomeAccountMappingArray.get(i).getAsJsonObject(); final Long chargeId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.CHARGE_ID.getValue()).getAsLong(); final Long incomeAccountId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue()).getAsLong(); inputChargeToIncomeAccountMap.put(chargeId, incomeAccountId); } // If input map is empty, delete all existing mappings if (inputChargeToIncomeAccountMap.size() == 0) { this.accountMappingRepository.deleteInBatch(existingChargeToIncomeAccountMappings); }/** * Else, <br/> * update existing mappings OR <br/> * delete old mappings (which are already present, but not passed in * as a part of Jsoncommand)<br/> * Create new mappings for charges that are passed in as a part of * the Jsoncommand but not already present * **/ else { for (final ProductToGLAccountMapping chargeToIncomeAccountMapping : existingChargeToIncomeAccountMappings) { final Long currentCharge = chargeToIncomeAccountMapping.getCharge().getId(); existingCharges.add(currentCharge); // update existing mappings (if required) if (inputChargeToIncomeAccountMap.containsKey(currentCharge)) { final Long newGLAccountId = inputChargeToIncomeAccountMap.get(currentCharge); if (newGLAccountId != chargeToIncomeAccountMapping.getGlAccount().getId()) { final GLAccount glAccount; if (isPenalty) { glAccount = getAccountByIdAndType(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue(), GLAccountType.INCOME, newGLAccountId); } else { List<GLAccountType> allowedAccountTypes = getAllowedAccountTypesForFeeMapping(); glAccount = getAccountByIdAndType(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue(), allowedAccountTypes, newGLAccountId); } chargeToIncomeAccountMapping.setGlAccount(glAccount); this.accountMappingRepository.save(chargeToIncomeAccountMapping); } }// deleted payment type else { this.accountMappingRepository.delete(chargeToIncomeAccountMapping); } } // create new mappings final Set<Long> incomingCharges = inputChargeToIncomeAccountMap.keySet(); incomingCharges.removeAll(existingCharges); // incomingPaymentTypes now only contains the newly added // payment Type mappings for (final Long newCharge : incomingCharges) { final Long newGLAccountId = inputChargeToIncomeAccountMap.get(newCharge); saveChargeToFundSourceMapping(productId, newCharge, newGLAccountId, portfolioProductType, isPenalty); } } } } /** * @param command * @param element * @param productId * @param changes */ public void updatePaymentChannelToFundSourceMappings(final JsonCommand command, final JsonElement element, final Long productId, final Map<String, Object> changes, final PortfolioProductType portfolioProductType) { // find all existing payment Channel to Fund source Mappings final List<ProductToGLAccountMapping> existingPaymentChannelToFundSourceMappings = this.accountMappingRepository .findAllPaymentTypeToFundSourceMappings(productId, portfolioProductType.getValue()); final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); /** * Variable stores a map representation of Payment channels (key) and * their fund sources (value) extracted from the passed in Jsoncommand **/ final Map<Long, Long> inputPaymentChannelFundSourceMap = new HashMap<>(); /*** * Variable stores all payment types which have already been mapped to * Fund Sources in the system **/ final Set<Long> existingPaymentTypes = new HashSet<>(); if (paymentChannelMappingArray != null && paymentChannelMappingArray.size() > 0) { if (changes != null) { changes.put(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), command.jsonFragment(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue())); } for (int i = 0; i < paymentChannelMappingArray.size(); i++) { final JsonObject jsonObject = paymentChannelMappingArray.get(i).getAsJsonObject(); final Long paymentTypeId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_TYPE.getValue()).getAsLong(); final Long paymentSpecificFundAccountId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).getAsLong(); inputPaymentChannelFundSourceMap.put(paymentTypeId, paymentSpecificFundAccountId); } // If input map is empty, delete all existing mappings if (inputPaymentChannelFundSourceMap.size() == 0) { this.accountMappingRepository.deleteInBatch(existingPaymentChannelToFundSourceMappings); }/** * Else, <br/> * update existing mappings OR <br/> * delete old mappings (which re already present, but not passed in * as a part of Jsoncommand)<br/> * Create new mappings for payment types that are passed in as a * part of the Jsoncommand but not already present * **/ else { for (final ProductToGLAccountMapping existingPaymentChannelToFundSourceMapping : existingPaymentChannelToFundSourceMappings) { final Long currentPaymentChannelId = existingPaymentChannelToFundSourceMapping.getPaymentType().getId(); existingPaymentTypes.add(currentPaymentChannelId); // update existing mappings (if required) if (inputPaymentChannelFundSourceMap.containsKey(currentPaymentChannelId)) { final Long newGLAccountId = inputPaymentChannelFundSourceMap.get(currentPaymentChannelId); if (newGLAccountId != existingPaymentChannelToFundSourceMapping.getGlAccount().getId()) { final GLAccount glAccount = getAccountByIdAndType(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), GLAccountType.ASSET, newGLAccountId); existingPaymentChannelToFundSourceMapping.setGlAccount(glAccount); this.accountMappingRepository.save(existingPaymentChannelToFundSourceMapping); } }// deleted payment type else { this.accountMappingRepository.delete(existingPaymentChannelToFundSourceMapping); } } // create new mappings final Set<Long> incomingPaymentTypes = inputPaymentChannelFundSourceMap.keySet(); incomingPaymentTypes.removeAll(existingPaymentTypes); // incomingPaymentTypes now only contains the newly added // payment Type mappings for (final Long newPaymentType : incomingPaymentTypes) { final Long newGLAccountId = inputPaymentChannelFundSourceMap.get(newPaymentType); savePaymentChannelToFundSourceMapping(productId, newPaymentType, newGLAccountId, portfolioProductType); } } } } /** * @param productId * @param jsonObject */ private void savePaymentChannelToFundSourceMapping(final Long productId, final Long paymentTypeId, final Long paymentTypeSpecificFundAccountId, final PortfolioProductType portfolioProductType) { final CodeValue paymentType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( PaymentDetailConstants.paymentTypeCodeName, paymentTypeId); final GLAccount glAccount = getAccountByIdAndType(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), GLAccountType.ASSET, paymentTypeSpecificFundAccountId); final ProductToGLAccountMapping accountMapping = new ProductToGLAccountMapping(glAccount, productId, portfolioProductType.getValue(), CASH_ACCOUNTS_FOR_LOAN.FUND_SOURCE.getValue(), paymentType); this.accountMappingRepository.save(accountMapping); } /** * @param productId * @param jsonObject */ private void saveChargeToFundSourceMapping(final Long productId, final Long chargeId, final Long incomeAccountId, final PortfolioProductType portfolioProductType, final boolean isPenalty) { final Charge charge = this.chargeRepositoryWrapper.findOneWithNotFoundDetection(chargeId); // TODO Vishwas: Need to validate if given charge is fee or Penalty // based on input condition GLAccount glAccount; /** * Both CASH and Accrual placeholders have the same value for income * from Interest and penalties **/ CASH_ACCOUNTS_FOR_LOAN placeHolderAccountType; if (isPenalty) { glAccount = getAccountByIdAndType(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue(), GLAccountType.INCOME, incomeAccountId); placeHolderAccountType = CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_PENALTIES; } else { List<GLAccountType> allowedAccountTypes = getAllowedAccountTypesForFeeMapping(); glAccount = getAccountByIdAndType(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue(), allowedAccountTypes, incomeAccountId); placeHolderAccountType = CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_FEES; } final ProductToGLAccountMapping accountMapping = new ProductToGLAccountMapping(glAccount, productId, portfolioProductType.getValue(), placeHolderAccountType.getValue(), charge); this.accountMappingRepository.save(accountMapping); } private List<GLAccountType> getAllowedAccountTypesForFeeMapping() { List<GLAccountType> allowedAccountTypes = new ArrayList<>(); allowedAccountTypes.add(GLAccountType.INCOME); allowedAccountTypes.add(GLAccountType.LIABILITY); return allowedAccountTypes; } /** * Fetches account with a particular Id and throws and Exception it is not * of the expected Account Category ('ASSET','liability' etc) * * @param paramName * @param expectedAccountType * @param accountId * @return */ public GLAccount getAccountByIdAndType(final String paramName, final GLAccountType expectedAccountType, final Long accountId) { final GLAccount glAccount = this.accountRepositoryWrapper.findOneWithNotFoundDetection(accountId); // validate account is of the expected Type if (glAccount.getType().intValue() != expectedAccountType.getValue()) { throw new ProductToGLAccountMappingInvalidException( paramName, glAccount.getName(), accountId, GLAccountType.fromInt(glAccount.getType()).toString(), expectedAccountType.toString()); } return glAccount; } public GLAccount getAccountByIdAndType(final String paramName, final List<GLAccountType> expectedAccountTypes, final Long accountId) { final GLAccount glAccount = this.accountRepositoryWrapper.findOneWithNotFoundDetection(accountId); // validate account is of the expected Type List<Integer> glAccountTypeValues = new ArrayList<>(); for (GLAccountType glAccountType : expectedAccountTypes) { glAccountTypeValues.add(glAccountType.getValue()); } if (!glAccountTypeValues.contains(glAccount.getType())) { throw new ProductToGLAccountMappingInvalidException(paramName, glAccount.getName(), accountId, GLAccountType.fromInt(glAccount.getType()).toString(), glAccountTypeValues.toString()); } return glAccount; } public void deleteProductToGLAccountMapping(final Long loanProductId, final PortfolioProductType portfolioProductType) { final List<ProductToGLAccountMapping> productToGLAccountMappings = this.accountMappingRepository.findByProductIdAndProductType( loanProductId, portfolioProductType.getValue()); if (productToGLAccountMappings != null && productToGLAccountMappings.size() > 0) { this.accountMappingRepository.deleteInBatch(productToGLAccountMappings); } } }
package org.wso2.am.integration.tests.other; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpStatus; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.testng.annotations.AfterClass; import org.wso2.am.integration.clients.admin.ApiException; import org.wso2.am.integration.clients.admin.ApiResponse; import org.wso2.am.integration.clients.admin.api.dto.BlockingConditionDTO; import org.wso2.am.integration.clients.admin.api.dto.BlockingConditionStatusDTO; import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO; import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO; import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO; import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants; import org.wso2.am.integration.test.utils.bean.APIRequest; import org.wso2.am.integration.tests.api.lifecycle.APIManagerLifecycleBaseTest; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.HashMap; public class APIDenyPolicyTestCase extends APIManagerLifecycleBaseTest { private final Log log = LogFactory.getLog(APIDenyPolicyTestCase.class); private BlockingConditionDTO blockingConditionDTO; private List<String> addedPolicyIds = new ArrayList<>(); private ArrayList<String> grantTypes; private String invokingAPIId; @Factory(dataProvider = "userModeDataProvider") public APIDenyPolicyTestCase(TestUserMode userMode) { this.userMode = userMode; } @DataProvider public static Object[][] userModeDataProvider() { return new Object[][]{new Object[]{TestUserMode.SUPER_TENANT_ADMIN}, new Object[]{TestUserMode.SUPER_TENANT_EMAIL_USER}}; } @BeforeClass(alwaysRun = true) public void setEnvironment() throws Exception { super.init(userMode); grantTypes = new ArrayList<>(); grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.PASSWORD); grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL); } //api context test case @Test(groups = {"wso2.am"}, description = "Test add API deny policy") public void testAddAPIDenyPolicy() throws Exception { //Add API String apiName = "DenyPolicyTestAPI"; String apiContext = "deny"; String apiVersion = "1.0"; String url = getGatewayURLHttp() + "jaxrs_basic/services/customers/customerservice"; APIRequest apiRequest = new APIRequest(apiName, apiContext, new URL(url)); apiRequest.setVersion(apiVersion); apiRequest.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED); apiRequest.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED); apiRequest.setProvider(user.getUserName()); //Add the API using the API publisher. HttpResponse postResponse = restAPIPublisher.addAPI(apiRequest); String apiId = postResponse.getData(); waitForAPIDeployment(); //create Deny Policy boolean conditionStatus = true; Object conditionValue = "/deny/1.0"; blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(conditionValue); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.API); ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED); BlockingConditionDTO addedBlockingConditionDTO = addedPolicy.getData(); String policyId = addedBlockingConditionDTO.getConditionId(); Assert.assertNotNull(policyId, "The deny policy ID cannot be null or empty"); blockingConditionDTO.setConditionId(policyId); } @Test(groups = {"wso2.am"}, description = "Test get API deny policy", dependsOnMethods = "testAddAPIDenyPolicy") public void testGetAddedDenyPolicy() throws ApiException { ApiResponse<BlockingConditionDTO> response = restAPIAdmin.getDenyThrottlingPolicy(blockingConditionDTO.getConditionId()); String retrievedConditionId = response.getData().getConditionId(); Assert.assertEquals(blockingConditionDTO.getConditionId(), retrievedConditionId); } @Test(groups = {"wso2.am"}, description = "Test add API deny policy with non existing context", dependsOnMethods = "testGetAddedDenyPolicy") public void testAddDenyPolicyWithNonExistingContext() { //create Deny Policy boolean conditionStatus = true; Object conditionValue = "/denyNonExisting/1.0.0/"; BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(conditionValue); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.API); try { ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); } catch (ApiException e) { Assert.assertEquals(e.getCode(), HttpStatus.SC_INTERNAL_SERVER_ERROR); Assert.assertTrue(e.getResponseBody().contains("Couldn't Save Block Condition Due to Invalid API Context /denyNonExisting/1.0.0/")); } } @Test(groups = {"wso2.am"}, description = "Test add API deny policy with the same name", dependsOnMethods = "testAddDenyPolicyWithNonExistingContext") public void testAddAPIDenyPolicyWithTheSameContext() { //create Deny Policy boolean conditionStatus = true; Object conditionValue = "/deny/1.0"; BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(conditionValue); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.API); try { ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED, "Duplicated Context Deny Policy Added"); } catch (ApiException e) { Assert.assertEquals(e.getCode(), HttpStatus.SC_CONFLICT); Assert.assertTrue(e.getResponseBody().contains("A black list item with type: API, value: /deny/1.0 already exists")); } } @Test(groups = {"wso2.am"}, description = "Test update API deny policy", dependsOnMethods = "testAddAPIDenyPolicyWithTheSameContext") public void testUpdateAPIDenyPolicyStatus() throws ApiException { String denyPolicyId = blockingConditionDTO.getConditionId(); String conditionType = blockingConditionDTO.getConditionType().toString(); boolean conditionStatus = false; BlockingConditionStatusDTO blockingConditionStatusDTO = new BlockingConditionStatusDTO(); blockingConditionStatusDTO.setConditionStatus(conditionStatus); blockingConditionStatusDTO.setConditionId(denyPolicyId); ApiResponse<BlockingConditionDTO> updatedCondition = restAPIAdmin.updateDenyThrottlingPolicy(denyPolicyId, conditionType, blockingConditionStatusDTO); Assert.assertEquals(updatedCondition.getStatusCode(), HttpStatus.SC_OK); BlockingConditionDTO updatedBlockedCondition = updatedCondition.getData(); Assert.assertEquals(updatedBlockedCondition.isConditionStatus().booleanValue(), conditionStatus); } @Test(groups = {"wso2.am"}, description = "Test delete API deny policy", dependsOnMethods = "testUpdateAPIDenyPolicyStatus") public void testDeleteAPIDenyPolicy() throws ApiException { String denyPolicyId = blockingConditionDTO.getConditionId(); ApiResponse<Void> response = restAPIAdmin.deleteDenyThrottlingPolicy(denyPolicyId); Assert.assertEquals(response.getStatusCode(), HttpStatus.SC_OK); } @Test(groups = {"wso2.am"}, description = "Test add API Application Vise deny policy", dependsOnMethods = "testDeleteAPIDenyPolicy") public void testAddAPIDenyPolicyApplicationVise() throws Exception { //create application String userName = user.getUserName(); HttpResponse applicationResponse = restAPIStore.createApplication("denyPolicyCheckApp", "Test Application", APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, ApplicationDTO.TokenTypeEnum.JWT); boolean conditionStatus = true; Object conditionValue = userName+":denyPolicyCheckApp"; BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(conditionValue); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.APPLICATION); ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED); BlockingConditionDTO addedBlockingConditionDTO = addedPolicy.getData(); String policyId = addedBlockingConditionDTO.getConditionId(); Assert.assertNotNull(policyId, "The deny policy ID cannot be null or empty"); restAPIAdmin.deleteDenyThrottlingPolicy(policyId); restAPIStore.deleteApplication(applicationResponse.getData()); } @Test(groups = {"wso2.am"}, description = "Test add API Deny Policy to Non Existing Application", dependsOnMethods = "testAddAPIDenyPolicyApplicationVise") public void testAddAPIDenyPolicyToNonExistingApplication() { String userName = user.getUserName(); boolean conditionStatus = true; Object conditionValue = userName+":NonExistingApp"; BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(conditionValue); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.APPLICATION); try { ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED, "Deny Policy Added without a non-existing application"); } catch (ApiException e) { Assert.assertEquals(e.getCode(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } } @Test(groups = {"wso2.am"}, description = "Test add API User Vise deny policy", dependsOnMethods = "testAddAPIDenyPolicyToNonExistingApplication") public void testAddAPIDenyPolicyUserVise() throws Exception { boolean conditionStatus = true; Object conditionValue = "admin"; BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(conditionValue); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.USER); ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED); BlockingConditionDTO addedBlockingConditionDTO = addedPolicy.getData(); String policyId = addedBlockingConditionDTO.getConditionId(); Assert.assertNotNull(policyId, "The deny policy ID cannot be null or empty"); restAPIAdmin.deleteDenyThrottlingPolicy(policyId); } @Test(groups = {"wso2.am"}, description = "Test add API Deny Policy to Invalid User", dependsOnMethods = "testAddAPIDenyPolicyUserVise") public void testAddAPIDenyPolicyWithInvalidUser() { boolean conditionStatus = true; Object conditionValue = "nonExistingAdmin"; BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(conditionValue); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.USER); try { ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED, "Deny Policy Added with an invalid IP"); } catch (ApiException e) { Assert.assertEquals(e.getCode(), HttpStatus.SC_CONFLICT); } } @Test(groups = {"wso2.am"}, description = "Test add API IP Address Vise deny policy", dependsOnMethods = "testAddAPIDenyPolicyWithInvalidUser") public void testAddAPIDenyPolicyIPAddressWise() throws Exception { boolean conditionStatus = true; Map<String, Object> valueMap = new LinkedHashMap<>(); valueMap.put("invert", false); valueMap.put("fixedIp", "127.0.0.1"); BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(valueMap); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.IP); ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED); BlockingConditionDTO addedBlockingConditionDTO = addedPolicy.getData(); String policyId = addedBlockingConditionDTO.getConditionId(); Assert.assertNotNull(policyId, "The deny policy ID cannot be null or empty"); restAPIAdmin.deleteDenyThrottlingPolicy(policyId); } @Test(groups = {"wso2.am"}, description = "Test add API deny policy with invalid IP Address", dependsOnMethods = "testAddAPIDenyPolicyIPAddressWise") public void testAddAPIDenyPolicyInvalidIPAddress() { boolean conditionStatus = true; Map<String, Object> valueMap = new LinkedHashMap<>(); valueMap.put("invert", false); valueMap.put("fixedIp", "127..0.0.1"); BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(valueMap); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.IP); try { ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED, "Deny Policy Added with an invalid IP"); } catch (ApiException e) { Assert.assertEquals(e.getCode(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } } @Test(groups = {"wso2.am"}, description = "Test add API IP Address Range Vise deny policy", dependsOnMethods = "testAddAPIDenyPolicyInvalidIPAddress") public void testAddAPIDenyPolicyIPRangeWise() throws Exception { boolean conditionStatus = true; Map<String, Object> valueMap = new LinkedHashMap<>(); valueMap.put("invert", false); valueMap.put("startingIp", "127.0.0.1"); valueMap.put("endingIp", "127.0.0.5"); BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(valueMap); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.IPRANGE); ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED); BlockingConditionDTO addedBlockingConditionDTO = addedPolicy.getData(); String policyId = addedBlockingConditionDTO.getConditionId(); Assert.assertNotNull(policyId, "The deny policy ID cannot be null or empty"); restAPIAdmin.deleteDenyThrottlingPolicy(policyId); } @Test(groups = {"wso2.am"}, description = "Test add API deny policy with invalid Ip Address range", dependsOnMethods = "testAddAPIDenyPolicyIPRangeWise") public void testAddAPIDenyPolicyInvalidIPAddressRange() { boolean conditionStatus = true; Map<String, Object> valueMap = new LinkedHashMap<>(); valueMap.put("startingIp", "127..0.0.1"); valueMap.put("endingIp", "127.0.0.5"); BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(valueMap); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.IP); try { ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED, "Deny Policy Added with an invalid IP"); } catch (ApiException e) { Assert.assertEquals(e.getCode(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } } @Test(groups = {"wso2.am"}, description = "Test add API deny policy with invalid Ip Address range", dependsOnMethods = "testAddAPIDenyPolicyInvalidIPAddressRange") public void testInvokeContextDeniedAPI() throws Exception { String API_NAME = "DenyInvokeTestAPI"; String API_CONTEXT = "DenyInvokeContext"; String API_END_POINT_METHOD = "/customers/123"; String API_VERSION_1_0_0 = "1.0.0"; String APPLICATION_NAME = "TestApplicationForCheckingDenyPolicy"; String apiEndPointUrl = backEndServerUrl.getWebAppURLHttp() + "am/sample/calculator/v1/api"; APIRequest apiRequest = new APIRequest(API_NAME, API_CONTEXT, new URL(apiEndPointUrl)); apiRequest.setVersion(API_VERSION_1_0_0); apiRequest.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED); apiRequest.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED); apiRequest.setProvider(publisherContext.getContextTenant().getContextUser().getUserName()); HttpResponse applicationResponse = restAPIStore.createApplication(APPLICATION_NAME, "Test Application", APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, ApplicationDTO.TokenTypeEnum.JWT); String applicationId = applicationResponse.getData(); invokingAPIId = createPublishAndSubscribeToAPIUsingRest(apiRequest, restAPIPublisher, restAPIStore, applicationId, APIMIntegrationConstants.API_TIER.UNLIMITED); //create Deny Policy boolean conditionStatus = true; Map<String, Object> valueMap = new LinkedHashMap<>(); valueMap.put("invert", false); valueMap.put("fixedIp", "127.0.0.1"); BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(valueMap); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.IP); ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); ApplicationKeyDTO applicationKeyDTO = restAPIStore .generateKeys(applicationId, "36000", null, ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes); Map<String, String> requestHeaders = new HashMap<String, String>(); requestHeaders.put("accept", "text/xml"); requestHeaders.put("Authorization", "Bearer " + applicationKeyDTO.getToken().getAccessToken()); waitForAPIDeploymentSync(apiRequest.getProvider(), apiRequest.getName(), apiRequest.getVersion(), APIMIntegrationConstants.IS_API_EXISTS); HttpResponse invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0), requestHeaders); Assert.assertEquals(invokeResponse.getResponseCode(), HttpStatus.SC_FORBIDDEN, "Response code mismatched when denied API was invoked"); restAPIAdmin.deleteDenyThrottlingPolicy(addedPolicy.getData().getConditionId()); restAPIStore.deleteApplication(applicationId); } @Test(groups = {"wso2.am"}, description = "Test add API deny policy with invalid Ip Address range", dependsOnMethods = "testInvokeContextDeniedAPI") public void testInvokeInverseContextDeniedAPI() throws Exception { String API_CONTEXT = "DenyInvokeContext"; String API_VERSION_1_0_0 = "1.0.0"; HttpResponse applicationResponse = restAPIStore.createApplication(APPLICATION_NAME, "Test Application Inverted", APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, ApplicationDTO.TokenTypeEnum.JWT); String applicationId = applicationResponse.getData(); HttpResponse inverseDenyPolicyApplicationResponse = subscribeToAPIUsingRest(invokingAPIId, applicationId, APIMIntegrationConstants.API_TIER.UNLIMITED, restAPIStore); boolean conditionStatus = true; Map<String, Object> valueMap = new LinkedHashMap<>(); valueMap.put("invert", true); valueMap.put("fixedIp", "127.0.0.1"); BlockingConditionDTO blockingConditionDTO = new BlockingConditionDTO(); blockingConditionDTO.setConditionStatus(conditionStatus); blockingConditionDTO.setConditionValue(valueMap); blockingConditionDTO.setConditionType(BlockingConditionDTO.ConditionTypeEnum.IP); ApiResponse<BlockingConditionDTO> addedPolicy = restAPIAdmin.addDenyThrottlingPolicy(blockingConditionDTO); ApplicationKeyDTO applicationKeyDTO = restAPIStore .generateKeys(applicationId, "36000", null, ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes); Map<String, String> requestHeaders = new HashMap<String, String>(); requestHeaders.put("accept", "text/xml"); requestHeaders.put("Authorization", "Bearer " + applicationKeyDTO.getToken().getAccessToken()); HttpResponse invokeResponse = HttpRequestUtil.doGet(getAPIInvocationURLHttps(API_CONTEXT, API_VERSION_1_0_0), requestHeaders); Assert.assertNotEquals(invokeResponse.getResponseCode(), HttpStatus.SC_FORBIDDEN, "Incorrect response code when inverted deny policy was invoked"); restAPIAdmin.deleteDenyThrottlingPolicy(addedPolicy.getData().getConditionId()); restAPIStore.deleteApplication(applicationId); } @AfterClass(alwaysRun = true) public void destroy() throws Exception { for (String conditionId : addedPolicyIds) { restAPIAdmin.deleteDenyThrottlingPolicy(conditionId); } super.cleanUp(); } }
package org.musicpd.android; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import org.a0z.mpd.MPD; import org.a0z.mpd.MPDOutput; import org.a0z.mpd.MPDStatus; import org.a0z.mpd.exception.MPDServerException; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.StrictMode; import android.preference.PreferenceManager; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.ListView; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.OnNavigationListener; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import org.musicpd.android.MPDActivities.MPDFragmentActivity; import org.musicpd.android.fragments.BrowseFragment; import org.musicpd.android.fragments.GestureFragment; import org.musicpd.android.fragments.MainPageFragment; import org.musicpd.android.fragments.NowPlayingFragment; import org.musicpd.android.fragments.PlaylistFragment; import org.musicpd.android.fragments.PlaylistFragmentCompat; import org.musicpd.android.helpers.MPDAsyncHelper.ConnectionListener; import org.musicpd.android.library.ILibraryFragmentActivity; import org.musicpd.android.library.LibraryTabActivity; import org.musicpd.android.tools.Job; import org.musicpd.android.tools.LibraryTabsUtil; import org.musicpd.android.tools.Log; import org.musicpd.android.tools.Tools; import org.musicpd.android.tools.Tuple3; public class MainMenuActivity extends MPDFragmentActivity implements OnNavigationListener, ILibraryFragmentActivity, GestureFragment.Listener { public static final int PLAYLIST = 1; public static final int ARTISTS = 2; public static final int SETTINGS = 5; public static final int STREAM = 6; public static final int LIBRARY = 7; public static final int CONNECT = 8; /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; private int backPressExitCount; private Handler exitCounterReset; private boolean isTablet; private boolean isDualPaneMode; ActionBar actionBar; ArrayAdapter<CharSequence> actionBarAdapter; List<String> tabs; public ConnectionListener persistentConnectionListener; ActionBarDrawerToggle drawerToggle; DrawerLayout drawer_layout; Context context; @SuppressLint("NewApi") @TargetApi(11) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final MPDApplication app = (MPDApplication) getApplication(); isTablet = app.isTabletUiEnabled(); setContentView(isTablet? R.layout.main_activity_tablet : R.layout.main_activity); isDualPaneMode = (findViewById(R.id.playlist_fragment) != null); exitCounterReset = new Handler(); if (android.os.Build.VERSION.SDK_INT >= 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } // Create the adapter that will return a fragment for each of the three primary sections // of the app. context = getApplicationContext(); tabs = LibraryTabsUtil.getCurrentLibraryTabs(context); mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the action bar. actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); setTitle(R.string.nowPlaying); actionBarAdapter = new ArrayAdapter<CharSequence>(getSupportActionBar().getThemedContext(), R.layout.sherlock_spinner_item); actionBarAdapter.add(LibraryTabsUtil.getTabTitle(context, tabs.get(0)).getString(context)); actionBarAdapter.add(getString(R.string.nowPlaying)); actionBarAdapter.add(getString(R.string.playQueue)); if(Build.VERSION.SDK_INT >= 14) { //Bug on ICS with sherlock's layout actionBarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } else { actionBarAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item); } actionBar.setListNavigationCallbacks(actionBarAdapter, this); if (actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_STANDARD) actionBar.setTitle(actionBarAdapter.getItem(1)); else actionBar.setSelectedNavigationItem(1); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setOffscreenPageLimit(3); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setCurrentItem(1, false); if (android.os.Build.VERSION.SDK_INT >= 9) mViewPager.setOverScrollMode(View.OVER_SCROLL_NEVER); mViewPager.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Object item = mSectionsPagerAdapter.getPrimaryItem(); if (item instanceof GestureFragment) { ((GestureFragment)item).setGestureFragmentListener(MainMenuActivity.this); ((GestureFragment)item).onTouchEvent(v, event); } return false; } }); // When swiping between different sections, select the corresponding tab. // We can also use ActionBar.Tab#select() to do this if we have a reference to the // Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { supportInvalidateOptionsMenu(); if (actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_STANDARD) actionBar.setTitle(actionBarAdapter.getItem(position)); else actionBar.setSelectedNavigationItem(position); } }); drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout); drawer_layout.setDrawerListener(drawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ drawer_layout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ )); final List<String> tabNames = new ArrayList<String>(tabs.size()); for (String tab : tabs) tabNames.add(LibraryTabsUtil.getTabTitle(context, tab).getString(context)); final ListView left_library = (ListView) findViewById(R.id.left_library); left_library.setAdapter(new ArrayAdapter<String>(this, R.layout.simple_list_item_1, tabNames)); left_library.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { MainMenuActivity.this.replaceLibraryFragment(tabs.get(position), tabNames.get(position)); drawer_layout.closeDrawers(); mViewPager.setCurrentItem(0, true); } }); setListViewHeightBasedOnChildren(left_library, true); final ListView left_outputs = (ListView) findViewById(R.id.left_outputs); final List<MPDOutput> outputs = new ArrayList<MPDOutput>(); final ArrayAdapter<MPDOutput> outputs_adapter = new ArrayAdapter<MPDOutput>(this, android.R.layout.simple_list_item_multiple_choice, outputs); left_outputs.setAdapter(outputs_adapter); app.oMPDAsyncHelper.addConnectionListener(persistentConnectionListener = new ConnectionListener() { @Override public void connectionFailed(String message) { } @Override public void connectionSucceeded(String message) { try { Log.i("Fetching outputs following connectionSucceeded"); final Collection<MPDOutput> o = app.oMPDAsyncHelper.oMPD.getOutputs(); Iterator<MPDOutput> i = o.iterator(); while (i.hasNext()) if ("quiet".equalsIgnoreCase(i.next().getName())) i.remove(); left_outputs.post(new Runnable() { @Override public void run() { outputs.clear(); outputs.addAll(o); outputs_adapter.notifyDataSetChanged(); setListViewHeightBasedOnChildren(left_outputs, false); } }); } catch (MPDServerException e) { Log.w(e); } } }); Log.i("Will fetch outputs following connectionSucceeded"); left_outputs.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() { @Override public void onChildViewAdded(View parent, View child) { int i = 0; for (MPDOutput output : outputs) left_outputs.setItemChecked(i++, output.isEnabled()); } @Override public void onChildViewRemoved(View parent, View child) { } }); left_outputs.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { try { //if ("slave".equals(id[1])) //oMPD.setStickers("global", "slaves", id[0], (System.currentTimeMillis()/1000) + (on? "=on" : "=off")); if (left_outputs.isItemChecked(position)) app.oMPDAsyncHelper.oMPD.enableOutput(outputs.get(position).getId()); else app.oMPDAsyncHelper.oMPD.disableOutput(outputs.get(position).getId()); } catch (MPDServerException e) { Log.e(e); } } }); setListViewHeightBasedOnChildren(left_outputs, false); final ListView left_servers = (ListView) findViewById(R.id.left_servers); final ArrayAdapter<ServerInfo> servers_adapter = new ArrayAdapter<ServerInfo>(this, android.R.layout.simple_list_item_1, android.R.id.text1, new ArrayList<ServerInfo>(app.serverDiscovery.servers)); left_servers.setAdapter(servers_adapter); app.serverDiscovery.onChanged = new Runnable() { @Override public void run() { left_servers.post(new Runnable() { @Override public void run() { servers_adapter.clear(); servers_adapter.addAll(app.serverDiscovery.servers); Log.i("Server count: " + app.serverDiscovery.servers.size()); servers_adapter.notifyDataSetChanged(); setListViewHeightBasedOnChildren(left_servers, false); } }); } }; left_servers.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { app.serverDiscovery.choose(position); drawer_layout.closeDrawers(); } }); setListViewHeightBasedOnChildren(left_servers, false); } int minListItemSize = 96; public void setListViewHeightBasedOnChildren(ListView listView, boolean record_size) { ArrayAdapter<?> listAdapter = (ArrayAdapter<?>) listView.getAdapter(); if (listAdapter == null) return; int totalHeight = 0, N = listAdapter.getCount(); for (int i = 0; i < N; i++) { final View listItem = listAdapter.getView(i, null, listView); listItem.measure( MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.MATCH_PARENT, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int size = Math.max(minListItemSize, listItem.getMeasuredHeight()); totalHeight += size; if (record_size) minListItemSize = size; } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (N - 1)); Log.i("setListViewHeightBasedOnChildren " + listView + " " + N + " " + params.height); listView.setLayoutParams(params); listView.requestLayout(); } void replace(Fragment old, String title, String label) { actionBarAdapter.remove(actionBarAdapter.getItem(0)); actionBarAdapter.insert(title, 0); if (actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_STANDARD) actionBar.setTitle(title); } public void replaceLibraryFragment(String tab, String label) { replace(mSectionsPagerAdapter.replace(tab), LibraryTabsUtil.getTabTitle(context, tab).getString(context), label); } @Override public void pushLibraryFragment(Fragment fragment, String label) { replace(mSectionsPagerAdapter.push(fragment), getTitle(fragment), label); mViewPager.setCurrentItem(0, true); } @Override public void onStart() { super.onStart(); MPDApplication app = (MPDApplication) getApplicationContext(); app.setActivity(this); } @Override public void onStop() { super.onStop(); MPDApplication app = (MPDApplication) getApplicationContext(); app.unsetActivity(this); } @Override protected void onResume() { super.onResume(); backPressExitCount = 0; } @Override public boolean dispatchTouchEvent (MotionEvent event) { Object item = mSectionsPagerAdapter.getPrimaryItem(); if (item instanceof GestureFragment) ((GestureFragment)item).onTouchEvent(null, event); return super.dispatchTouchEvent(event); } public boolean popBrowser() { if (mViewPager.getCurrentItem() == 0) { Fragment old = mSectionsPagerAdapter.pop(); if (old != null) { CharSequence title = mSectionsPagerAdapter.getPageTitle(0); actionBarAdapter.remove(getTitle(old)); actionBarAdapter.insert(title, 0); if (actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_STANDARD) actionBar.setTitle(title); final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); ft.remove(old); ft.commit(); return true; } } return false; } @Override public void onSwipeLeft() { } @Override public void onSwipeRight() { if (!popBrowser()) drawer_layout.openDrawer(GravityCompat.START); } /** * Called when Back button is pressed, displays message to user indicating the if back button is pressed again the application will exit. We keep a count of how many time back * button is pressed within 5 seconds. If the count is greater than 1 then call system.exit(0) * * Starts a post delay handler to reset the back press count to zero after 5 seconds * * @return None */ @Override public void onBackPressed() { if (drawer_layout.isDrawerVisible(GravityCompat.START) || drawer_layout.isDrawerVisible(Gravity.LEFT)) { drawer_layout.closeDrawers(); return; } if (popBrowser()) return; if (mViewPager.getCurrentItem() != 1) { mViewPager.setCurrentItem(1, true); return; } final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); final boolean exitConfirmationRequired = settings.getBoolean("enableExitConfirmation", false); if (exitConfirmationRequired && backPressExitCount < 1) { try { Tools.notifyUser(String.format(getResources().getString(R.string.backpressToQuit)), this); } catch (Exception e) { Log.w(e); } backPressExitCount += 1; exitCounterReset.postDelayed(new Runnable() { @Override public void run() { backPressExitCount = 0; } }, 5000); } else { /* * Nasty force quit, should shutdown everything nicely but there just too many async tasks maybe I'll correctly implement app.terminateApplication(); */ System.exit(0); } return; } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { mViewPager.setCurrentItem(itemPosition); return true; } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary * sections of the app. */ static int next = 100; public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); replace(tabs.get(0)); } public Fragment replace(String tab) { Class<? extends Object> clazz = tab == null? null : LibraryTabsUtil.getClass(MainMenuActivity.this, tab); for (int i = 0, N = stack.size(); i < N; i++) { Tuple3<Integer, Fragment, String> t = stack.get(i); if (tab == null || clazz.isInstance(t._2) && t._3.equals(LibraryTabsUtil.getTabTitle(context, tab).getString(context))) try { return i + 1 == N? null : stack.peek()._2; } finally { if (i + 1 < N) { stack.subList(i + 1, N).clear(); notifyDataSetChanged(); } } } try { return push((Fragment) Tools.instantiate(clazz)); } finally { stack.subList(0, stack.size() - 1).clear(); } } Stack<Tuple3<Integer, Fragment, String>> stack = new Stack<Tuple3<Integer, Fragment, String>>(); public Fragment push(Fragment f) { try { Fragment g = stack.isEmpty()? null : stack.peek()._2; stack.push(new Tuple3<Integer, Fragment, String>(++next, f, getTitle(f))); return g; } finally { notifyDataSetChanged(); } } public Fragment pop() { try { return stack.size() > 1? stack.pop()._2 : null; } finally { notifyDataSetChanged(); } } @Override public Fragment getItem(int i) { Fragment fragment = null; switch (i) { case 0: fragment = stack.peek()._2; break; case 1: if (isTablet && !isDualPaneMode) fragment = new MainPageFragment(); else fragment = new NowPlayingFragment(); break; case 2: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { fragment = new PlaylistFragment(); } else { fragment = new PlaylistFragmentCompat(); } break; } return fragment; } @Override public int getCount() { return isTablet? 2 : 3; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return stack.peek()._3; case 1: return getString(R.string.nowPlaying); case 2: return getString(R.string.playQueue); } return null; } @Override public int getItemPosition(Object object) { if (object instanceof BrowseFragment && object != stack.peek()._2) return POSITION_NONE; return POSITION_UNCHANGED; } @Override public long getItemId(int position) { return position > 0? position : stack.peek()._1; } Object primaryItem; public Object getPrimaryItem() { return primaryItem; } @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { super.setPrimaryItem(container, position, primaryItem = object); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.mpd_mainmenu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { //Reminder : never disable buttons that are shown as actionbar actions here super.onPrepareOptionsMenu(menu); int page = mViewPager.getCurrentItem(); Log.i("onPrepareOptionsMenu " + page); //menu.findItem(R.id.menu_search).setShowAsAction(page == 0? MenuItem.SHOW_AS_ACTION_ALWAYS : MenuItem.SHOW_AS_ACTION_NEVER); menu.findItem(R.id.menu_up_to_root).setVisible(page == 0); menu.findItem(R.id.GMM_LibTab).setVisible(page == 1); menu.findItem(R.id.menu_back_left).setVisible(page == 2); menu.findItem(R.id.menu_back_right).setVisible(page == 0); menu.findItem(R.id.menu_playlist).setVisible(page == 1 && !isTablet); menu.findItem(R.id.menu_search).setShowAsAction(page == 1 && isTablet? MenuItem.SHOW_AS_ACTION_ALWAYS : MenuItem.SHOW_AS_ACTION_NEVER); menu.findItem(R.id.PLM_EditPL).setVisible(page == 2); menu.findItem(R.id.PLM_Clear).setVisible(page == 2); menu.findItem(R.id.PLM_Save).setVisible(page == 2); final MPDApplication app = (MPDApplication) getApplication(); MPDStatus status = app.getApplicationState().currentMpdStatus; menu.findItem(R.id.menu_play).setIcon(getResources().getDrawable( status != null && MPDStatus.MPD_STATE_PLAYING.equals(status.getState()) ? R.drawable.ic_media_pause : R.drawable.ic_media_play )); MPD mpd = app.oMPDAsyncHelper.oMPD; if (!mpd.isConnected()) { if (menu.findItem(CONNECT) == null) { menu.add(0, CONNECT, 0, R.string.connect); } } else { if (menu.findItem(CONNECT) != null) { menu.removeItem(CONNECT); } } setMenuChecked(menu.findItem(R.id.GMM_Stream), app.getApplicationState().streamingMode); final MPDStatus mpdStatus = app.getApplicationState().currentMpdStatus; if (mpdStatus != null) { setMenuChecked(menu.findItem(R.id.GMM_Single), mpdStatus.isSingle()); setMenuChecked(menu.findItem(R.id.GMM_Consume), mpdStatus.isConsume()); setMenuChecked(menu.findItem(R.id.GMM_Random), mpdStatus.isRandom()); setMenuChecked(menu.findItem(R.id.GMM_Repeat), mpdStatus.isRepeat()); } return true; } private void setMenuChecked(MenuItem item, boolean checked) { // Set the icon to a checkbox so 2.x users also get one item.setChecked(checked); item.setIcon(checked ? R.drawable.btn_check_buttonless_on : R.drawable.btn_check_buttonless_off); } private void openLibrary() { final Intent i = new Intent(this, LibraryTabActivity.class); startActivity(i); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(final MenuItem item) { if (drawerToggle.onOptionsItemSelected(getMenuItem(item))) return true; Intent i = null; final MPDApplication app = (MPDApplication) this.getApplication(); final MPD mpd = app.oMPDAsyncHelper.oMPD; // Handle item selection switch (item.getItemId()) { case R.id.menu_search: this.onSearchRequested(); return true; case R.id.menu_up_to_root: if (mSectionsPagerAdapter.replace(null) == null) if (drawer_layout.isDrawerVisible(GravityCompat.START) || drawer_layout.isDrawerVisible(Gravity.LEFT)) drawer_layout.closeDrawers(); else drawer_layout.openDrawer(GravityCompat.START); return true; case R.id.GMM_LibTab: mViewPager.setCurrentItem(0, true); return true; case R.id.menu_back_left: case R.id.menu_back_right: mViewPager.setCurrentItem(1, true); return true; case R.id.menu_playlist: mViewPager.setCurrentItem(2, true); return true; case R.id.GMM_Settings: i = new Intent(this, SettingsActivity.class); startActivityForResult(i, SETTINGS); return true; case R.id.GMM_Outputs: i = new Intent(this, SettingsActivity.class); i.putExtra(SettingsActivity.OPEN_OUTPUT, true); startActivityForResult(i, SETTINGS); return true; case CONNECT: ((MPDApplication) this.getApplication()).connect(); return true; case R.id.GMM_Stream: if (app.getApplicationState().streamingMode) { i = new Intent(this, StreamingService.class); i.setAction("org.musicpd.android.DIE"); this.startService(i); ((MPDApplication) this.getApplication()).getApplicationState().streamingMode = false; // Toast.makeText(this, "MPD Streaming Stopped", Toast.LENGTH_SHORT).show(); } else { if (app.oMPDAsyncHelper.oMPD.isConnected()) { i = new Intent(this, StreamingService.class); i.setAction("org.musicpd.android.START_STREAMING"); this.startService(i); ((MPDApplication) this.getApplication()).getApplicationState().streamingMode = true; // Toast.makeText(this, "MPD Streaming Started", Toast.LENGTH_SHORT).show(); } } return true; case R.id.GMM_bonjour: startActivity(new Intent(this, ServerBonjourListActivity.class)); return true; case R.id.GMM_Consume: try { mpd.setConsume(!mpd.getStatus().isConsume()); } catch (MPDServerException e) { } return true; case R.id.GMM_Single: try { mpd.setSingle(!mpd.getStatus().isSingle()); } catch (MPDServerException e) { } return true; case R.id.GMM_Random: try { mpd.setRandom(!mpd.getStatus().isRandom()); } catch (MPDServerException e) { } return true; case R.id.GMM_Repeat: try { mpd.setRepeat(!mpd.getStatus().isRepeat()); } catch (MPDServerException e) { } return true; case R.id.menu_previous: case R.id.menu_play: case R.id.menu_next: new Job() { @Override public void run() { try { switch (item.getItemId()) { case R.id.menu_previous: mpd.previous(); break; case R.id.menu_play: String state = mpd.getStatus().getState(); if (state == null || state.equals(MPDStatus.MPD_STATE_PLAYING) || state.equals(MPDStatus.MPD_STATE_PAUSED)) mpd.pause(); else mpd.play(); break; case R.id.menu_next: mpd.next(); break; } } catch (MPDServerException e) { Log.w(e); } } }; return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { final MPDApplication app = (MPDApplication) getApplicationContext(); switch (event.getKeyCode()) { case KeyEvent.KEYCODE_VOLUME_UP: new Job() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD.next(); } catch (MPDServerException e) { Log.w(e); } } }; return true; case KeyEvent.KEYCODE_VOLUME_DOWN: new Job() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD.previous(); } catch (MPDServerException e) { Log.w(e); } } }; return true; } return super.onKeyLongPress(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) { // For onKeyLongPress to work event.startTracking(); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, final KeyEvent event) { final MPDApplication app = (MPDApplication) getApplicationContext(); switch (event.getKeyCode()) { case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_DOWN: if (event.isTracking() && !event.isCanceled() && !app.getApplicationState().streamingMode) { new Job() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD.adjustVolume(event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP ? NowPlayingFragment.VOLUME_STEP : -NowPlayingFragment.VOLUME_STEP); } catch (MPDServerException e) { Log.w(e); } } }; } return true; } return super.onKeyUp(keyCode, event); } }