target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void calculate() throws Exception { assertEquals(8.467838642560691, DoublingTime.calculate(Rate.of(0.0853)).doubleValue(), 0.0d); assertEquals(1.709511291351455, DoublingTime.calculate(Rate.of(0.5)).doubleValue(), 0.0d); assertEquals(1.0, DoublingTime.calculate(Rate.of(1)).doubleValue(), 0.0d); assertEquals(15.74730183648559, DoublingTime.calculate(Rate.of(0.045)).doubleValue(), 0.0d); } | public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); } | DoublingTime { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); } } | DoublingTime { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); } private DoublingTime(); } | DoublingTime { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); } private DoublingTime(); static BigDecimal calculate(Rate rate); } | DoublingTime { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); } private DoublingTime(); static BigDecimal calculate(Rate rate); } |
@Test(expected = MonetaryException.class) public void calculate_Invalid(){ DoublingTime.calculate(Rate.of(0)); } | public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); } | DoublingTime { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); } } | DoublingTime { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); } private DoublingTime(); } | DoublingTime { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); } private DoublingTime(); static BigDecimal calculate(Rate rate); } | DoublingTime { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); } private DoublingTime(); static BigDecimal calculate(Rate rate); } |
@Test public void getRate() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.03,1) ); assertEquals(val.getRate(), Rate.of(0.03)); } | public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } | PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } } | PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); } | PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } | PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } |
@Test public void calculate_twoPeriods() throws Exception { BalloonLoanPayment ci = BalloonLoanPayment.of( RateAndPeriods.of(0.05,2), Money.of(5, "CHF") ); assertEquals(Money.of(100,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(51.34,"CHF")); assertEquals(Money.of(0,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(-2.44,"CHF")); assertEquals(Money.of(-1,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(-2.98,"CHF")); } | public static BalloonLoanPayment of(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount){ return new BalloonLoanPayment(rateAndPeriods, balloonAmount); } | BalloonLoanPayment extends AbstractRateAndPeriodBasedOperator { public static BalloonLoanPayment of(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount){ return new BalloonLoanPayment(rateAndPeriods, balloonAmount); } } | BalloonLoanPayment extends AbstractRateAndPeriodBasedOperator { public static BalloonLoanPayment of(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount){ return new BalloonLoanPayment(rateAndPeriods, balloonAmount); } private BalloonLoanPayment(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount); } | BalloonLoanPayment extends AbstractRateAndPeriodBasedOperator { public static BalloonLoanPayment of(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount){ return new BalloonLoanPayment(rateAndPeriods, balloonAmount); } private BalloonLoanPayment(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount); MonetaryAmount getBalloonAmount(); static BalloonLoanPayment of(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount); @Override MonetaryAmount apply(MonetaryAmount amountPV); @Override String toString(); static MonetaryAmount calculate(MonetaryAmount amountPV, MonetaryAmount balloonAmount,
RateAndPeriods rateAndPeriods); } | BalloonLoanPayment extends AbstractRateAndPeriodBasedOperator { public static BalloonLoanPayment of(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount){ return new BalloonLoanPayment(rateAndPeriods, balloonAmount); } private BalloonLoanPayment(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount); MonetaryAmount getBalloonAmount(); static BalloonLoanPayment of(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount); @Override MonetaryAmount apply(MonetaryAmount amountPV); @Override String toString(); static MonetaryAmount calculate(MonetaryAmount amountPV, MonetaryAmount balloonAmount,
RateAndPeriods rateAndPeriods); } |
@Test public void should_sort_ranges() throws Exception { Range first = range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 3)); Range second = range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 5)); Range third = range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 7)); Range fourth = range(from(2017, Calendar.AUGUST, 10), from(2017, Calendar.AUGUST, 27)); List<Range> result = RangeSorter.sort(asList(second, first, third, fourth)); List<Range> expected = asList(first, second, third, fourth); assertEquals(expected, result); } | static List<Range> sort(List<Range> list) { RangeSorter sorter = new RangeSorter(list); sorter.sortRanges(); return sorter.ranges; } | RangeSorter { static List<Range> sort(List<Range> list) { RangeSorter sorter = new RangeSorter(list); sorter.sortRanges(); return sorter.ranges; } } | RangeSorter { static List<Range> sort(List<Range> list) { RangeSorter sorter = new RangeSorter(list); sorter.sortRanges(); return sorter.ranges; } private RangeSorter(List<Range> ranges); } | RangeSorter { static List<Range> sort(List<Range> list) { RangeSorter sorter = new RangeSorter(list); sorter.sortRanges(); return sorter.ranges; } private RangeSorter(List<Range> ranges); } | RangeSorter { static List<Range> sort(List<Range> list) { RangeSorter sorter = new RangeSorter(list); sorter.sortRanges(); return sorter.ranges; } private RangeSorter(List<Range> ranges); } |
@Test public void testFormattedDayOfWeek_Sunday() throws Exception { assertThat(formatter.format(Calendar.SUNDAY).toString(), is("Sun")); } | @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } |
@Test public void testFormattedDayOfWeek_Monday() throws Exception { assertThat(formatter.format(Calendar.MONDAY).toString(), is("Mon")); } | @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } |
@Test public void testFormattedDayOfWeek_Tuesday() throws Exception { assertThat(formatter.format(Calendar.TUESDAY).toString(), is("Tue")); } | @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } |
@Test public void testFormattedDayOfWeek_Wednesday() throws Exception { assertThat(formatter.format(Calendar.WEDNESDAY).toString(), is("Wed")); } | @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } |
@Test public void testFormattedDayOfWeek_Thursday() throws Exception { assertThat(formatter.format(Calendar.THURSDAY).toString(), is("Thu")); } | @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } |
@Test public void testFormattedDayOfWeek_Friday() throws Exception { assertThat(formatter.format(Calendar.FRIDAY).toString(), is("Fri")); } | @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } |
@Test public void shouldReturnCorrectFormattedEnglishTextOfSaturday() throws Exception { assertThat(formatter.format(Calendar.SATURDAY).toString(), is("Sat")); } | @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } | CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); } |
@Test public void should_join_overlapping_ranges() throws Exception { List<Range> ranges = asList( range(from(2017, Calendar.JANUARY, 1), from(2017, Calendar.JANUARY, 4)), range(from(2017, Calendar.JANUARY, 2), from(2017, Calendar.JANUARY, 5)) ); assertEquals(2, ranges.size()); List<Range> result = RangeOverlapMerger.join(ranges); assertEquals(1, result.size()); Range range = result.get(0); assertEquals(1, range.from.getDay()); assertEquals(Calendar.JANUARY, range.from.getMonth()); assertEquals(2017, range.from.getYear()); assertEquals(5, range.to.getDay()); assertEquals(Calendar.JANUARY, range.to.getMonth()); assertEquals(2017, range.to.getYear()); } | static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } |
@Test public void should_join_overlaping_ranges_to_one() throws Exception { List<Range> ranges = asList( range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 5)), range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 3)), range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 7)) ); assertEquals(3, ranges.size()); List<Range> result = RangeOverlapMerger.join(ranges); assertEquals(1, result.size()); Range range = result.get(0); assertEquals(1, range.from.getDay()); assertEquals(Calendar.AUGUST, range.from.getMonth()); assertEquals(2017, range.from.getYear()); assertEquals(7, range.to.getDay()); assertEquals(Calendar.AUGUST, range.to.getMonth()); assertEquals(2017, range.to.getYear()); } | static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } |
@Test public void should_join_overlaping_ranges_to_two() throws Exception { List<Range> ranges = asList( range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 5)), range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 3)), range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 7)), range(from(2017, Calendar.AUGUST, 10), from(2017, Calendar.AUGUST, 27)) ); assertEquals(4, ranges.size()); List<Range> result = RangeOverlapMerger.join(ranges); assertEquals(2, result.size()); Range range1 = result.get(0); assertEquals(1, range1.from.getDay()); assertEquals(Calendar.AUGUST, range1.from.getMonth()); assertEquals(2017, range1.from.getYear()); assertEquals(7, range1.to.getDay()); assertEquals(Calendar.AUGUST, range1.to.getMonth()); assertEquals(2017, range1.to.getYear()); Range range2 = result.get(1); assertEquals(10, range2.from.getDay()); assertEquals(Calendar.AUGUST, range2.from.getMonth()); assertEquals(2017, range2.from.getYear()); assertEquals(27, range2.to.getDay()); assertEquals(Calendar.AUGUST, range2.to.getMonth()); assertEquals(2017, range2.to.getYear()); } | static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } |
@Test public void should_not_join_ranges() throws Exception { List<Range> ranges = asList( range(from(2017, Calendar.JANUARY, 1), from(2017, Calendar.JANUARY, 4)), range(from(2017, Calendar.JANUARY, 6), from(2017, Calendar.JANUARY, 9)) ); assertEquals(ranges.size(), 2); List<Range> result = RangeOverlapMerger.join(ranges); assertEquals(result.size(), 2); } | static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } |
@Test public void should_join_overlaping_ranges_within_same_days() throws Exception { List<Range> ranges = asList( range(from(2017, Calendar.JANUARY, 1), from(2017, Calendar.JANUARY, 4)), range(from(2017, Calendar.JANUARY, 4), from(2017, Calendar.JANUARY, 9)) ); assertEquals(ranges.size(), 2); List<Range> result = RangeOverlapMerger.join(ranges); assertEquals(result.size(), 1); Range range = result.get(0); assertEquals(1, range.from.getDay()); assertEquals(Calendar.JANUARY, range.from.getMonth()); assertEquals(2017, range.from.getYear()); assertEquals(9, range.to.getDay()); assertEquals(Calendar.JANUARY, range.to.getMonth()); assertEquals(2017, range.to.getYear()); } | static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } |
@Test public void should_not_join_overlaping_ranges_on_next_day() throws Exception { List<Range> ranges = asList( range(from(2017, Calendar.JANUARY, 1), from(2017, Calendar.JANUARY, 4)), range(from(2017, Calendar.JANUARY, 5), from(2017, Calendar.JANUARY, 9)) ); assertEquals(ranges.size(), 2); List<Range> result = RangeOverlapMerger.join(ranges); assertEquals(result.size(), 2); } | static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } |
@Test public void should_join_overlaping_ranges_over_month() throws Exception { List<Range> ranges = asList( range(from(2017, Calendar.JANUARY, 1), from(2017, Calendar.JANUARY, 25)), range(from(2017, Calendar.JANUARY, 15), from(2017, Calendar.FEBRUARY, 9)) ); assertEquals(ranges.size(), 2); List<Range> result = RangeOverlapMerger.join(ranges); assertEquals(result.size(), 1); Range range = result.get(0); assertEquals(1, range.from.getDay()); assertEquals(Calendar.JANUARY, range.from.getMonth()); assertEquals(2017, range.from.getYear()); assertEquals(9, range.to.getDay()); assertEquals(Calendar.FEBRUARY, range.to.getMonth()); assertEquals(2017, range.to.getYear()); } | static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } |
@Test public void should_join_overlaping_ranges_over_months() throws Exception { List<Range> ranges = asList( range(from(2017, Calendar.JANUARY, 1), from(2017, Calendar.FEBRUARY, 4)), range(from(2017, Calendar.FEBRUARY, 2), from(2017, Calendar.MARCH, 9)) ); assertEquals(ranges.size(), 2); List<Range> result = RangeOverlapMerger.join(ranges); assertEquals(result.size(), 1); Range range = result.get(0); assertEquals(1, range.from.getDay()); assertEquals(Calendar.JANUARY, range.from.getMonth()); assertEquals(2017, range.from.getYear()); assertEquals(9, range.to.getDay()); assertEquals(Calendar.MARCH, range.to.getMonth()); assertEquals(2017, range.to.getYear()); } | static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } |
@Test public void should_join_more_ranges_to_one() throws Exception { List<Range> ranges = asList( range(from(2017, Calendar.JANUARY, 1), from(2017, Calendar.JANUARY, 4)), range(from(2017, Calendar.JANUARY, 3), from(2017, Calendar.JANUARY, 9)), range(from(2017, Calendar.JANUARY, 5), from(2017, Calendar.JANUARY, 19)), range(from(2017, Calendar.JANUARY, 2), from(2017, Calendar.JANUARY, 18)), range(from(2017, Calendar.JANUARY, 7), from(2017, Calendar.JANUARY, 25)) ); assertEquals(ranges.size(), 5); List<Range> result = RangeOverlapMerger.join(ranges); assertEquals(result.size(), 1); Range range = result.get(0); assertEquals(1, range.from.getDay()); assertEquals(Calendar.JANUARY, range.from.getMonth()); assertEquals(2017, range.from.getYear()); assertEquals(25, range.to.getDay()); assertEquals(Calendar.JANUARY, range.to.getMonth()); assertEquals(2017, range.to.getYear()); } | static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } |
@Test public void sessionTestErrorCase() throws Exception { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .build(); WakelockMonitor monitor = new WakelockMonitor(testUtilComponent, stateObservable(), EVENT_WAKELOCK_ACQUIRED, MONITOR_LABEL_WAKELOCK); TestObserver<FalxMonitorEvent> testObserver = monitor.getEventObservable().test(); TestClock testClock = (TestClock) monitor.clock; final long firstSessionStartTime = 100L; long currentTime = firstSessionStartTime; testClock.setCurrentTimeMillis(currentTime); Assert.assertEquals(testClock.currentTimeMillis(), currentTime); monitor.released(); FalxMonitorEvent event = testObserver.values().get(0); Assert.assertEquals(EVENT_WAKELOCK_ACQUIRED, event.getName()); Assert.assertEquals(0, (long)(event.getArguments().get(FalxConstants.PROP_DURATION) * DateUtils.SECOND_IN_MILLIS)); } | @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean released() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a wakelock session"); endTime = startTime; } logger.d(Logger.TAG, label + " wakelock released, duration (seconds): " + ((endTime - startTime) / 1000)); if (monitorEvent != null) { sessionData.endTime = endTime; monitorEvent.updateArgs(sessionData.getArgumentMap()); eventPublishSubject.onNext(monitorEvent); } else { OnOffSessionData sessionData1 = new OnOffSessionData(metricName, startTime, endTime); eventPublishSubject.onNext(new FalxMonitorEvent(sessionData1.getName(), sessionData1.getArgumentMap())); } startTime = 0; sessionData = null; maxDuration = 0; monitorEvent = null; return true; } | WakelockMonitor extends Monitor { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean released() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a wakelock session"); endTime = startTime; } logger.d(Logger.TAG, label + " wakelock released, duration (seconds): " + ((endTime - startTime) / 1000)); if (monitorEvent != null) { sessionData.endTime = endTime; monitorEvent.updateArgs(sessionData.getArgumentMap()); eventPublishSubject.onNext(monitorEvent); } else { OnOffSessionData sessionData1 = new OnOffSessionData(metricName, startTime, endTime); eventPublishSubject.onNext(new FalxMonitorEvent(sessionData1.getName(), sessionData1.getArgumentMap())); } startTime = 0; sessionData = null; maxDuration = 0; monitorEvent = null; return true; } } | WakelockMonitor extends Monitor { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean released() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a wakelock session"); endTime = startTime; } logger.d(Logger.TAG, label + " wakelock released, duration (seconds): " + ((endTime - startTime) / 1000)); if (monitorEvent != null) { sessionData.endTime = endTime; monitorEvent.updateArgs(sessionData.getArgumentMap()); eventPublishSubject.onNext(monitorEvent); } else { OnOffSessionData sessionData1 = new OnOffSessionData(metricName, startTime, endTime); eventPublishSubject.onNext(new FalxMonitorEvent(sessionData1.getName(), sessionData1.getArgumentMap())); } startTime = 0; sessionData = null; maxDuration = 0; monitorEvent = null; return true; } WakelockMonitor(@NonNull UtilComponent utilComponent, @NonNull Observable<WakelockState> stateObservable, String metricName, String label); } | WakelockMonitor extends Monitor { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean released() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a wakelock session"); endTime = startTime; } logger.d(Logger.TAG, label + " wakelock released, duration (seconds): " + ((endTime - startTime) / 1000)); if (monitorEvent != null) { sessionData.endTime = endTime; monitorEvent.updateArgs(sessionData.getArgumentMap()); eventPublishSubject.onNext(monitorEvent); } else { OnOffSessionData sessionData1 = new OnOffSessionData(metricName, startTime, endTime); eventPublishSubject.onNext(new FalxMonitorEvent(sessionData1.getName(), sessionData1.getArgumentMap())); } startTime = 0; sessionData = null; maxDuration = 0; monitorEvent = null; return true; } WakelockMonitor(@NonNull UtilComponent utilComponent, @NonNull Observable<WakelockState> stateObservable, String metricName, String label); @Override void stop(); } | WakelockMonitor extends Monitor { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean released() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a wakelock session"); endTime = startTime; } logger.d(Logger.TAG, label + " wakelock released, duration (seconds): " + ((endTime - startTime) / 1000)); if (monitorEvent != null) { sessionData.endTime = endTime; monitorEvent.updateArgs(sessionData.getArgumentMap()); eventPublishSubject.onNext(monitorEvent); } else { OnOffSessionData sessionData1 = new OnOffSessionData(metricName, startTime, endTime); eventPublishSubject.onNext(new FalxMonitorEvent(sessionData1.getName(), sessionData1.getArgumentMap())); } startTime = 0; sessionData = null; maxDuration = 0; monitorEvent = null; return true; } WakelockMonitor(@NonNull UtilComponent utilComponent, @NonNull Observable<WakelockState> stateObservable, String metricName, String label); @Override void stop(); } |
@Test public void testObservable() { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .testLoggerModule(new TestLoggerModule()) .build(); PublishSubject<RealtimeMessagingActivity> rtMessagingPublishSubject = PublishSubject.create(); PublishSubject<RealtimeMessagingSession> realtimeMessagingSessionObservable = PublishSubject.create(); RealtimeMessagingMonitor monitor = new RealtimeMessagingMonitor(testUtilComponent, rtMessagingPublishSubject, realtimeMessagingSessionObservable) { @Override protected void saveToDataStore(RealtimeMessagingActivity activity) { } }; Assert.assertNotNull(monitor.rtMessagingDisposable); Assert.assertFalse(monitor.rtMessagingDisposable.isDisposed()); monitor.stop(); Assert.assertTrue(monitor.rtMessagingDisposable.isDisposed()); } | @Override public void stop() { super.stop(); if (!rtMessagingDisposable.isDisposed()) { rtMessagingDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingDisposable"); } if (!rtMessagingSessionDisposable.isDisposed()) { rtMessagingSessionDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingSessionDisposable"); } } | RealtimeMessagingMonitor extends Monitor { @Override public void stop() { super.stop(); if (!rtMessagingDisposable.isDisposed()) { rtMessagingDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingDisposable"); } if (!rtMessagingSessionDisposable.isDisposed()) { rtMessagingSessionDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingSessionDisposable"); } } } | RealtimeMessagingMonitor extends Monitor { @Override public void stop() { super.stop(); if (!rtMessagingDisposable.isDisposed()) { rtMessagingDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingDisposable"); } if (!rtMessagingSessionDisposable.isDisposed()) { rtMessagingSessionDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingSessionDisposable"); } } RealtimeMessagingMonitor(@NonNull Observable<RealtimeMessagingActivity> rtDataObservable,
@NonNull Observable<RealtimeMessagingSession> rtMessagingSessionObservable); RealtimeMessagingMonitor(@NonNull UtilComponent utilComponent,
@NonNull Observable<RealtimeMessagingActivity> rtMessagingObservable,
@NonNull Observable<RealtimeMessagingSession> rtMessagingSessionObservable); } | RealtimeMessagingMonitor extends Monitor { @Override public void stop() { super.stop(); if (!rtMessagingDisposable.isDisposed()) { rtMessagingDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingDisposable"); } if (!rtMessagingSessionDisposable.isDisposed()) { rtMessagingSessionDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingSessionDisposable"); } } RealtimeMessagingMonitor(@NonNull Observable<RealtimeMessagingActivity> rtDataObservable,
@NonNull Observable<RealtimeMessagingSession> rtMessagingSessionObservable); RealtimeMessagingMonitor(@NonNull UtilComponent utilComponent,
@NonNull Observable<RealtimeMessagingActivity> rtMessagingObservable,
@NonNull Observable<RealtimeMessagingSession> rtMessagingSessionObservable); static UtilComponent createDaggerComponent(); @Override void stop(); } | RealtimeMessagingMonitor extends Monitor { @Override public void stop() { super.stop(); if (!rtMessagingDisposable.isDisposed()) { rtMessagingDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingDisposable"); } if (!rtMessagingSessionDisposable.isDisposed()) { rtMessagingSessionDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingSessionDisposable"); } } RealtimeMessagingMonitor(@NonNull Observable<RealtimeMessagingActivity> rtDataObservable,
@NonNull Observable<RealtimeMessagingSession> rtMessagingSessionObservable); RealtimeMessagingMonitor(@NonNull UtilComponent utilComponent,
@NonNull Observable<RealtimeMessagingActivity> rtMessagingObservable,
@NonNull Observable<RealtimeMessagingSession> rtMessagingSessionObservable); static UtilComponent createDaggerComponent(); @Override void stop(); } |
@Test public void testObservable() { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .testLoggerModule(new TestLoggerModule()) .build(); PublishSubject<NetworkActivity> networkActivityPublishSubject = PublishSubject.create(); NetworkMonitor monitor = new NetworkMonitor(testUtilComponent, networkActivityPublishSubject) { @Override protected void saveToDataStore(NetworkActivity activity) { } }; Assert.assertNotNull(monitor.networkActivityDisposable); Assert.assertFalse(monitor.networkActivityDisposable.isDisposed()); monitor.stop(); Assert.assertTrue(monitor.networkActivityDisposable.isDisposed()); } | @Override public void stop() { super.stop(); if (!networkActivityDisposable.isDisposed()) { networkActivityDisposable.dispose(); logger.d(TAG, "stop: disposed networkActivityDisposable"); } } | NetworkMonitor extends Monitor { @Override public void stop() { super.stop(); if (!networkActivityDisposable.isDisposed()) { networkActivityDisposable.dispose(); logger.d(TAG, "stop: disposed networkActivityDisposable"); } } } | NetworkMonitor extends Monitor { @Override public void stop() { super.stop(); if (!networkActivityDisposable.isDisposed()) { networkActivityDisposable.dispose(); logger.d(TAG, "stop: disposed networkActivityDisposable"); } } NetworkMonitor(@NonNull Observable<NetworkActivity> networkActivityObservable); NetworkMonitor(@NonNull UtilComponent utilComponent, @NonNull Observable<NetworkActivity> networkActivityObservable); } | NetworkMonitor extends Monitor { @Override public void stop() { super.stop(); if (!networkActivityDisposable.isDisposed()) { networkActivityDisposable.dispose(); logger.d(TAG, "stop: disposed networkActivityDisposable"); } } NetworkMonitor(@NonNull Observable<NetworkActivity> networkActivityObservable); NetworkMonitor(@NonNull UtilComponent utilComponent, @NonNull Observable<NetworkActivity> networkActivityObservable); static UtilComponent createDaggerComponent(); @Override void stop(); } | NetworkMonitor extends Monitor { @Override public void stop() { super.stop(); if (!networkActivityDisposable.isDisposed()) { networkActivityDisposable.dispose(); logger.d(TAG, "stop: disposed networkActivityDisposable"); } } NetworkMonitor(@NonNull Observable<NetworkActivity> networkActivityObservable); NetworkMonitor(@NonNull UtilComponent utilComponent, @NonNull Observable<NetworkActivity> networkActivityObservable); static UtilComponent createDaggerComponent(); @Override void stop(); } |
@Test public void sessionTestErrorCase() throws Exception { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .build(); OnOffMonitor monitor = new OnOffMonitor(testUtilComponent, stateObservable(), EVENT_GPS_ON, MONITOR_LABEL_GPS); TestObserver<FalxMonitorEvent> testObserver = monitor.getEventObservable().test(); TestClock testClock = (TestClock) monitor.clock; final long firstSessionStartTime = 100L; long currentTime = firstSessionStartTime; testClock.setCurrentTimeMillis(currentTime); Assert.assertEquals(testClock.currentTimeMillis(), currentTime); monitor.turnedOff(); FalxMonitorEvent event = testObserver.values().get(0); Assert.assertEquals(EVENT_GPS_ON, event.getName()); Assert.assertEquals(0, (long)(event.getArguments().get(FalxConstants.PROP_DURATION) * DateUtils.SECOND_IN_MILLIS)); } | @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean turnedOff() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a GPS session"); endTime = startTime; } logger.d(Logger.TAG, label + " Session completed, duration (seconds): " + ((endTime - startTime) / 1000)); OnOffSessionData sessionData = new OnOffSessionData(metricName, startTime, endTime); eventPublishSubject.onNext(new FalxMonitorEvent(sessionData.getName(), sessionData.getArgumentMap())); startTime = 0; return true; } | OnOffMonitor extends Monitor { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean turnedOff() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a GPS session"); endTime = startTime; } logger.d(Logger.TAG, label + " Session completed, duration (seconds): " + ((endTime - startTime) / 1000)); OnOffSessionData sessionData = new OnOffSessionData(metricName, startTime, endTime); eventPublishSubject.onNext(new FalxMonitorEvent(sessionData.getName(), sessionData.getArgumentMap())); startTime = 0; return true; } } | OnOffMonitor extends Monitor { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean turnedOff() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a GPS session"); endTime = startTime; } logger.d(Logger.TAG, label + " Session completed, duration (seconds): " + ((endTime - startTime) / 1000)); OnOffSessionData sessionData = new OnOffSessionData(metricName, startTime, endTime); eventPublishSubject.onNext(new FalxMonitorEvent(sessionData.getName(), sessionData.getArgumentMap())); startTime = 0; return true; } OnOffMonitor(@NonNull UtilComponent utilComponent, @NonNull Observable<Boolean> stateObservable, String metricName, String label); } | OnOffMonitor extends Monitor { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean turnedOff() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a GPS session"); endTime = startTime; } logger.d(Logger.TAG, label + " Session completed, duration (seconds): " + ((endTime - startTime) / 1000)); OnOffSessionData sessionData = new OnOffSessionData(metricName, startTime, endTime); eventPublishSubject.onNext(new FalxMonitorEvent(sessionData.getName(), sessionData.getArgumentMap())); startTime = 0; return true; } OnOffMonitor(@NonNull UtilComponent utilComponent, @NonNull Observable<Boolean> stateObservable, String metricName, String label); @Override void stop(); } | OnOffMonitor extends Monitor { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean turnedOff() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a GPS session"); endTime = startTime; } logger.d(Logger.TAG, label + " Session completed, duration (seconds): " + ((endTime - startTime) / 1000)); OnOffSessionData sessionData = new OnOffSessionData(metricName, startTime, endTime); eventPublishSubject.onNext(new FalxMonitorEvent(sessionData.getName(), sessionData.getArgumentMap())); startTime = 0; return true; } OnOffMonitor(@NonNull UtilComponent utilComponent, @NonNull Observable<Boolean> stateObservable, String metricName, String label); @Override void stop(); } |
@Test public void testEnableLogging() { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .build(); FalxApi api = new FalxApi(mockContext, testUtilComponent); Assert.assertNotNull(api); api.enableLogging(true); FalxInterceptor interceptor = api.getInterceptor(); Assert.assertFalse(interceptor.logger.isEnabled()); api.enableLogging(true); Assert.assertTrue(interceptor.logger.isEnabled()); } | public void enableLogging(boolean enable) { logger.setEnabled(enable); if (falxInterceptor != null) { falxInterceptor.enableLogging(enable); } } | FalxApi { public void enableLogging(boolean enable) { logger.setEnabled(enable); if (falxInterceptor != null) { falxInterceptor.enableLogging(enable); } } } | FalxApi { public void enableLogging(boolean enable) { logger.setEnabled(enable); if (falxInterceptor != null) { falxInterceptor.enableLogging(enable); } } private FalxApi(@NonNull Context context); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) FalxApi(@NonNull Context context, @NonNull UtilComponent utilComponent); } | FalxApi { public void enableLogging(boolean enable) { logger.setEnabled(enable); if (falxInterceptor != null) { falxInterceptor.enableLogging(enable); } } private FalxApi(@NonNull Context context); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) FalxApi(@NonNull Context context, @NonNull UtilComponent utilComponent); static FalxApi getInstance(Context context); void addMonitors(int monitorFlags); void addOnOffMonitor(@NonNull String monitorLabel, @NonNull String metricName); void addWakelockMonitor(@NonNull String monitorLabel, @NonNull String metricName); void removeAllMonitors(); boolean isMonitorActive(int monitorId); boolean isMonitorActive(@NonNull String monitorLabel); boolean startSession(Activity activity); boolean endSession(Activity activity); void turnedOn(@NonNull String label); void turnedOff(@NonNull String label); void wakelockAcquired(@NonNull String label, long maxDuration); void wakelockAcquired(@NonNull String label); void wakelockReleased(@NonNull String label); void realtimeMessageReceived(final RealtimeMessagingActivity activity); void realtimeMessageSessionCompleted(final RealtimeMessagingSession session); void addAppStateListener(AppStateListener listener); void removeAppStateListener(AppStateListener listener); void removeAllAppStateListeners(); void enableLogging(boolean enable); FalxInterceptor getInterceptor(); Observable<RealtimeMessagingActivity> getRealtimeMessagingObservable(); Observable<RealtimeMessagingSession> getRealtimeMessagingSessionObservable(); List<AggregatedFalxMonitorEvent> aggregateEvents(String eventName); List<AggregatedFalxMonitorEvent> aggregatedEvents(String eventName, boolean allowPartialDays); List<AggregatedFalxMonitorEvent> allAggregatedEvents(boolean allowPartialDays); URI writeEventsToFile(@NonNull String fileName); void deleteAllEvents(); } | FalxApi { public void enableLogging(boolean enable) { logger.setEnabled(enable); if (falxInterceptor != null) { falxInterceptor.enableLogging(enable); } } private FalxApi(@NonNull Context context); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) FalxApi(@NonNull Context context, @NonNull UtilComponent utilComponent); static FalxApi getInstance(Context context); void addMonitors(int monitorFlags); void addOnOffMonitor(@NonNull String monitorLabel, @NonNull String metricName); void addWakelockMonitor(@NonNull String monitorLabel, @NonNull String metricName); void removeAllMonitors(); boolean isMonitorActive(int monitorId); boolean isMonitorActive(@NonNull String monitorLabel); boolean startSession(Activity activity); boolean endSession(Activity activity); void turnedOn(@NonNull String label); void turnedOff(@NonNull String label); void wakelockAcquired(@NonNull String label, long maxDuration); void wakelockAcquired(@NonNull String label); void wakelockReleased(@NonNull String label); void realtimeMessageReceived(final RealtimeMessagingActivity activity); void realtimeMessageSessionCompleted(final RealtimeMessagingSession session); void addAppStateListener(AppStateListener listener); void removeAppStateListener(AppStateListener listener); void removeAllAppStateListeners(); void enableLogging(boolean enable); FalxInterceptor getInterceptor(); Observable<RealtimeMessagingActivity> getRealtimeMessagingObservable(); Observable<RealtimeMessagingSession> getRealtimeMessagingSessionObservable(); List<AggregatedFalxMonitorEvent> aggregateEvents(String eventName); List<AggregatedFalxMonitorEvent> aggregatedEvents(String eventName, boolean allowPartialDays); List<AggregatedFalxMonitorEvent> allAggregatedEvents(boolean allowPartialDays); URI writeEventsToFile(@NonNull String fileName); void deleteAllEvents(); static final int MONITOR_APP_STATE; static final int MONITOR_NETWORK; static final int MONITOR_REALTIME_MESSAGING; } |
@Test public void mapsFakeEntityToReal(){ ArticleEntity entity= FakeProvider.provideArticleEntity(); Article article=mapper.map(entity); assertThatAreEqual(article,entity); } | @Override public Article map(ArticleEntity fake) { Article article=new Article(); article.setId(fake.getId()); article.setAuthor(fake.getAuthor()); article.setBackdropUrl(fake.getBackdropUrl()); article.setPosterUrl(fake.getPosterUrl()); article.setTitle(fake.getTitle()); article.setPublishedDate(fake.getPublishedDate()); article.setBody(fake.getBody()); article.setPosterRatio(fake.getPosterRatio()); return article; } | ArticleMapper extends Mapper<Article,ArticleEntity> { @Override public Article map(ArticleEntity fake) { Article article=new Article(); article.setId(fake.getId()); article.setAuthor(fake.getAuthor()); article.setBackdropUrl(fake.getBackdropUrl()); article.setPosterUrl(fake.getPosterUrl()); article.setTitle(fake.getTitle()); article.setPublishedDate(fake.getPublishedDate()); article.setBody(fake.getBody()); article.setPosterRatio(fake.getPosterRatio()); return article; } } | ArticleMapper extends Mapper<Article,ArticleEntity> { @Override public Article map(ArticleEntity fake) { Article article=new Article(); article.setId(fake.getId()); article.setAuthor(fake.getAuthor()); article.setBackdropUrl(fake.getBackdropUrl()); article.setPosterUrl(fake.getPosterUrl()); article.setTitle(fake.getTitle()); article.setPublishedDate(fake.getPublishedDate()); article.setBody(fake.getBody()); article.setPosterRatio(fake.getPosterRatio()); return article; } @Inject ArticleMapper(); } | ArticleMapper extends Mapper<Article,ArticleEntity> { @Override public Article map(ArticleEntity fake) { Article article=new Article(); article.setId(fake.getId()); article.setAuthor(fake.getAuthor()); article.setBackdropUrl(fake.getBackdropUrl()); article.setPosterUrl(fake.getPosterUrl()); article.setTitle(fake.getTitle()); article.setPublishedDate(fake.getPublishedDate()); article.setBody(fake.getBody()); article.setPosterRatio(fake.getPosterRatio()); return article; } @Inject ArticleMapper(); @Override Article map(ArticleEntity fake); } | ArticleMapper extends Mapper<Article,ArticleEntity> { @Override public Article map(ArticleEntity fake) { Article article=new Article(); article.setId(fake.getId()); article.setAuthor(fake.getAuthor()); article.setBackdropUrl(fake.getBackdropUrl()); article.setPosterUrl(fake.getPosterUrl()); article.setTitle(fake.getTitle()); article.setPublishedDate(fake.getPublishedDate()); article.setBody(fake.getBody()); article.setPosterRatio(fake.getPosterRatio()); return article; } @Inject ArticleMapper(); @Override Article map(ArticleEntity fake); } |
@Test public void showsEmptyMessageOnStartMethod(){ when(repository.get()).thenReturn(Observable.just(null)); presenter.start(); verify(view).setLoadingIndicator(eq(true)); verify(view).setLoadingIndicator(eq(false)); verify(view).showEmptyMessage(); } | @Override public void start() { fetchData(); } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } @Inject ArticlesPresenter(@NonNull IRepository<Article> repository,
@NonNull BaseSchedulerProvider schedulerProvider,
@NonNull IArticlesConfig iArticlesConfig); } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } @Inject ArticlesPresenter(@NonNull IRepository<Article> repository,
@NonNull BaseSchedulerProvider schedulerProvider,
@NonNull IArticlesConfig iArticlesConfig); @Override void start(); @Override void stop(); @Override void refresh(); @Override void onConfigChanged(ViewConfig config); @Override void attachView(@NonNull View view); } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } @Inject ArticlesPresenter(@NonNull IRepository<Article> repository,
@NonNull BaseSchedulerProvider schedulerProvider,
@NonNull IArticlesConfig iArticlesConfig); @Override void start(); @Override void stop(); @Override void refresh(); @Override void onConfigChanged(ViewConfig config); @Override void attachView(@NonNull View view); } |
@Test public void showsErrorMessageOnStartMethod(){ when(repository.get()).thenReturn(Observable.error(new Exception())); presenter.start(); verify(view).setLoadingIndicator(eq(true)); verify(view).setLoadingIndicator(eq(false)); verify(view).showErrorMessage(); } | @Override public void start() { fetchData(); } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } @Inject ArticlesPresenter(@NonNull IRepository<Article> repository,
@NonNull BaseSchedulerProvider schedulerProvider,
@NonNull IArticlesConfig iArticlesConfig); } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } @Inject ArticlesPresenter(@NonNull IRepository<Article> repository,
@NonNull BaseSchedulerProvider schedulerProvider,
@NonNull IArticlesConfig iArticlesConfig); @Override void start(); @Override void stop(); @Override void refresh(); @Override void onConfigChanged(ViewConfig config); @Override void attachView(@NonNull View view); } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } @Inject ArticlesPresenter(@NonNull IRepository<Article> repository,
@NonNull BaseSchedulerProvider schedulerProvider,
@NonNull IArticlesConfig iArticlesConfig); @Override void start(); @Override void stop(); @Override void refresh(); @Override void onConfigChanged(ViewConfig config); @Override void attachView(@NonNull View view); } |
@Test public void mapsFakeEntityListToRealList(){ List<ArticleEntity> entities=FakeProvider.provideArticleEntityList(); List<Article> articles=mapper.map(entities); assertThat(articles,notNullValue()); assertThat(articles.size(),is(entities.size())); for(int index=0;index<articles.size();index++){ assertThatAreEqual(articles.get(index),entities.get(index)); } } | @Override public Article map(ArticleEntity fake) { Article article=new Article(); article.setId(fake.getId()); article.setAuthor(fake.getAuthor()); article.setBackdropUrl(fake.getBackdropUrl()); article.setPosterUrl(fake.getPosterUrl()); article.setTitle(fake.getTitle()); article.setPublishedDate(fake.getPublishedDate()); article.setBody(fake.getBody()); article.setPosterRatio(fake.getPosterRatio()); return article; } | ArticleMapper extends Mapper<Article,ArticleEntity> { @Override public Article map(ArticleEntity fake) { Article article=new Article(); article.setId(fake.getId()); article.setAuthor(fake.getAuthor()); article.setBackdropUrl(fake.getBackdropUrl()); article.setPosterUrl(fake.getPosterUrl()); article.setTitle(fake.getTitle()); article.setPublishedDate(fake.getPublishedDate()); article.setBody(fake.getBody()); article.setPosterRatio(fake.getPosterRatio()); return article; } } | ArticleMapper extends Mapper<Article,ArticleEntity> { @Override public Article map(ArticleEntity fake) { Article article=new Article(); article.setId(fake.getId()); article.setAuthor(fake.getAuthor()); article.setBackdropUrl(fake.getBackdropUrl()); article.setPosterUrl(fake.getPosterUrl()); article.setTitle(fake.getTitle()); article.setPublishedDate(fake.getPublishedDate()); article.setBody(fake.getBody()); article.setPosterRatio(fake.getPosterRatio()); return article; } @Inject ArticleMapper(); } | ArticleMapper extends Mapper<Article,ArticleEntity> { @Override public Article map(ArticleEntity fake) { Article article=new Article(); article.setId(fake.getId()); article.setAuthor(fake.getAuthor()); article.setBackdropUrl(fake.getBackdropUrl()); article.setPosterUrl(fake.getPosterUrl()); article.setTitle(fake.getTitle()); article.setPublishedDate(fake.getPublishedDate()); article.setBody(fake.getBody()); article.setPosterRatio(fake.getPosterRatio()); return article; } @Inject ArticleMapper(); @Override Article map(ArticleEntity fake); } | ArticleMapper extends Mapper<Article,ArticleEntity> { @Override public Article map(ArticleEntity fake) { Article article=new Article(); article.setId(fake.getId()); article.setAuthor(fake.getAuthor()); article.setBackdropUrl(fake.getBackdropUrl()); article.setPosterUrl(fake.getPosterUrl()); article.setTitle(fake.getTitle()); article.setPublishedDate(fake.getPublishedDate()); article.setBody(fake.getBody()); article.setPosterRatio(fake.getPosterRatio()); return article; } @Inject ArticleMapper(); @Override Article map(ArticleEntity fake); } |
@Test public void getsAllArticlesIfThereIsNetwork(){ setNetworkAvailable(); setDataSourceResult(remote); repository.get() .observeOn(SCHEDULER.io()) .subscribeOn(SCHEDULER.ui()) .subscribe(this::resultShouldNotBeNull); verify(remote).get(); verify(mapper).map(anyList()); verify(manager).getActiveNetworkInfo(); verify(context).getSystemService(Context.CONNECTIVITY_SERVICE); verify(cacheStore,times(FakeProvider.LIST_SIZE)).put(anyInt(),any(Article.class)); verify(local,times(FakeProvider.LIST_SIZE)).insert(any(ArticleEntity.class)); } | @Override public Observable<Article> get(int id) { if(!cacheStore.isInCache(id)) { if (isNetworkConnection()) { return remoteSource.get(id) .doOnNext(this::saveToLocal) .map(mapper::map) .doOnNext(this::saveInCache); } return localSource.get(id) .map(mapper::map) .doOnNext(this::saveInCache); } return Observable.just(cacheStore.get(id)); } | ArticleRepository implements IRepository<Article> { @Override public Observable<Article> get(int id) { if(!cacheStore.isInCache(id)) { if (isNetworkConnection()) { return remoteSource.get(id) .doOnNext(this::saveToLocal) .map(mapper::map) .doOnNext(this::saveInCache); } return localSource.get(id) .map(mapper::map) .doOnNext(this::saveInCache); } return Observable.just(cacheStore.get(id)); } } | ArticleRepository implements IRepository<Article> { @Override public Observable<Article> get(int id) { if(!cacheStore.isInCache(id)) { if (isNetworkConnection()) { return remoteSource.get(id) .doOnNext(this::saveToLocal) .map(mapper::map) .doOnNext(this::saveInCache); } return localSource.get(id) .map(mapper::map) .doOnNext(this::saveInCache); } return Observable.just(cacheStore.get(id)); } @Inject ArticleRepository(@Local DataSource<ArticleEntity> localSource,
@Remote DataSource<ArticleEntity> remoteSource,
BaseSchedulerProvider schedulerProvider,
CacheStore<Article> cacheStore,
Mapper<Article,ArticleEntity> mapper,
Context context); } | ArticleRepository implements IRepository<Article> { @Override public Observable<Article> get(int id) { if(!cacheStore.isInCache(id)) { if (isNetworkConnection()) { return remoteSource.get(id) .doOnNext(this::saveToLocal) .map(mapper::map) .doOnNext(this::saveInCache); } return localSource.get(id) .map(mapper::map) .doOnNext(this::saveInCache); } return Observable.just(cacheStore.get(id)); } @Inject ArticleRepository(@Local DataSource<ArticleEntity> localSource,
@Remote DataSource<ArticleEntity> remoteSource,
BaseSchedulerProvider schedulerProvider,
CacheStore<Article> cacheStore,
Mapper<Article,ArticleEntity> mapper,
Context context); @Override Observable<Article> get(int id); @Override Observable<List<Article>> get(); } | ArticleRepository implements IRepository<Article> { @Override public Observable<Article> get(int id) { if(!cacheStore.isInCache(id)) { if (isNetworkConnection()) { return remoteSource.get(id) .doOnNext(this::saveToLocal) .map(mapper::map) .doOnNext(this::saveInCache); } return localSource.get(id) .map(mapper::map) .doOnNext(this::saveInCache); } return Observable.just(cacheStore.get(id)); } @Inject ArticleRepository(@Local DataSource<ArticleEntity> localSource,
@Remote DataSource<ArticleEntity> remoteSource,
BaseSchedulerProvider schedulerProvider,
CacheStore<Article> cacheStore,
Mapper<Article,ArticleEntity> mapper,
Context context); @Override Observable<Article> get(int id); @Override Observable<List<Article>> get(); } |
@Test public void getsAllArticlesWhenThereIsNoNetwork(){ setDataSourceResult(local); repository.get() .observeOn(SCHEDULER.io()) .subscribeOn(SCHEDULER.ui()) .subscribe(this::resultShouldNotBeNull); verify(local).get(); verify(mapper).map(anyList()); verify(manager).getActiveNetworkInfo(); verify(cacheStore,times(FakeProvider.LIST_SIZE)).put(anyInt(),any(Article.class)); verify(context).getSystemService(Context.CONNECTIVITY_SERVICE); } | @Override public Observable<Article> get(int id) { if(!cacheStore.isInCache(id)) { if (isNetworkConnection()) { return remoteSource.get(id) .doOnNext(this::saveToLocal) .map(mapper::map) .doOnNext(this::saveInCache); } return localSource.get(id) .map(mapper::map) .doOnNext(this::saveInCache); } return Observable.just(cacheStore.get(id)); } | ArticleRepository implements IRepository<Article> { @Override public Observable<Article> get(int id) { if(!cacheStore.isInCache(id)) { if (isNetworkConnection()) { return remoteSource.get(id) .doOnNext(this::saveToLocal) .map(mapper::map) .doOnNext(this::saveInCache); } return localSource.get(id) .map(mapper::map) .doOnNext(this::saveInCache); } return Observable.just(cacheStore.get(id)); } } | ArticleRepository implements IRepository<Article> { @Override public Observable<Article> get(int id) { if(!cacheStore.isInCache(id)) { if (isNetworkConnection()) { return remoteSource.get(id) .doOnNext(this::saveToLocal) .map(mapper::map) .doOnNext(this::saveInCache); } return localSource.get(id) .map(mapper::map) .doOnNext(this::saveInCache); } return Observable.just(cacheStore.get(id)); } @Inject ArticleRepository(@Local DataSource<ArticleEntity> localSource,
@Remote DataSource<ArticleEntity> remoteSource,
BaseSchedulerProvider schedulerProvider,
CacheStore<Article> cacheStore,
Mapper<Article,ArticleEntity> mapper,
Context context); } | ArticleRepository implements IRepository<Article> { @Override public Observable<Article> get(int id) { if(!cacheStore.isInCache(id)) { if (isNetworkConnection()) { return remoteSource.get(id) .doOnNext(this::saveToLocal) .map(mapper::map) .doOnNext(this::saveInCache); } return localSource.get(id) .map(mapper::map) .doOnNext(this::saveInCache); } return Observable.just(cacheStore.get(id)); } @Inject ArticleRepository(@Local DataSource<ArticleEntity> localSource,
@Remote DataSource<ArticleEntity> remoteSource,
BaseSchedulerProvider schedulerProvider,
CacheStore<Article> cacheStore,
Mapper<Article,ArticleEntity> mapper,
Context context); @Override Observable<Article> get(int id); @Override Observable<List<Article>> get(); } | ArticleRepository implements IRepository<Article> { @Override public Observable<Article> get(int id) { if(!cacheStore.isInCache(id)) { if (isNetworkConnection()) { return remoteSource.get(id) .doOnNext(this::saveToLocal) .map(mapper::map) .doOnNext(this::saveInCache); } return localSource.get(id) .map(mapper::map) .doOnNext(this::saveInCache); } return Observable.just(cacheStore.get(id)); } @Inject ArticleRepository(@Local DataSource<ArticleEntity> localSource,
@Remote DataSource<ArticleEntity> remoteSource,
BaseSchedulerProvider schedulerProvider,
CacheStore<Article> cacheStore,
Mapper<Article,ArticleEntity> mapper,
Context context); @Override Observable<Article> get(int id); @Override Observable<List<Article>> get(); } |
@Test public void returnsNullIfThereIsNoValueInCache(){ assertThat(cacheStore.get(FakeProvider.FAKE_ID),nullValue()); } | public T get(int key){ return inMemoryCache.get(key); } | CacheStore { public T get(int key){ return inMemoryCache.get(key); } } | CacheStore { public T get(int key){ return inMemoryCache.get(key); } CacheStore(int size); } | CacheStore { public T get(int key){ return inMemoryCache.get(key); } CacheStore(int size); void put(int key, T item); boolean isInCache(int key); T get(int key); } | CacheStore { public T get(int key){ return inMemoryCache.get(key); } CacheStore(int size); void put(int key, T item); boolean isInCache(int key); T get(int key); } |
@Test public void checksIfItemIsInCache(){ putIn(); assertTrue(cacheStore.isInCache(FakeProvider.FAKE_ID)); } | public boolean isInCache(int key){ return inMemoryCache.get(key,null)!=null; } | CacheStore { public boolean isInCache(int key){ return inMemoryCache.get(key,null)!=null; } } | CacheStore { public boolean isInCache(int key){ return inMemoryCache.get(key,null)!=null; } CacheStore(int size); } | CacheStore { public boolean isInCache(int key){ return inMemoryCache.get(key,null)!=null; } CacheStore(int size); void put(int key, T item); boolean isInCache(int key); T get(int key); } | CacheStore { public boolean isInCache(int key){ return inMemoryCache.get(key,null)!=null; } CacheStore(int size); void put(int key, T item); boolean isInCache(int key); T get(int key); } |
@Test public void showsDataToViewOnStartMethod(){ when(repository.get(1)).thenReturn(Observable.just(FakeProvider.provideArticle())); presenter.loadArticle(1); verify(view).showArticle(any(Article.class)); } | @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } @Inject ArticlePresenter(IRepository<Article> repository,
BaseSchedulerProvider schedulerProvider); } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } @Inject ArticlePresenter(IRepository<Article> repository,
BaseSchedulerProvider schedulerProvider); @Override void attachView(@NonNull View view); @Override void loadArticle(int id); } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } @Inject ArticlePresenter(IRepository<Article> repository,
BaseSchedulerProvider schedulerProvider); @Override void attachView(@NonNull View view); @Override void loadArticle(int id); } |
@Test public void showsEmptyMessageOnStartMethod(){ when(repository.get(1)).thenReturn(Observable.just(null)); presenter.loadArticle(1); verify(view).showEmptyMessage(); } | @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } @Inject ArticlePresenter(IRepository<Article> repository,
BaseSchedulerProvider schedulerProvider); } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } @Inject ArticlePresenter(IRepository<Article> repository,
BaseSchedulerProvider schedulerProvider); @Override void attachView(@NonNull View view); @Override void loadArticle(int id); } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } @Inject ArticlePresenter(IRepository<Article> repository,
BaseSchedulerProvider schedulerProvider); @Override void attachView(@NonNull View view); @Override void loadArticle(int id); } |
@Test public void showsErrorMessageOnStartMethod(){ when(repository.get(1)).thenReturn(Observable.error(new Exception())); presenter.loadArticle(1); verify(view).showErrorMessage(); } | @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } @Inject ArticlePresenter(IRepository<Article> repository,
BaseSchedulerProvider schedulerProvider); } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } @Inject ArticlePresenter(IRepository<Article> repository,
BaseSchedulerProvider schedulerProvider); @Override void attachView(@NonNull View view); @Override void loadArticle(int id); } | ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } @Inject ArticlePresenter(IRepository<Article> repository,
BaseSchedulerProvider schedulerProvider); @Override void attachView(@NonNull View view); @Override void loadArticle(int id); } |
@Test public void showsDataToViewOnStartMethod(){ when(repository.get()).thenReturn(Observable.just(FakeProvider.provideArticleList())); presenter.start(); verify(view).setLoadingIndicator(eq(true)); verify(view).setLoadingIndicator(eq(false)); verify(view).showList(anyList()); } | @Override public void start() { fetchData(); } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } @Inject ArticlesPresenter(@NonNull IRepository<Article> repository,
@NonNull BaseSchedulerProvider schedulerProvider,
@NonNull IArticlesConfig iArticlesConfig); } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } @Inject ArticlesPresenter(@NonNull IRepository<Article> repository,
@NonNull BaseSchedulerProvider schedulerProvider,
@NonNull IArticlesConfig iArticlesConfig); @Override void start(); @Override void stop(); @Override void refresh(); @Override void onConfigChanged(ViewConfig config); @Override void attachView(@NonNull View view); } | ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } @Inject ArticlesPresenter(@NonNull IRepository<Article> repository,
@NonNull BaseSchedulerProvider schedulerProvider,
@NonNull IArticlesConfig iArticlesConfig); @Override void start(); @Override void stop(); @Override void refresh(); @Override void onConfigChanged(ViewConfig config); @Override void attachView(@NonNull View view); } |
@Test public void getWikipediaLink() throws UIMAException, IOException{ WikidataHyponyms WikidataHyponyms = new WikidataHyponyms(); assertEquals("Q4692", WikidataHyponyms.getWikidataId("de", "Renaissance")); assertEquals("Q169243", WikidataHyponyms.getWikidataId("en","Protagoras")); } | public String getWikidataId(String language, String title) throws JSONException, IOException { if(title.contains("#")) return null; String url = "https: language+ ".wikipedia.org/w/api.php?action=query&titles="+title+"&ppprop=wikibase_item&prop=pageprops&format=json&redirects"; System.out.println(url); JSONObject json = new JSONObject(Jsoup.connect(url).ignoreContentType(true).execute().body()); if(!json.getJSONObject("query").has("pages")) return null; String key = json.getJSONObject("query").getJSONObject("pages").keySet().iterator().next(); if(json.getJSONObject("query").getJSONObject("pages").getJSONObject(key).has("pageprops")) return (json.getJSONObject("query").getJSONObject("pages").getJSONObject(key).getJSONObject("pageprops").getString("wikibase_item")); else return null; } | WikidataHyponyms extends JCasAnnotator_ImplBase { public String getWikidataId(String language, String title) throws JSONException, IOException { if(title.contains("#")) return null; String url = "https: language+ ".wikipedia.org/w/api.php?action=query&titles="+title+"&ppprop=wikibase_item&prop=pageprops&format=json&redirects"; System.out.println(url); JSONObject json = new JSONObject(Jsoup.connect(url).ignoreContentType(true).execute().body()); if(!json.getJSONObject("query").has("pages")) return null; String key = json.getJSONObject("query").getJSONObject("pages").keySet().iterator().next(); if(json.getJSONObject("query").getJSONObject("pages").getJSONObject(key).has("pageprops")) return (json.getJSONObject("query").getJSONObject("pages").getJSONObject(key).getJSONObject("pageprops").getString("wikibase_item")); else return null; } } | WikidataHyponyms extends JCasAnnotator_ImplBase { public String getWikidataId(String language, String title) throws JSONException, IOException { if(title.contains("#")) return null; String url = "https: language+ ".wikipedia.org/w/api.php?action=query&titles="+title+"&ppprop=wikibase_item&prop=pageprops&format=json&redirects"; System.out.println(url); JSONObject json = new JSONObject(Jsoup.connect(url).ignoreContentType(true).execute().body()); if(!json.getJSONObject("query").has("pages")) return null; String key = json.getJSONObject("query").getJSONObject("pages").keySet().iterator().next(); if(json.getJSONObject("query").getJSONObject("pages").getJSONObject(key).has("pageprops")) return (json.getJSONObject("query").getJSONObject("pages").getJSONObject(key).getJSONObject("pageprops").getString("wikibase_item")); else return null; } } | WikidataHyponyms extends JCasAnnotator_ImplBase { public String getWikidataId(String language, String title) throws JSONException, IOException { if(title.contains("#")) return null; String url = "https: language+ ".wikipedia.org/w/api.php?action=query&titles="+title+"&ppprop=wikibase_item&prop=pageprops&format=json&redirects"; System.out.println(url); JSONObject json = new JSONObject(Jsoup.connect(url).ignoreContentType(true).execute().body()); if(!json.getJSONObject("query").has("pages")) return null; String key = json.getJSONObject("query").getJSONObject("pages").keySet().iterator().next(); if(json.getJSONObject("query").getJSONObject("pages").getJSONObject(key).has("pageprops")) return (json.getJSONObject("query").getJSONObject("pages").getJSONObject(key).getJSONObject("pageprops").getString("wikibase_item")); else return null; } @Override void initialize(UimaContext context); @Override void process(JCas aJCas); String getWikidataId(String language, String title); HashSet<WikidataHyponymObject> getSubclassOf(String wikidataId); HashSet<WikidataHyponymObject> getSubclassOf(String wikidataId, int depthOffset); HashSet<WikidataHyponymObject> getParentTaxon(String wikidataId, int depthOffset); HashSet<WikidataHyponymObject> getInstenceOf(String wikidataId); HashSet<WikidataHyponymObject> json2Wikidata(JSONObject jsonHyponymsInstanceOf, int depthOffset); } | WikidataHyponyms extends JCasAnnotator_ImplBase { public String getWikidataId(String language, String title) throws JSONException, IOException { if(title.contains("#")) return null; String url = "https: language+ ".wikipedia.org/w/api.php?action=query&titles="+title+"&ppprop=wikibase_item&prop=pageprops&format=json&redirects"; System.out.println(url); JSONObject json = new JSONObject(Jsoup.connect(url).ignoreContentType(true).execute().body()); if(!json.getJSONObject("query").has("pages")) return null; String key = json.getJSONObject("query").getJSONObject("pages").keySet().iterator().next(); if(json.getJSONObject("query").getJSONObject("pages").getJSONObject(key).has("pageprops")) return (json.getJSONObject("query").getJSONObject("pages").getJSONObject(key).getJSONObject("pageprops").getString("wikibase_item")); else return null; } @Override void initialize(UimaContext context); @Override void process(JCas aJCas); String getWikidataId(String language, String title); HashSet<WikidataHyponymObject> getSubclassOf(String wikidataId); HashSet<WikidataHyponymObject> getSubclassOf(String wikidataId, int depthOffset); HashSet<WikidataHyponymObject> getParentTaxon(String wikidataId, int depthOffset); HashSet<WikidataHyponymObject> getInstenceOf(String wikidataId); HashSet<WikidataHyponymObject> json2Wikidata(JSONObject jsonHyponymsInstanceOf, int depthOffset); static final String PARAM_CACHE_PATH; static final String PARAM_THREAD_COUNT; } |
@Test public void format() throws Exception { this.assertFormat("Some test here %s.", 54); this.assertFormat("Some test here %s and there %s, and test [%s]. sfsfs !!!", 54, 59, "HAHA"); this.assertFormat("Some test here %s and there %s, and test [%s]. sfsfs !!!", 54, 59, "HAHA", "DONT SHOW"); Assert.assertEquals("Formatting is not working", "Some test here 54 %s.", Strings.format("Some test here %s %s.", 54)); } | public static String format(final String format, final Object... args) { String retVal = format; for (final Object current : args) { retVal = retVal.replaceFirst("[%][s]", current.toString()); } return retVal; } | Strings { public static String format(final String format, final Object... args) { String retVal = format; for (final Object current : args) { retVal = retVal.replaceFirst("[%][s]", current.toString()); } return retVal; } } | Strings { public static String format(final String format, final Object... args) { String retVal = format; for (final Object current : args) { retVal = retVal.replaceFirst("[%][s]", current.toString()); } return retVal; } } | Strings { public static String format(final String format, final Object... args) { String retVal = format; for (final Object current : args) { retVal = retVal.replaceFirst("[%][s]", current.toString()); } return retVal; } static String format(final String format, final Object... args); } | Strings { public static String format(final String format, final Object... args) { String retVal = format; for (final Object current : args) { retVal = retVal.replaceFirst("[%][s]", current.toString()); } return retVal; } static String format(final String format, final Object... args); } |
@Test public void testPluginConfigurationFromBuild() throws Exception { final File pom = new File(this.getClass().getClassLoader().getResource("pom-1.xml").getFile()); final Model model = TestHelper.readMavenModel(pom); final MavenProject project = Mockito.mock(MavenProject.class); Mockito.when(project.getModel()).thenReturn(model); final Xpp3Dom config = MavenUtils.getPluginConfiguration(project, "com.microsoft.azure:azure-spring-cloud-maven-plugin"); assertNotNull(config); assertNotNull(config.getChild("public")); assertEquals("true", config.getChild("public").getValue()); assertNotNull(config.getChild("deployment")); assertEquals("1", config.getChild("deployment").getChild("cpu").getValue()); } | public static Xpp3Dom getPluginConfiguration(MavenProject mavenProject, String pluginKey) { final Plugin plugin = getPluginFromMavenModel(mavenProject.getModel(), pluginKey); return plugin == null ? null : (Xpp3Dom) plugin.getConfiguration(); } | MavenUtils { public static Xpp3Dom getPluginConfiguration(MavenProject mavenProject, String pluginKey) { final Plugin plugin = getPluginFromMavenModel(mavenProject.getModel(), pluginKey); return plugin == null ? null : (Xpp3Dom) plugin.getConfiguration(); } } | MavenUtils { public static Xpp3Dom getPluginConfiguration(MavenProject mavenProject, String pluginKey) { final Plugin plugin = getPluginFromMavenModel(mavenProject.getModel(), pluginKey); return plugin == null ? null : (Xpp3Dom) plugin.getConfiguration(); } private MavenUtils(); } | MavenUtils { public static Xpp3Dom getPluginConfiguration(MavenProject mavenProject, String pluginKey) { final Plugin plugin = getPluginFromMavenModel(mavenProject.getModel(), pluginKey); return plugin == null ? null : (Xpp3Dom) plugin.getConfiguration(); } private MavenUtils(); static Xpp3Dom getPluginConfiguration(MavenProject mavenProject, String pluginKey); } | MavenUtils { public static Xpp3Dom getPluginConfiguration(MavenProject mavenProject, String pluginKey) { final Plugin plugin = getPluginFromMavenModel(mavenProject.getModel(), pluginKey); return plugin == null ? null : (Xpp3Dom) plugin.getConfiguration(); } private MavenUtils(); static Xpp3Dom getPluginConfiguration(MavenProject mavenProject, String pluginKey); } |
@Test public void testHandleSelectOnePromoteYesNo() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("promote", "Input the {{global_property1}} value(***{{default}}***):"), new DefaultMapEntry<>("resource", "App"), new DefaultMapEntry<>("default", "false"), new DefaultMapEntry<>("property", "isPublic"), new DefaultMapEntry<>("required", false), }); templates.put("testId1", map); when(reader.readLine()).thenReturn("Y").thenReturn("N"); String result = wrapper.handleSelectOne("testId1", Collections.singletonList("foo"), null, String::toString); assertEquals("foo", result); result = wrapper.handleSelectOne("testId1", Collections.singletonList("foo"), null, String::toString); assertNull(result); map.put("required", true); try { wrapper.handleSelectOne("testId1", Collections.singletonList("foo"), null, String::toString); fail("Should throw SpringConfigurationException."); } catch (SpringConfigurationException ex) { } } | public <T> T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc) throws IOException, SpringConfigurationException { final Map<String, Object> variables = createVariableTables(templateId); final boolean isRequired = TemplateUtils.evalBoolean("required", variables); if (options.size() == 0) { if (isRequired) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return null; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options.get(0); } if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), isRequired, isRequired)) { if (isRequired) { throw new SpringConfigurationException(TemplateUtils.evalText("message.select_none", variables)); } return null; } return options.get(0); } if (defaultEntity == null && variables.containsKey("default_index")) { defaultEntity = options.get((Integer) variables.get("default_index")); } return prompt.promoteSingleEntity(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), options, defaultEntity, getNameFunc, isRequired); } | PromptWrapper { public <T> T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc) throws IOException, SpringConfigurationException { final Map<String, Object> variables = createVariableTables(templateId); final boolean isRequired = TemplateUtils.evalBoolean("required", variables); if (options.size() == 0) { if (isRequired) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return null; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options.get(0); } if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), isRequired, isRequired)) { if (isRequired) { throw new SpringConfigurationException(TemplateUtils.evalText("message.select_none", variables)); } return null; } return options.get(0); } if (defaultEntity == null && variables.containsKey("default_index")) { defaultEntity = options.get((Integer) variables.get("default_index")); } return prompt.promoteSingleEntity(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), options, defaultEntity, getNameFunc, isRequired); } } | PromptWrapper { public <T> T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc) throws IOException, SpringConfigurationException { final Map<String, Object> variables = createVariableTables(templateId); final boolean isRequired = TemplateUtils.evalBoolean("required", variables); if (options.size() == 0) { if (isRequired) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return null; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options.get(0); } if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), isRequired, isRequired)) { if (isRequired) { throw new SpringConfigurationException(TemplateUtils.evalText("message.select_none", variables)); } return null; } return options.get(0); } if (defaultEntity == null && variables.containsKey("default_index")) { defaultEntity = options.get((Integer) variables.get("default_index")); } return prompt.promoteSingleEntity(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), options, defaultEntity, getNameFunc, isRequired); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); } | PromptWrapper { public <T> T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc) throws IOException, SpringConfigurationException { final Map<String, Object> variables = createVariableTables(templateId); final boolean isRequired = TemplateUtils.evalBoolean("required", variables); if (options.size() == 0) { if (isRequired) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return null; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options.get(0); } if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), isRequired, isRequired)) { if (isRequired) { throw new SpringConfigurationException(TemplateUtils.evalText("message.select_none", variables)); } return null; } return options.get(0); } if (defaultEntity == null && variables.containsKey("default_index")) { defaultEntity = options.get((Integer) variables.get("default_index")); } return prompt.promoteSingleEntity(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), options, defaultEntity, getNameFunc, isRequired); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } | PromptWrapper { public <T> T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc) throws IOException, SpringConfigurationException { final Map<String, Object> variables = createVariableTables(templateId); final boolean isRequired = TemplateUtils.evalBoolean("required", variables); if (options.size() == 0) { if (isRequired) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return null; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options.get(0); } if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), isRequired, isRequired)) { if (isRequired) { throw new SpringConfigurationException(TemplateUtils.evalText("message.select_none", variables)); } return null; } return options.get(0); } if (defaultEntity == null && variables.containsKey("default_index")) { defaultEntity = options.get((Integer) variables.get("default_index")); } return prompt.promoteSingleEntity(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), options, defaultEntity, getNameFunc, isRequired); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } |
@Test public void testHandleSelectMany() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("promote", "Input the {{global_property1}} value(***{{default}}***):"), new DefaultMapEntry<>("resource", "App"), new DefaultMapEntry<>("default", "false"), new DefaultMapEntry<>("property", "isPublic"), new DefaultMapEntry<>("required", true), }); templates.put("testId1", map); when(reader.readLine()).thenReturn("1"); List<String> result = wrapper.handleMultipleCase("testId1", Arrays.asList("foo", "bar"), String::toString); assertEquals("foo", StringUtils.join(result.toArray(), ',')); when(reader.readLine()).thenReturn("").thenReturn("100").thenReturn("1-2"); result = wrapper.handleMultipleCase("testId1", Arrays.asList("bar", "foo"), String::toString); assertEquals("bar,foo", StringUtils.join(result.toArray(), ',')); map.put("allow_empty", false); map.put("message", Collections.singletonMap("empty_options", "Option is empty")); try { wrapper.handleMultipleCase("testId1", Collections.emptyList(), String::toString); fail("Should report error when required resources are not available."); } catch (NoResourcesAvailableException ex) { } map.put("allow_empty", true); assertTrue(wrapper.handleMultipleCase("testId1", Collections.emptyList(), String::toString).isEmpty()); } | public <T> List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc) throws IOException, NoResourcesAvailableException { final Map<String, Object> variables = createVariableTables(templateId); final boolean allowEmpty = TemplateUtils.evalBoolean("allow_empty", variables); if (options.size() == 0) { if (!allowEmpty) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } else { final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return options; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); final boolean defaultSelected = TemplateUtils.evalBoolean("default_selected", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options; } else { if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), defaultSelected, false)) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return Collections.emptyList(); } return options; } } final List<T> selectedEntities = prompt.promoteMultipleEntities(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), TemplateUtils.evalText("promote.header", variables), options, getNameFunc, allowEmpty, defaultSelected ? "to select ALL" : "to select NONE", defaultSelected ? options : Collections.emptyList()); if (selectedEntities.isEmpty()) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return selectedEntities; } | PromptWrapper { public <T> List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc) throws IOException, NoResourcesAvailableException { final Map<String, Object> variables = createVariableTables(templateId); final boolean allowEmpty = TemplateUtils.evalBoolean("allow_empty", variables); if (options.size() == 0) { if (!allowEmpty) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } else { final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return options; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); final boolean defaultSelected = TemplateUtils.evalBoolean("default_selected", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options; } else { if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), defaultSelected, false)) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return Collections.emptyList(); } return options; } } final List<T> selectedEntities = prompt.promoteMultipleEntities(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), TemplateUtils.evalText("promote.header", variables), options, getNameFunc, allowEmpty, defaultSelected ? "to select ALL" : "to select NONE", defaultSelected ? options : Collections.emptyList()); if (selectedEntities.isEmpty()) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return selectedEntities; } } | PromptWrapper { public <T> List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc) throws IOException, NoResourcesAvailableException { final Map<String, Object> variables = createVariableTables(templateId); final boolean allowEmpty = TemplateUtils.evalBoolean("allow_empty", variables); if (options.size() == 0) { if (!allowEmpty) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } else { final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return options; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); final boolean defaultSelected = TemplateUtils.evalBoolean("default_selected", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options; } else { if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), defaultSelected, false)) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return Collections.emptyList(); } return options; } } final List<T> selectedEntities = prompt.promoteMultipleEntities(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), TemplateUtils.evalText("promote.header", variables), options, getNameFunc, allowEmpty, defaultSelected ? "to select ALL" : "to select NONE", defaultSelected ? options : Collections.emptyList()); if (selectedEntities.isEmpty()) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return selectedEntities; } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); } | PromptWrapper { public <T> List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc) throws IOException, NoResourcesAvailableException { final Map<String, Object> variables = createVariableTables(templateId); final boolean allowEmpty = TemplateUtils.evalBoolean("allow_empty", variables); if (options.size() == 0) { if (!allowEmpty) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } else { final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return options; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); final boolean defaultSelected = TemplateUtils.evalBoolean("default_selected", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options; } else { if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), defaultSelected, false)) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return Collections.emptyList(); } return options; } } final List<T> selectedEntities = prompt.promoteMultipleEntities(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), TemplateUtils.evalText("promote.header", variables), options, getNameFunc, allowEmpty, defaultSelected ? "to select ALL" : "to select NONE", defaultSelected ? options : Collections.emptyList()); if (selectedEntities.isEmpty()) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return selectedEntities; } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } | PromptWrapper { public <T> List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc) throws IOException, NoResourcesAvailableException { final Map<String, Object> variables = createVariableTables(templateId); final boolean allowEmpty = TemplateUtils.evalBoolean("allow_empty", variables); if (options.size() == 0) { if (!allowEmpty) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } else { final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return options; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); final boolean defaultSelected = TemplateUtils.evalBoolean("default_selected", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options; } else { if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), defaultSelected, false)) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return Collections.emptyList(); } return options; } } final List<T> selectedEntities = prompt.promoteMultipleEntities(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), TemplateUtils.evalText("promote.header", variables), options, getNameFunc, allowEmpty, defaultSelected ? "to select ALL" : "to select NONE", defaultSelected ? options : Collections.emptyList()); if (selectedEntities.isEmpty()) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return selectedEntities; } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } |
@Test public void testPromoteYesNoForOneOption() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("promote", "Input the {{global_property1}} value(***{{default}}***):"), new DefaultMapEntry<>("resource", "App"), new DefaultMapEntry<>("default", "false"), new DefaultMapEntry<>("property", "isPublic"), new DefaultMapEntry<>("required", true), }); templates.put("testId1", map); when(reader.readLine()).thenReturn("Y"); List<String> result = wrapper.handleMultipleCase("testId1", Collections.singletonList("foo"), String::toString); assertEquals("foo", StringUtils.join(result.toArray(), ',')); when(reader.readLine()).thenReturn("N"); result = wrapper.handleMultipleCase("testId1", Collections.singletonList("foo"), String::toString); assertTrue(result.isEmpty()); when(reader.readLine()).thenReturn(""); map.put("auto_select", true); map.put("default_selected", false); result = wrapper.handleMultipleCase("testId1", Collections.singletonList("foo"), String::toString); assertEquals("foo", StringUtils.join(result.toArray(), ',')); map.put("auto_select", false); map.put("default_selected", true); result = wrapper.handleMultipleCase("testId1", Collections.singletonList("foo"), String::toString); assertEquals("foo", StringUtils.join(result.toArray(), ',')); map.put("default_selected", false); map.put("allow_empty", true); when(reader.readLine()).thenReturn("10-10000"); result = wrapper.handleMultipleCase("testId1", Arrays.asList("foo", "bar"), String::toString); assertTrue(result.isEmpty()); } | public <T> List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc) throws IOException, NoResourcesAvailableException { final Map<String, Object> variables = createVariableTables(templateId); final boolean allowEmpty = TemplateUtils.evalBoolean("allow_empty", variables); if (options.size() == 0) { if (!allowEmpty) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } else { final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return options; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); final boolean defaultSelected = TemplateUtils.evalBoolean("default_selected", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options; } else { if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), defaultSelected, false)) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return Collections.emptyList(); } return options; } } final List<T> selectedEntities = prompt.promoteMultipleEntities(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), TemplateUtils.evalText("promote.header", variables), options, getNameFunc, allowEmpty, defaultSelected ? "to select ALL" : "to select NONE", defaultSelected ? options : Collections.emptyList()); if (selectedEntities.isEmpty()) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return selectedEntities; } | PromptWrapper { public <T> List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc) throws IOException, NoResourcesAvailableException { final Map<String, Object> variables = createVariableTables(templateId); final boolean allowEmpty = TemplateUtils.evalBoolean("allow_empty", variables); if (options.size() == 0) { if (!allowEmpty) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } else { final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return options; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); final boolean defaultSelected = TemplateUtils.evalBoolean("default_selected", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options; } else { if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), defaultSelected, false)) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return Collections.emptyList(); } return options; } } final List<T> selectedEntities = prompt.promoteMultipleEntities(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), TemplateUtils.evalText("promote.header", variables), options, getNameFunc, allowEmpty, defaultSelected ? "to select ALL" : "to select NONE", defaultSelected ? options : Collections.emptyList()); if (selectedEntities.isEmpty()) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return selectedEntities; } } | PromptWrapper { public <T> List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc) throws IOException, NoResourcesAvailableException { final Map<String, Object> variables = createVariableTables(templateId); final boolean allowEmpty = TemplateUtils.evalBoolean("allow_empty", variables); if (options.size() == 0) { if (!allowEmpty) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } else { final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return options; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); final boolean defaultSelected = TemplateUtils.evalBoolean("default_selected", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options; } else { if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), defaultSelected, false)) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return Collections.emptyList(); } return options; } } final List<T> selectedEntities = prompt.promoteMultipleEntities(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), TemplateUtils.evalText("promote.header", variables), options, getNameFunc, allowEmpty, defaultSelected ? "to select ALL" : "to select NONE", defaultSelected ? options : Collections.emptyList()); if (selectedEntities.isEmpty()) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return selectedEntities; } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); } | PromptWrapper { public <T> List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc) throws IOException, NoResourcesAvailableException { final Map<String, Object> variables = createVariableTables(templateId); final boolean allowEmpty = TemplateUtils.evalBoolean("allow_empty", variables); if (options.size() == 0) { if (!allowEmpty) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } else { final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return options; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); final boolean defaultSelected = TemplateUtils.evalBoolean("default_selected", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options; } else { if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), defaultSelected, false)) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return Collections.emptyList(); } return options; } } final List<T> selectedEntities = prompt.promoteMultipleEntities(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), TemplateUtils.evalText("promote.header", variables), options, getNameFunc, allowEmpty, defaultSelected ? "to select ALL" : "to select NONE", defaultSelected ? options : Collections.emptyList()); if (selectedEntities.isEmpty()) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return selectedEntities; } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } | PromptWrapper { public <T> List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc) throws IOException, NoResourcesAvailableException { final Map<String, Object> variables = createVariableTables(templateId); final boolean allowEmpty = TemplateUtils.evalBoolean("allow_empty", variables); if (options.size() == 0) { if (!allowEmpty) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } else { final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return options; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); final boolean defaultSelected = TemplateUtils.evalBoolean("default_selected", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options; } else { if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), defaultSelected, false)) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return Collections.emptyList(); } return options; } } final List<T> selectedEntities = prompt.promoteMultipleEntities(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), TemplateUtils.evalText("promote.header", variables), options, getNameFunc, allowEmpty, defaultSelected ? "to select ALL" : "to select NONE", defaultSelected ? options : Collections.emptyList()); if (selectedEntities.isEmpty()) { final String warningMessage = TemplateUtils.evalText("message.select_none", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } } return selectedEntities; } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } |
@Test public void testConfirmChanges() throws Exception { final Map<String, String> changesToConfirm = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("foo", "bar"), new DefaultMapEntry<>("count", "1"), new DefaultMapEntry<>("blank", ""), new DefaultMapEntry<>("update", "true"), }); final List<MavenProject> projects = new ArrayList<>(); for (int i = 0; i < 10; i++) { final MavenProject proj = mock(MavenProject.class); Mockito.when(proj.getFile()).thenReturn(new File("test" + (i + 1))); projects.add(proj); } when(reader.readLine()).thenReturn(""); wrapper.putCommonVariable("projects", projects); wrapper.confirmChanges(changesToConfirm, () -> 10); wrapper.confirmChanges(changesToConfirm, () -> null); wrapper.confirmChanges(changesToConfirm, () -> 1); when(reader.readLine()).thenReturn("N"); wrapper.confirmChanges(changesToConfirm, () -> { throw new RuntimeException("This function will never be called."); }); } | public void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction) throws IOException { final Map<String, Object> variables = createVariableTables("confirm"); System.out.println(TemplateUtils.evalText("promote.header", variables)); for (final Map.Entry<String, String> entry : changesToConfirm.entrySet()) { if (StringUtils.isNotBlank(entry.getValue())) { printConfirmation(entry.getKey(), entry.getValue()); } } final Boolean userConfirm = prompt.promoteYesNo(TemplateUtils.evalText("promote.footer", variables), TemplateUtils.evalBoolean("default", variables), TemplateUtils.evalBoolean("required", variables)); if (userConfirm == null || !userConfirm) { log.info(TemplateUtils.evalText("message.skip", variables)); return; } final Integer appliedCount = confirmedAction.get(); if (appliedCount == null || appliedCount == 0) { log.info(TemplateUtils.evalText("message.none", variables)); } else if (appliedCount == 1) { log.info(TemplateUtils.evalText("message.one", variables)); } else { log.info(TemplateUtils.evalText("message.many", variables)); } } | PromptWrapper { public void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction) throws IOException { final Map<String, Object> variables = createVariableTables("confirm"); System.out.println(TemplateUtils.evalText("promote.header", variables)); for (final Map.Entry<String, String> entry : changesToConfirm.entrySet()) { if (StringUtils.isNotBlank(entry.getValue())) { printConfirmation(entry.getKey(), entry.getValue()); } } final Boolean userConfirm = prompt.promoteYesNo(TemplateUtils.evalText("promote.footer", variables), TemplateUtils.evalBoolean("default", variables), TemplateUtils.evalBoolean("required", variables)); if (userConfirm == null || !userConfirm) { log.info(TemplateUtils.evalText("message.skip", variables)); return; } final Integer appliedCount = confirmedAction.get(); if (appliedCount == null || appliedCount == 0) { log.info(TemplateUtils.evalText("message.none", variables)); } else if (appliedCount == 1) { log.info(TemplateUtils.evalText("message.one", variables)); } else { log.info(TemplateUtils.evalText("message.many", variables)); } } } | PromptWrapper { public void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction) throws IOException { final Map<String, Object> variables = createVariableTables("confirm"); System.out.println(TemplateUtils.evalText("promote.header", variables)); for (final Map.Entry<String, String> entry : changesToConfirm.entrySet()) { if (StringUtils.isNotBlank(entry.getValue())) { printConfirmation(entry.getKey(), entry.getValue()); } } final Boolean userConfirm = prompt.promoteYesNo(TemplateUtils.evalText("promote.footer", variables), TemplateUtils.evalBoolean("default", variables), TemplateUtils.evalBoolean("required", variables)); if (userConfirm == null || !userConfirm) { log.info(TemplateUtils.evalText("message.skip", variables)); return; } final Integer appliedCount = confirmedAction.get(); if (appliedCount == null || appliedCount == 0) { log.info(TemplateUtils.evalText("message.none", variables)); } else if (appliedCount == 1) { log.info(TemplateUtils.evalText("message.one", variables)); } else { log.info(TemplateUtils.evalText("message.many", variables)); } } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); } | PromptWrapper { public void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction) throws IOException { final Map<String, Object> variables = createVariableTables("confirm"); System.out.println(TemplateUtils.evalText("promote.header", variables)); for (final Map.Entry<String, String> entry : changesToConfirm.entrySet()) { if (StringUtils.isNotBlank(entry.getValue())) { printConfirmation(entry.getKey(), entry.getValue()); } } final Boolean userConfirm = prompt.promoteYesNo(TemplateUtils.evalText("promote.footer", variables), TemplateUtils.evalBoolean("default", variables), TemplateUtils.evalBoolean("required", variables)); if (userConfirm == null || !userConfirm) { log.info(TemplateUtils.evalText("message.skip", variables)); return; } final Integer appliedCount = confirmedAction.get(); if (appliedCount == null || appliedCount == 0) { log.info(TemplateUtils.evalText("message.none", variables)); } else if (appliedCount == 1) { log.info(TemplateUtils.evalText("message.one", variables)); } else { log.info(TemplateUtils.evalText("message.many", variables)); } } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } | PromptWrapper { public void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction) throws IOException { final Map<String, Object> variables = createVariableTables("confirm"); System.out.println(TemplateUtils.evalText("promote.header", variables)); for (final Map.Entry<String, String> entry : changesToConfirm.entrySet()) { if (StringUtils.isNotBlank(entry.getValue())) { printConfirmation(entry.getKey(), entry.getValue()); } } final Boolean userConfirm = prompt.promoteYesNo(TemplateUtils.evalText("promote.footer", variables), TemplateUtils.evalBoolean("default", variables), TemplateUtils.evalBoolean("required", variables)); if (userConfirm == null || !userConfirm) { log.info(TemplateUtils.evalText("message.skip", variables)); return; } final Integer appliedCount = confirmedAction.get(); if (appliedCount == null || appliedCount == 0) { log.info(TemplateUtils.evalText("message.none", variables)); } else if (appliedCount == 1) { log.info(TemplateUtils.evalText("message.one", variables)); } else { log.info(TemplateUtils.evalText("message.many", variables)); } } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } |
@Test public void testClose() throws Exception { final IPrompter prompt = mock(IPrompter.class); Mockito.doThrow(IOException.class).when(prompt).close(); FieldUtils.writeField(wrapper, "prompt", prompt, true); try { wrapper.close(); fail("Should throw IOException"); } catch (IOException ex) { } Mockito.verify(prompt); prompt.close(); } | public void close() throws IOException { this.prompt.close(); } | PromptWrapper { public void close() throws IOException { this.prompt.close(); } } | PromptWrapper { public void close() throws IOException { this.prompt.close(); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); } | PromptWrapper { public void close() throws IOException { this.prompt.close(); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } | PromptWrapper { public void close() throws IOException { this.prompt.close(); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } |
@Test public void testPrettyPrintElementNoNamespace() throws Exception { final String[] lines = TextUtils.splitLines(XmlUtils.prettyPrintElementNoNamespace(propertiesNode)); assertEquals(5, lines.length); assertEquals("<properties>", lines[0]); assertEquals(" <maven.compiler.source>1.8</maven.compiler.source>", lines[1]); assertEquals(" <maven.compiler.target>1.8</maven.compiler.target>", lines[2]); assertEquals(" <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>", lines[3]); assertEquals("</properties>", lines[4]); } | public static String prettyPrintElementNoNamespace(Element node) { removeAllNamespaces(node); try { final StringWriter out = new StringWriter(); final OutputFormat format = OutputFormat.createPrettyPrint(); format.setSuppressDeclaration(true); format.setIndent(" "); format.setPadText(false); final XMLWriter writer = new XMLWriter(out, format); writer.write(node); writer.flush(); return StringUtils.stripStart(out.toString(), null); } catch (IOException e) { throw new RuntimeException("IOException while generating " + "textual representation: " + e.getMessage()); } } | XmlUtils { public static String prettyPrintElementNoNamespace(Element node) { removeAllNamespaces(node); try { final StringWriter out = new StringWriter(); final OutputFormat format = OutputFormat.createPrettyPrint(); format.setSuppressDeclaration(true); format.setIndent(" "); format.setPadText(false); final XMLWriter writer = new XMLWriter(out, format); writer.write(node); writer.flush(); return StringUtils.stripStart(out.toString(), null); } catch (IOException e) { throw new RuntimeException("IOException while generating " + "textual representation: " + e.getMessage()); } } } | XmlUtils { public static String prettyPrintElementNoNamespace(Element node) { removeAllNamespaces(node); try { final StringWriter out = new StringWriter(); final OutputFormat format = OutputFormat.createPrettyPrint(); format.setSuppressDeclaration(true); format.setIndent(" "); format.setPadText(false); final XMLWriter writer = new XMLWriter(out, format); writer.write(node); writer.flush(); return StringUtils.stripStart(out.toString(), null); } catch (IOException e) { throw new RuntimeException("IOException while generating " + "textual representation: " + e.getMessage()); } } private XmlUtils(); } | XmlUtils { public static String prettyPrintElementNoNamespace(Element node) { removeAllNamespaces(node); try { final StringWriter out = new StringWriter(); final OutputFormat format = OutputFormat.createPrettyPrint(); format.setSuppressDeclaration(true); format.setIndent(" "); format.setPadText(false); final XMLWriter writer = new XMLWriter(out, format); writer.write(node); writer.flush(); return StringUtils.stripStart(out.toString(), null); } catch (IOException e) { throw new RuntimeException("IOException while generating " + "textual representation: " + e.getMessage()); } } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); } | XmlUtils { public static String prettyPrintElementNoNamespace(Element node) { removeAllNamespaces(node); try { final StringWriter out = new StringWriter(); final OutputFormat format = OutputFormat.createPrettyPrint(); format.setSuppressDeclaration(true); format.setIndent(" "); format.setPadText(false); final XMLWriter writer = new XMLWriter(out, format); writer.write(node); writer.flush(); return StringUtils.stripStart(out.toString(), null); } catch (IOException e) { throw new RuntimeException("IOException while generating " + "textual representation: " + e.getMessage()); } } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); } |
@Test public void testGetChildValue() { assertEquals("1.8\n", XmlUtils.getChildValue(propertiesNode, "maven.compiler.target")); } | public static String getChildValue(Element element, String attribute) { final Element child = element.element(attribute); return child == null ? null : child.getText(); } | XmlUtils { public static String getChildValue(Element element, String attribute) { final Element child = element.element(attribute); return child == null ? null : child.getText(); } } | XmlUtils { public static String getChildValue(Element element, String attribute) { final Element child = element.element(attribute); return child == null ? null : child.getText(); } private XmlUtils(); } | XmlUtils { public static String getChildValue(Element element, String attribute) { final Element child = element.element(attribute); return child == null ? null : child.getText(); } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); } | XmlUtils { public static String getChildValue(Element element, String attribute) { final Element child = element.element(attribute); return child == null ? null : child.getText(); } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); } |
@Test public void testAddDomWithKeyValue() { XmlUtils.addDomWithKeyValue(propertiesNode, "foo", "bar"); final String[] lines = TextUtils.splitLines(XmlUtils.prettyPrintElementNoNamespace(propertiesNode)); assertEquals(6, lines.length); assertEquals(" <foo>bar</foo>", lines[4]); } | public static void addDomWithKeyValue(Element node, String key, Object value) { final DOMElement newNode = new DOMElement(key); if (value != null) { newNode.setText(value.toString()); } node.add(newNode); } | XmlUtils { public static void addDomWithKeyValue(Element node, String key, Object value) { final DOMElement newNode = new DOMElement(key); if (value != null) { newNode.setText(value.toString()); } node.add(newNode); } } | XmlUtils { public static void addDomWithKeyValue(Element node, String key, Object value) { final DOMElement newNode = new DOMElement(key); if (value != null) { newNode.setText(value.toString()); } node.add(newNode); } private XmlUtils(); } | XmlUtils { public static void addDomWithKeyValue(Element node, String key, Object value) { final DOMElement newNode = new DOMElement(key); if (value != null) { newNode.setText(value.toString()); } node.add(newNode); } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); } | XmlUtils { public static void addDomWithKeyValue(Element node, String key, Object value) { final DOMElement newNode = new DOMElement(key); if (value != null) { newNode.setText(value.toString()); } node.add(newNode); } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); } |
@Test public void testTrimTextBeforeEnd() { XmlUtils.removeAllNamespaces(propertiesNode); XmlUtils.addDomWithKeyValue(propertiesNode, "foo", "bar"); final Namespace ns = propertiesNode.getNamespace(); final Element fooNode = propertiesNode.element(new QName("foo", ns)); propertiesNode.addText(" "); final String xmlBefore = propertiesNode.asXML(); XmlUtils.trimTextBeforeEnd(propertiesNode, fooNode); final String xmlAfter = propertiesNode.asXML(); assertTrue(xmlBefore.contains("</project.build.sourceEncoding>\n <foo>bar</foo> </properties>")); assertTrue(xmlAfter.contains("</project.build.sourceEncoding><foo>bar</foo></properties>")); } | public static void trimTextBeforeEnd(Element parent, Node target) { final List<Node> children = parent.content(); final int index = children.indexOf(target); int pos = index - 1; while (pos >= 0 && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos--); textNode.setText(StringUtils.stripEnd(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } final int size = children.size(); pos = index + 1; while (pos < size && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos++); textNode.setText(StringUtils.stripStart(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } } | XmlUtils { public static void trimTextBeforeEnd(Element parent, Node target) { final List<Node> children = parent.content(); final int index = children.indexOf(target); int pos = index - 1; while (pos >= 0 && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos--); textNode.setText(StringUtils.stripEnd(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } final int size = children.size(); pos = index + 1; while (pos < size && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos++); textNode.setText(StringUtils.stripStart(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } } } | XmlUtils { public static void trimTextBeforeEnd(Element parent, Node target) { final List<Node> children = parent.content(); final int index = children.indexOf(target); int pos = index - 1; while (pos >= 0 && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos--); textNode.setText(StringUtils.stripEnd(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } final int size = children.size(); pos = index + 1; while (pos < size && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos++); textNode.setText(StringUtils.stripStart(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } } private XmlUtils(); } | XmlUtils { public static void trimTextBeforeEnd(Element parent, Node target) { final List<Node> children = parent.content(); final int index = children.indexOf(target); int pos = index - 1; while (pos >= 0 && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos--); textNode.setText(StringUtils.stripEnd(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } final int size = children.size(); pos = index + 1; while (pos < size && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos++); textNode.setText(StringUtils.stripStart(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); } | XmlUtils { public static void trimTextBeforeEnd(Element parent, Node target) { final List<Node> children = parent.content(); final int index = children.indexOf(target); int pos = index - 1; while (pos >= 0 && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos--); textNode.setText(StringUtils.stripEnd(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } final int size = children.size(); pos = index + 1; while (pos < size && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos++); textNode.setText(StringUtils.stripStart(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); } |
@Test public void testEvalBoolean() { assertEquals(Boolean.TRUE, evalBoolean("foo", Collections.singletonMap("foo", "true"))); assertEquals(Boolean.TRUE, evalBoolean("foo", Collections.singletonMap("foo", true))); assertEquals(Boolean.FALSE, evalBoolean("foo", Collections.singletonMap("foo", null))); } | public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } private TemplateUtils(); } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } |
@Test(expected = AzureExecutionException.class) public void checkStageDirectoryExistenceWhenNotExisting() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); doReturn("./NotExistFile").when(mojoSpy).getDeploymentStagingDirectoryPath(); mojoSpy.checkStageDirectoryExistence(); } | protected void checkStageDirectoryExistence() throws AzureExecutionException { final File file = new File(getDeploymentStagingDirectoryPath()); if (!file.exists() || !file.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } Log.info(STAGE_DIR_FOUND + getDeploymentStagingDirectoryPath()); } | RunMojo extends AbstractFunctionMojo { protected void checkStageDirectoryExistence() throws AzureExecutionException { final File file = new File(getDeploymentStagingDirectoryPath()); if (!file.exists() || !file.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } Log.info(STAGE_DIR_FOUND + getDeploymentStagingDirectoryPath()); } } | RunMojo extends AbstractFunctionMojo { protected void checkStageDirectoryExistence() throws AzureExecutionException { final File file = new File(getDeploymentStagingDirectoryPath()); if (!file.exists() || !file.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } Log.info(STAGE_DIR_FOUND + getDeploymentStagingDirectoryPath()); } } | RunMojo extends AbstractFunctionMojo { protected void checkStageDirectoryExistence() throws AzureExecutionException { final File file = new File(getDeploymentStagingDirectoryPath()); if (!file.exists() || !file.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } Log.info(STAGE_DIR_FOUND + getDeploymentStagingDirectoryPath()); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } | RunMojo extends AbstractFunctionMojo { protected void checkStageDirectoryExistence() throws AzureExecutionException { final File file = new File(getDeploymentStagingDirectoryPath()); if (!file.exists() || !file.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } Log.info(STAGE_DIR_FOUND + getDeploymentStagingDirectoryPath()); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } |
@Test public void testEvalBooleanVariable() { final Map<String, Object> map = new HashMap<>(); map.put("foo", "{{bar}}"); map.put("bar", "true"); assertEquals(Boolean.TRUE, evalBoolean("foo", map)); } | public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } private TemplateUtils(); } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } |
@Test public void testEvalBooleanRecursive() { final Map<String, Object> map = new HashMap<>(); map.put("foo", Collections.singletonMap("bar", "true")); assertEquals(Boolean.TRUE, evalBoolean("foo.bar", map)); } | public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } private TemplateUtils(); } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } | TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } |
@Test public void testEvalPlainText() { final Map<String, Object> map = new HashMap<>(); map.put("foo", Collections.singletonMap("bar", "true")); assertEquals("true", evalPlainText("foo.bar", map)); map.put("foo", Collections.singletonMap("bar", true)); assertEquals("true", evalPlainText("foo.bar", map)); } | public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } |
@Test public void testEvalPlainTextVariable() { final Map<String, Object> map = new HashMap<>(); map.put("foo", "{{bar}}"); map.put("bar", "hello world"); assertEquals("hello world", evalPlainText("foo", map)); } | public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } |
@Test public void testEvalText() { final Map<String, Object> map = new HashMap<>(); map.put("foo", "hello ***{{name}}***"); map.put("name", "Jack"); assertEquals(String.format("hello %s", TextUtils.blue("Jack")), evalText("foo", map)); } | public static String evalText(String expr, Map<String, Object> variableMap) { return evalPlainText(expr, variableMap).replaceAll("\\*\\*\\*(.*?)\\*\\*\\*", TextUtils.blue("$1")); } | TemplateUtils { public static String evalText(String expr, Map<String, Object> variableMap) { return evalPlainText(expr, variableMap).replaceAll("\\*\\*\\*(.*?)\\*\\*\\*", TextUtils.blue("$1")); } } | TemplateUtils { public static String evalText(String expr, Map<String, Object> variableMap) { return evalPlainText(expr, variableMap).replaceAll("\\*\\*\\*(.*?)\\*\\*\\*", TextUtils.blue("$1")); } private TemplateUtils(); } | TemplateUtils { public static String evalText(String expr, Map<String, Object> variableMap) { return evalPlainText(expr, variableMap).replaceAll("\\*\\*\\*(.*?)\\*\\*\\*", TextUtils.blue("$1")); } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } | TemplateUtils { public static String evalText(String expr, Map<String, Object> variableMap) { return evalPlainText(expr, variableMap).replaceAll("\\*\\*\\*(.*?)\\*\\*\\*", TextUtils.blue("$1")); } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } |
@Test public void testEndlessEval() { final Map<String, Object> map = new HashMap<>(); map.put("foo", "hello {{name}}"); map.put("name", "{{foo}}"); assertEquals("hello hello hello hello {{name}}", evalPlainText("foo", map)); } | public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } |
@Test public void testBadExpression() { final Map<String, Object> map = new HashMap<>(); map.put("foo", "{{bar}"); map.put("bar", "hello world"); try { evalPlainText("foo", map); fail("Should report error when evaluate text is not valid."); } catch (ParseException ex) { } } | public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } | TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); } |
@Test public void testGetDefaultResources() { final List<Resource> resources = ResourcesUtils.getDefaultResources(); assertEquals(1, resources.size()); final Resource resource = resources.get(0); assertNotNull(resource); assertEquals("${project.basedir}/target", resource.getDirectory()); assertNull(resource.getFiltering()); assertEquals(0, resource.getExcludes().size()); assertEquals(1, resource.getIncludes().size()); assertEquals("*.jar", resource.getIncludes().get(0)); } | public static List<Resource> getDefaultResources() { final Resource resource = new Resource(); resource.setDirectory(DEFAULT_DIRECTORY); resource.addInclude(DEFAULT_INCLUDE); return Collections.singletonList(resource); } | ResourcesUtils { public static List<Resource> getDefaultResources() { final Resource resource = new Resource(); resource.setDirectory(DEFAULT_DIRECTORY); resource.addInclude(DEFAULT_INCLUDE); return Collections.singletonList(resource); } } | ResourcesUtils { public static List<Resource> getDefaultResources() { final Resource resource = new Resource(); resource.setDirectory(DEFAULT_DIRECTORY); resource.addInclude(DEFAULT_INCLUDE); return Collections.singletonList(resource); } private ResourcesUtils(); } | ResourcesUtils { public static List<Resource> getDefaultResources() { final Resource resource = new Resource(); resource.setDirectory(DEFAULT_DIRECTORY); resource.addInclude(DEFAULT_INCLUDE); return Collections.singletonList(resource); } private ResourcesUtils(); static List<Resource> getDefaultResources(); static void applyDefaultResourcesToDom4j(Element root); } | ResourcesUtils { public static List<Resource> getDefaultResources() { final Resource resource = new Resource(); resource.setDirectory(DEFAULT_DIRECTORY); resource.addInclude(DEFAULT_INCLUDE); return Collections.singletonList(resource); } private ResourcesUtils(); static List<Resource> getDefaultResources(); static void applyDefaultResourcesToDom4j(Element root); } |
@Test public void testApplyDefaultResourcesToDom4j() throws Exception { final SAXReader reader = new SAXReader(); final Document document = reader.read(this.getClass().getClassLoader().getResourceAsStream("test-2.xml")); final Element rootNode = document.getRootElement(); ResourcesUtils.applyDefaultResourcesToDom4j(rootNode); assertTrue(rootNode.asXML().contains( "<resources><resource><filtering/><mergeId/><targetPath/><directory>${project.basedir}/target</directory>" + "<includes><include>*.jar</include></includes></resource></resources>")); } | public static void applyDefaultResourcesToDom4j(Element root) { final DOMElement resourceRootNode = new DOMElement("resources"); for (final Resource resource : getDefaultResources()) { final DOMElement resourceNode = new DOMElement("resource"); XmlUtils.addDomWithKeyValue(resourceNode, "filtering", resource.getFiltering()); XmlUtils.addDomWithKeyValue(resourceNode, "mergeId", resource.getMergeId()); XmlUtils.addDomWithKeyValue(resourceNode, "targetPath", resource.getTargetPath()); XmlUtils.addDomWithKeyValue(resourceNode, "directory", resource.getDirectory()); XmlUtils.addDomWithValueList(resourceNode, "includes", "include", resource.getIncludes()); XmlUtils.addDomWithValueList(resourceNode, "excludes", "exclude", resource.getExcludes()); resourceRootNode.add(resourceNode); } root.add(resourceRootNode); } | ResourcesUtils { public static void applyDefaultResourcesToDom4j(Element root) { final DOMElement resourceRootNode = new DOMElement("resources"); for (final Resource resource : getDefaultResources()) { final DOMElement resourceNode = new DOMElement("resource"); XmlUtils.addDomWithKeyValue(resourceNode, "filtering", resource.getFiltering()); XmlUtils.addDomWithKeyValue(resourceNode, "mergeId", resource.getMergeId()); XmlUtils.addDomWithKeyValue(resourceNode, "targetPath", resource.getTargetPath()); XmlUtils.addDomWithKeyValue(resourceNode, "directory", resource.getDirectory()); XmlUtils.addDomWithValueList(resourceNode, "includes", "include", resource.getIncludes()); XmlUtils.addDomWithValueList(resourceNode, "excludes", "exclude", resource.getExcludes()); resourceRootNode.add(resourceNode); } root.add(resourceRootNode); } } | ResourcesUtils { public static void applyDefaultResourcesToDom4j(Element root) { final DOMElement resourceRootNode = new DOMElement("resources"); for (final Resource resource : getDefaultResources()) { final DOMElement resourceNode = new DOMElement("resource"); XmlUtils.addDomWithKeyValue(resourceNode, "filtering", resource.getFiltering()); XmlUtils.addDomWithKeyValue(resourceNode, "mergeId", resource.getMergeId()); XmlUtils.addDomWithKeyValue(resourceNode, "targetPath", resource.getTargetPath()); XmlUtils.addDomWithKeyValue(resourceNode, "directory", resource.getDirectory()); XmlUtils.addDomWithValueList(resourceNode, "includes", "include", resource.getIncludes()); XmlUtils.addDomWithValueList(resourceNode, "excludes", "exclude", resource.getExcludes()); resourceRootNode.add(resourceNode); } root.add(resourceRootNode); } private ResourcesUtils(); } | ResourcesUtils { public static void applyDefaultResourcesToDom4j(Element root) { final DOMElement resourceRootNode = new DOMElement("resources"); for (final Resource resource : getDefaultResources()) { final DOMElement resourceNode = new DOMElement("resource"); XmlUtils.addDomWithKeyValue(resourceNode, "filtering", resource.getFiltering()); XmlUtils.addDomWithKeyValue(resourceNode, "mergeId", resource.getMergeId()); XmlUtils.addDomWithKeyValue(resourceNode, "targetPath", resource.getTargetPath()); XmlUtils.addDomWithKeyValue(resourceNode, "directory", resource.getDirectory()); XmlUtils.addDomWithValueList(resourceNode, "includes", "include", resource.getIncludes()); XmlUtils.addDomWithValueList(resourceNode, "excludes", "exclude", resource.getExcludes()); resourceRootNode.add(resourceNode); } root.add(resourceRootNode); } private ResourcesUtils(); static List<Resource> getDefaultResources(); static void applyDefaultResourcesToDom4j(Element root); } | ResourcesUtils { public static void applyDefaultResourcesToDom4j(Element root) { final DOMElement resourceRootNode = new DOMElement("resources"); for (final Resource resource : getDefaultResources()) { final DOMElement resourceNode = new DOMElement("resource"); XmlUtils.addDomWithKeyValue(resourceNode, "filtering", resource.getFiltering()); XmlUtils.addDomWithKeyValue(resourceNode, "mergeId", resource.getMergeId()); XmlUtils.addDomWithKeyValue(resourceNode, "targetPath", resource.getTargetPath()); XmlUtils.addDomWithKeyValue(resourceNode, "directory", resource.getDirectory()); XmlUtils.addDomWithValueList(resourceNode, "includes", "include", resource.getIncludes()); XmlUtils.addDomWithValueList(resourceNode, "excludes", "exclude", resource.getExcludes()); resourceRootNode.add(resourceNode); } root.add(resourceRootNode); } private ResourcesUtils(); static List<Resource> getDefaultResources(); static void applyDefaultResourcesToDom4j(Element root); } |
@Test public void testCheckProjectPackaging() throws MojoExecutionException { final MavenProject mockProject = mock(MavenProject.class); doReturn("jar").when(mockProject).getPackaging(); assertTrue(checkProjectPackaging(mockProject)); doReturn("pom").when(mockProject).getPackaging(); assertFalse(checkProjectPackaging(mockProject)); doReturn("war").when(mockProject).getPackaging(); try { checkProjectPackaging(mockProject); fail("Check project packaging should throw exception when project packing is war"); } catch (MojoExecutionException exception) { } } | protected boolean checkProjectPackaging(MavenProject project) throws MojoExecutionException { if (Utils.isJarPackagingProject(project)) { return true; } else if (Utils.isPomPackagingProject(project)) { getLog().info(PROJECT_SKIP); return false; } else { throw new MojoExecutionException(String.format(PROJECT_NOT_SUPPORT, project.getPackaging())); } } | DeployMojo extends AbstractSpringMojo { protected boolean checkProjectPackaging(MavenProject project) throws MojoExecutionException { if (Utils.isJarPackagingProject(project)) { return true; } else if (Utils.isPomPackagingProject(project)) { getLog().info(PROJECT_SKIP); return false; } else { throw new MojoExecutionException(String.format(PROJECT_NOT_SUPPORT, project.getPackaging())); } } } | DeployMojo extends AbstractSpringMojo { protected boolean checkProjectPackaging(MavenProject project) throws MojoExecutionException { if (Utils.isJarPackagingProject(project)) { return true; } else if (Utils.isPomPackagingProject(project)) { getLog().info(PROJECT_SKIP); return false; } else { throw new MojoExecutionException(String.format(PROJECT_NOT_SUPPORT, project.getPackaging())); } } } | DeployMojo extends AbstractSpringMojo { protected boolean checkProjectPackaging(MavenProject project) throws MojoExecutionException { if (Utils.isJarPackagingProject(project)) { return true; } else if (Utils.isPomPackagingProject(project)) { getLog().info(PROJECT_SKIP); return false; } else { throw new MojoExecutionException(String.format(PROJECT_NOT_SUPPORT, project.getPackaging())); } } } | DeployMojo extends AbstractSpringMojo { protected boolean checkProjectPackaging(MavenProject project) throws MojoExecutionException { if (Utils.isJarPackagingProject(project)) { return true; } else if (Utils.isPomPackagingProject(project)) { getLog().info(PROJECT_SKIP); return false; } else { throw new MojoExecutionException(String.format(PROJECT_NOT_SUPPORT, project.getPackaging())); } } } |
@Test public void checkRuntimeExistence() throws Exception { final RunMojo mojo = getMojoFromPom(); final CommandHandler commandHandlerMock = mock(CommandHandlerImpl.class); mojo.checkRuntimeExistence(commandHandlerMock); verify(commandHandlerMock, times(1)) .runCommandWithReturnCodeCheck( mojo.getCheckRuntimeCommand(), false, null, CommandUtils.getDefaultValidReturnCodes(), RUNTIME_NOT_FOUND ); } | protected void checkRuntimeExistence(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getCheckRuntimeCommand(), false, null, CommandUtils.getDefaultValidReturnCodes(), RUNTIME_NOT_FOUND ); Log.info(RUNTIME_FOUND); } | RunMojo extends AbstractFunctionMojo { protected void checkRuntimeExistence(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getCheckRuntimeCommand(), false, null, CommandUtils.getDefaultValidReturnCodes(), RUNTIME_NOT_FOUND ); Log.info(RUNTIME_FOUND); } } | RunMojo extends AbstractFunctionMojo { protected void checkRuntimeExistence(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getCheckRuntimeCommand(), false, null, CommandUtils.getDefaultValidReturnCodes(), RUNTIME_NOT_FOUND ); Log.info(RUNTIME_FOUND); } } | RunMojo extends AbstractFunctionMojo { protected void checkRuntimeExistence(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getCheckRuntimeCommand(), false, null, CommandUtils.getDefaultValidReturnCodes(), RUNTIME_NOT_FOUND ); Log.info(RUNTIME_FOUND); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } | RunMojo extends AbstractFunctionMojo { protected void checkRuntimeExistence(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getCheckRuntimeCommand(), false, null, CommandUtils.getDefaultValidReturnCodes(), RUNTIME_NOT_FOUND ); Log.info(RUNTIME_FOUND); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } |
@Test public void getClusterByName() { final ServiceResourceInner mockCluster = mock(ServiceResourceInner.class); doReturn("existCluster").when(mockCluster).name(); final List<ServiceResourceInner> mockClusterList = new ArrayList<>(); mockClusterList.add(mockCluster); doReturn(mockClusterList).when(spyClient).getAvailableClusters(); assertSame(spyClient.getClusterByName("existCluster"), mockCluster); try { spyClient.getClusterByName("unExistCluster"); fail("Should throw IPE when cluster doesn't exist"); } catch (InvalidParameterException e) { } } | public ServiceResourceInner getClusterByName(String cluster) { final List<ServiceResourceInner> clusterList = getAvailableClusters(); return clusterList.stream().filter(appClusterResourceInner -> appClusterResourceInner.name().equals(cluster)) .findFirst() .orElseThrow(() -> new InvalidParameterException(String.format(NO_CLUSTER, cluster, subscriptionId))); } | SpringServiceClient { public ServiceResourceInner getClusterByName(String cluster) { final List<ServiceResourceInner> clusterList = getAvailableClusters(); return clusterList.stream().filter(appClusterResourceInner -> appClusterResourceInner.name().equals(cluster)) .findFirst() .orElseThrow(() -> new InvalidParameterException(String.format(NO_CLUSTER, cluster, subscriptionId))); } } | SpringServiceClient { public ServiceResourceInner getClusterByName(String cluster) { final List<ServiceResourceInner> clusterList = getAvailableClusters(); return clusterList.stream().filter(appClusterResourceInner -> appClusterResourceInner.name().equals(cluster)) .findFirst() .orElseThrow(() -> new InvalidParameterException(String.format(NO_CLUSTER, cluster, subscriptionId))); } SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent); SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent, LogLevel logLevel); } | SpringServiceClient { public ServiceResourceInner getClusterByName(String cluster) { final List<ServiceResourceInner> clusterList = getAvailableClusters(); return clusterList.stream().filter(appClusterResourceInner -> appClusterResourceInner.name().equals(cluster)) .findFirst() .orElseThrow(() -> new InvalidParameterException(String.format(NO_CLUSTER, cluster, subscriptionId))); } SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent); SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent, LogLevel logLevel); SpringAppClient newSpringAppClient(String subscriptionId, String cluster, String app); SpringAppClient newSpringAppClient(SpringConfiguration configuration); List<ServiceResourceInner> getAvailableClusters(); ServiceResourceInner getClusterByName(String cluster); String getResourceGroupByCluster(String clusterName); String getResourceGroupByCluster(ServiceResourceInner cluster); String getSubscriptionId(); AppPlatformManager getSpringManager(); } | SpringServiceClient { public ServiceResourceInner getClusterByName(String cluster) { final List<ServiceResourceInner> clusterList = getAvailableClusters(); return clusterList.stream().filter(appClusterResourceInner -> appClusterResourceInner.name().equals(cluster)) .findFirst() .orElseThrow(() -> new InvalidParameterException(String.format(NO_CLUSTER, cluster, subscriptionId))); } SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent); SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent, LogLevel logLevel); SpringAppClient newSpringAppClient(String subscriptionId, String cluster, String app); SpringAppClient newSpringAppClient(SpringConfiguration configuration); List<ServiceResourceInner> getAvailableClusters(); ServiceResourceInner getClusterByName(String cluster); String getResourceGroupByCluster(String clusterName); String getResourceGroupByCluster(ServiceResourceInner cluster); String getSubscriptionId(); AppPlatformManager getSpringManager(); } |
@Test public void getResourceGroupByCluster() { final ServiceResourceInner mockCluster = mock(ServiceResourceInner.class); doReturn("/resourceGroups/test").when(mockCluster).id(); doReturn(mockCluster).when(spyClient).getClusterByName(any()); assertEquals("test", spyClient.getResourceGroupByCluster("cluster")); } | public String getResourceGroupByCluster(String clusterName) { final ServiceResourceInner cluster = getClusterByName(clusterName); return this.getResourceGroupByCluster(cluster); } | SpringServiceClient { public String getResourceGroupByCluster(String clusterName) { final ServiceResourceInner cluster = getClusterByName(clusterName); return this.getResourceGroupByCluster(cluster); } } | SpringServiceClient { public String getResourceGroupByCluster(String clusterName) { final ServiceResourceInner cluster = getClusterByName(clusterName); return this.getResourceGroupByCluster(cluster); } SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent); SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent, LogLevel logLevel); } | SpringServiceClient { public String getResourceGroupByCluster(String clusterName) { final ServiceResourceInner cluster = getClusterByName(clusterName); return this.getResourceGroupByCluster(cluster); } SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent); SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent, LogLevel logLevel); SpringAppClient newSpringAppClient(String subscriptionId, String cluster, String app); SpringAppClient newSpringAppClient(SpringConfiguration configuration); List<ServiceResourceInner> getAvailableClusters(); ServiceResourceInner getClusterByName(String cluster); String getResourceGroupByCluster(String clusterName); String getResourceGroupByCluster(ServiceResourceInner cluster); String getSubscriptionId(); AppPlatformManager getSpringManager(); } | SpringServiceClient { public String getResourceGroupByCluster(String clusterName) { final ServiceResourceInner cluster = getClusterByName(clusterName); return this.getResourceGroupByCluster(cluster); } SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent); SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent, LogLevel logLevel); SpringAppClient newSpringAppClient(String subscriptionId, String cluster, String app); SpringAppClient newSpringAppClient(SpringConfiguration configuration); List<ServiceResourceInner> getAvailableClusters(); ServiceResourceInner getClusterByName(String cluster); String getResourceGroupByCluster(String clusterName); String getResourceGroupByCluster(ServiceResourceInner cluster); String getSubscriptionId(); AppPlatformManager getSpringManager(); } |
@Test public void testSaveXml() throws Exception { final File pomFile = new File(this.getClass().getClassLoader().getResource("pom-4.xml").getFile()); final File tempFile = Files.createTempFile("azure-spring-cloud-plugin-test", ".xml").toFile(); FileUtils.copyFile(pomFile, tempFile); final Model model = TestHelper.readMavenModel(tempFile); final MavenProject project = mock(MavenProject.class); when(project.getModel()).thenReturn(model); when(project.getFile()).thenReturn(tempFile); final AppSettings app = new AppSettings(); app.setSubscriptionId("subscriptionId1"); app.setClusterName("clusterName1"); app.setAppName("appName1"); app.setPublic("true"); final DeploymentSettings deploy = new DeploymentSettings(); deploy.setCpu("1"); deploy.setMemoryInGB("2"); deploy.setInstanceCount("3"); deploy.setRuntimeVersion("8"); deploy.setJvmOptions("jvmOptions1"); final Plugin plugin = model.getBuild().getPlugins().get(0); final PluginDescriptor pd = mock(PluginDescriptor.class); when(pd.getGroupId()).thenReturn(plugin.getGroupId()); when(pd.getArtifactId()).thenReturn(plugin.getArtifactId()); when(pd.getVersion()).thenReturn(plugin.getVersion()); final PomXmlUpdater updater = new PomXmlUpdater(project, pd); updater.updateSettings(app, deploy); final String updatedXml = FileUtils.readFileToString(tempFile); assertTrue(updatedXml.contains("<maven.compiler.target>1.8\n" + " </maven.compiler.target>")); assertTrue(updatedXml.contains("<configuration>\n" + " <subscriptionId>subscriptionId1</subscriptionId>\n" + " <clusterName>clusterName1</clusterName>\n" + " <appName>appName1</appName>\n" + " <isPublic>true</isPublic>\n" + " <deployment>\n" + " <cpu>1</cpu>\n" + " <memoryInGB>2</memoryInGB>\n" + " <instanceCount>3</instanceCount>\n" + " <jvmOptions>jvmOptions1</jvmOptions>\n" + " <runtimeVersion>8</runtimeVersion>\n" + " <resources>\n" + " <resource>\n" + " <filtering/>\n" + " <mergeId/>\n" + " <targetPath/>\n" + " <directory>${project.basedir}/target</directory>\n" + " <includes>\n" + " <include>*.jar</include>\n" + " </includes>\n" + " </resource>\n" + " </resources>\n" + " </deployment>\n" + " </configuration>")); tempFile.delete(); } | public void updateSettings(AppSettings app, DeploymentSettings deploy) throws DocumentException, IOException { final File pom = this.project.getFile(); final SAXReader reader = new CustomSAXReader(); reader.setDocumentFactory(new LocatorAwareDocumentFactory()); final Document doc = reader.read(new InputStreamReader(new FileInputStream(pom))); final Element pluginsNode = createToPath(doc.getRootElement(), "build", "plugins"); Element springPluginNode = null; for (final Element element : pluginsNode.elements()) { final String groupId = XmlUtils.getChildValue(element, "groupId"); final String artifactId = XmlUtils.getChildValue(element, "artifactId"); final String version = XmlUtils.getChildValue(element, "version"); if (plugin.getGroupId().equals(groupId) && plugin.getArtifactId().equals(artifactId) && (version == null || StringUtils.equals(plugin.getVersion(), version))) { springPluginNode = element; } } if (springPluginNode == null) { springPluginNode = createMavenSpringPluginNode(pluginsNode); } Element newNode; if (app != null || deploy != null) { final Element configurationNode = createToPath(springPluginNode, "configuration"); if (app != null) { app.applyToDom4j(configurationNode); } if (deploy != null) { final Element deployNode = createToPath(configurationNode, "deployment"); deploy.applyToDom4j(deployNode); ResourcesUtils.applyDefaultResourcesToDom4j(deployNode); } newNode = configurationNode; } else { newNode = springPluginNode; } while (!(newNode.getParent() instanceof LocationAwareElement)) { newNode = newNode.getParent(); } FileUtils.fileWrite(pom, formatElement(FileUtils.fileRead(pom), (LocationAwareElement) newNode.getParent(), newNode)); } | PomXmlUpdater { public void updateSettings(AppSettings app, DeploymentSettings deploy) throws DocumentException, IOException { final File pom = this.project.getFile(); final SAXReader reader = new CustomSAXReader(); reader.setDocumentFactory(new LocatorAwareDocumentFactory()); final Document doc = reader.read(new InputStreamReader(new FileInputStream(pom))); final Element pluginsNode = createToPath(doc.getRootElement(), "build", "plugins"); Element springPluginNode = null; for (final Element element : pluginsNode.elements()) { final String groupId = XmlUtils.getChildValue(element, "groupId"); final String artifactId = XmlUtils.getChildValue(element, "artifactId"); final String version = XmlUtils.getChildValue(element, "version"); if (plugin.getGroupId().equals(groupId) && plugin.getArtifactId().equals(artifactId) && (version == null || StringUtils.equals(plugin.getVersion(), version))) { springPluginNode = element; } } if (springPluginNode == null) { springPluginNode = createMavenSpringPluginNode(pluginsNode); } Element newNode; if (app != null || deploy != null) { final Element configurationNode = createToPath(springPluginNode, "configuration"); if (app != null) { app.applyToDom4j(configurationNode); } if (deploy != null) { final Element deployNode = createToPath(configurationNode, "deployment"); deploy.applyToDom4j(deployNode); ResourcesUtils.applyDefaultResourcesToDom4j(deployNode); } newNode = configurationNode; } else { newNode = springPluginNode; } while (!(newNode.getParent() instanceof LocationAwareElement)) { newNode = newNode.getParent(); } FileUtils.fileWrite(pom, formatElement(FileUtils.fileRead(pom), (LocationAwareElement) newNode.getParent(), newNode)); } } | PomXmlUpdater { public void updateSettings(AppSettings app, DeploymentSettings deploy) throws DocumentException, IOException { final File pom = this.project.getFile(); final SAXReader reader = new CustomSAXReader(); reader.setDocumentFactory(new LocatorAwareDocumentFactory()); final Document doc = reader.read(new InputStreamReader(new FileInputStream(pom))); final Element pluginsNode = createToPath(doc.getRootElement(), "build", "plugins"); Element springPluginNode = null; for (final Element element : pluginsNode.elements()) { final String groupId = XmlUtils.getChildValue(element, "groupId"); final String artifactId = XmlUtils.getChildValue(element, "artifactId"); final String version = XmlUtils.getChildValue(element, "version"); if (plugin.getGroupId().equals(groupId) && plugin.getArtifactId().equals(artifactId) && (version == null || StringUtils.equals(plugin.getVersion(), version))) { springPluginNode = element; } } if (springPluginNode == null) { springPluginNode = createMavenSpringPluginNode(pluginsNode); } Element newNode; if (app != null || deploy != null) { final Element configurationNode = createToPath(springPluginNode, "configuration"); if (app != null) { app.applyToDom4j(configurationNode); } if (deploy != null) { final Element deployNode = createToPath(configurationNode, "deployment"); deploy.applyToDom4j(deployNode); ResourcesUtils.applyDefaultResourcesToDom4j(deployNode); } newNode = configurationNode; } else { newNode = springPluginNode; } while (!(newNode.getParent() instanceof LocationAwareElement)) { newNode = newNode.getParent(); } FileUtils.fileWrite(pom, formatElement(FileUtils.fileRead(pom), (LocationAwareElement) newNode.getParent(), newNode)); } PomXmlUpdater(MavenProject project, PluginDescriptor plugin); } | PomXmlUpdater { public void updateSettings(AppSettings app, DeploymentSettings deploy) throws DocumentException, IOException { final File pom = this.project.getFile(); final SAXReader reader = new CustomSAXReader(); reader.setDocumentFactory(new LocatorAwareDocumentFactory()); final Document doc = reader.read(new InputStreamReader(new FileInputStream(pom))); final Element pluginsNode = createToPath(doc.getRootElement(), "build", "plugins"); Element springPluginNode = null; for (final Element element : pluginsNode.elements()) { final String groupId = XmlUtils.getChildValue(element, "groupId"); final String artifactId = XmlUtils.getChildValue(element, "artifactId"); final String version = XmlUtils.getChildValue(element, "version"); if (plugin.getGroupId().equals(groupId) && plugin.getArtifactId().equals(artifactId) && (version == null || StringUtils.equals(plugin.getVersion(), version))) { springPluginNode = element; } } if (springPluginNode == null) { springPluginNode = createMavenSpringPluginNode(pluginsNode); } Element newNode; if (app != null || deploy != null) { final Element configurationNode = createToPath(springPluginNode, "configuration"); if (app != null) { app.applyToDom4j(configurationNode); } if (deploy != null) { final Element deployNode = createToPath(configurationNode, "deployment"); deploy.applyToDom4j(deployNode); ResourcesUtils.applyDefaultResourcesToDom4j(deployNode); } newNode = configurationNode; } else { newNode = springPluginNode; } while (!(newNode.getParent() instanceof LocationAwareElement)) { newNode = newNode.getParent(); } FileUtils.fileWrite(pom, formatElement(FileUtils.fileRead(pom), (LocationAwareElement) newNode.getParent(), newNode)); } PomXmlUpdater(MavenProject project, PluginDescriptor plugin); void updateSettings(AppSettings app, DeploymentSettings deploy); } | PomXmlUpdater { public void updateSettings(AppSettings app, DeploymentSettings deploy) throws DocumentException, IOException { final File pom = this.project.getFile(); final SAXReader reader = new CustomSAXReader(); reader.setDocumentFactory(new LocatorAwareDocumentFactory()); final Document doc = reader.read(new InputStreamReader(new FileInputStream(pom))); final Element pluginsNode = createToPath(doc.getRootElement(), "build", "plugins"); Element springPluginNode = null; for (final Element element : pluginsNode.elements()) { final String groupId = XmlUtils.getChildValue(element, "groupId"); final String artifactId = XmlUtils.getChildValue(element, "artifactId"); final String version = XmlUtils.getChildValue(element, "version"); if (plugin.getGroupId().equals(groupId) && plugin.getArtifactId().equals(artifactId) && (version == null || StringUtils.equals(plugin.getVersion(), version))) { springPluginNode = element; } } if (springPluginNode == null) { springPluginNode = createMavenSpringPluginNode(pluginsNode); } Element newNode; if (app != null || deploy != null) { final Element configurationNode = createToPath(springPluginNode, "configuration"); if (app != null) { app.applyToDom4j(configurationNode); } if (deploy != null) { final Element deployNode = createToPath(configurationNode, "deployment"); deploy.applyToDom4j(deployNode); ResourcesUtils.applyDefaultResourcesToDom4j(deployNode); } newNode = configurationNode; } else { newNode = springPluginNode; } while (!(newNode.getParent() instanceof LocationAwareElement)) { newNode = newNode.getParent(); } FileUtils.fileWrite(pom, formatElement(FileUtils.fileRead(pom), (LocationAwareElement) newNode.getParent(), newNode)); } PomXmlUpdater(MavenProject project, PluginDescriptor plugin); void updateSettings(AppSettings app, DeploymentSettings deploy); } |
@Test public void testSaveXmlNoBuild() throws Exception { final File pomFile = new File(this.getClass().getClassLoader().getResource("pom-5.xml").getFile()); final File tempFile = Files.createTempFile("azure-spring-cloud-plugin-test", ".xml").toFile(); FileUtils.copyFile(pomFile, tempFile); final Model model = TestHelper.readMavenModel(tempFile); final MavenProject project = mock(MavenProject.class); when(project.getModel()).thenReturn(model); when(project.getFile()).thenReturn(tempFile); final AppSettings app = new AppSettings(); app.setSubscriptionId("subscriptionId1"); app.setClusterName("clusterName1"); app.setAppName("appName1"); app.setPublic("true"); final DeploymentSettings deploy = new DeploymentSettings(); deploy.setCpu("1"); deploy.setMemoryInGB("2"); deploy.setInstanceCount("3"); deploy.setRuntimeVersion("8"); deploy.setJvmOptions("jvmOptions1"); final PluginDescriptor pd = mock(PluginDescriptor.class); when(pd.getGroupId()).thenReturn("com.microsoft.azure"); when(pd.getArtifactId()).thenReturn("azure-spring-cloud-maven-plugin"); when(pd.getVersion()).thenReturn("0.1.0.SNAPSHOT"); final PomXmlUpdater updater = new PomXmlUpdater(project, pd); updater.updateSettings(app, deploy); final String updatedXml = FileUtils.readFileToString(tempFile); assertTrue(updatedXml.contains("<maven.compiler.target>1.8\n" + " </maven.compiler.target>")); assertTrue(updatedXml.contains("<configuration>\n" + " <subscriptionId>subscriptionId1</subscriptionId>\n" + " <clusterName>clusterName1</clusterName>\n" + " <appName>appName1</appName>\n" + " <isPublic>true</isPublic>\n" + " <deployment>\n" + " <cpu>1</cpu>\n" + " <memoryInGB>2</memoryInGB>\n" + " <instanceCount>3</instanceCount>\n" + " <jvmOptions>jvmOptions1</jvmOptions>\n" + " <runtimeVersion>8</runtimeVersion>\n" + " <resources>\n" + " <resource>\n" + " <filtering/>\n" + " <mergeId/>\n" + " <targetPath/>\n" + " <directory>${project.basedir}/target</directory>\n" + " <includes>\n" + " <include>*.jar</include>\n" + " </includes>\n" + " </resource>\n" + " </resources>\n" + " </deployment>\n" + " </configuration>")); tempFile.delete(); } | public void updateSettings(AppSettings app, DeploymentSettings deploy) throws DocumentException, IOException { final File pom = this.project.getFile(); final SAXReader reader = new CustomSAXReader(); reader.setDocumentFactory(new LocatorAwareDocumentFactory()); final Document doc = reader.read(new InputStreamReader(new FileInputStream(pom))); final Element pluginsNode = createToPath(doc.getRootElement(), "build", "plugins"); Element springPluginNode = null; for (final Element element : pluginsNode.elements()) { final String groupId = XmlUtils.getChildValue(element, "groupId"); final String artifactId = XmlUtils.getChildValue(element, "artifactId"); final String version = XmlUtils.getChildValue(element, "version"); if (plugin.getGroupId().equals(groupId) && plugin.getArtifactId().equals(artifactId) && (version == null || StringUtils.equals(plugin.getVersion(), version))) { springPluginNode = element; } } if (springPluginNode == null) { springPluginNode = createMavenSpringPluginNode(pluginsNode); } Element newNode; if (app != null || deploy != null) { final Element configurationNode = createToPath(springPluginNode, "configuration"); if (app != null) { app.applyToDom4j(configurationNode); } if (deploy != null) { final Element deployNode = createToPath(configurationNode, "deployment"); deploy.applyToDom4j(deployNode); ResourcesUtils.applyDefaultResourcesToDom4j(deployNode); } newNode = configurationNode; } else { newNode = springPluginNode; } while (!(newNode.getParent() instanceof LocationAwareElement)) { newNode = newNode.getParent(); } FileUtils.fileWrite(pom, formatElement(FileUtils.fileRead(pom), (LocationAwareElement) newNode.getParent(), newNode)); } | PomXmlUpdater { public void updateSettings(AppSettings app, DeploymentSettings deploy) throws DocumentException, IOException { final File pom = this.project.getFile(); final SAXReader reader = new CustomSAXReader(); reader.setDocumentFactory(new LocatorAwareDocumentFactory()); final Document doc = reader.read(new InputStreamReader(new FileInputStream(pom))); final Element pluginsNode = createToPath(doc.getRootElement(), "build", "plugins"); Element springPluginNode = null; for (final Element element : pluginsNode.elements()) { final String groupId = XmlUtils.getChildValue(element, "groupId"); final String artifactId = XmlUtils.getChildValue(element, "artifactId"); final String version = XmlUtils.getChildValue(element, "version"); if (plugin.getGroupId().equals(groupId) && plugin.getArtifactId().equals(artifactId) && (version == null || StringUtils.equals(plugin.getVersion(), version))) { springPluginNode = element; } } if (springPluginNode == null) { springPluginNode = createMavenSpringPluginNode(pluginsNode); } Element newNode; if (app != null || deploy != null) { final Element configurationNode = createToPath(springPluginNode, "configuration"); if (app != null) { app.applyToDom4j(configurationNode); } if (deploy != null) { final Element deployNode = createToPath(configurationNode, "deployment"); deploy.applyToDom4j(deployNode); ResourcesUtils.applyDefaultResourcesToDom4j(deployNode); } newNode = configurationNode; } else { newNode = springPluginNode; } while (!(newNode.getParent() instanceof LocationAwareElement)) { newNode = newNode.getParent(); } FileUtils.fileWrite(pom, formatElement(FileUtils.fileRead(pom), (LocationAwareElement) newNode.getParent(), newNode)); } } | PomXmlUpdater { public void updateSettings(AppSettings app, DeploymentSettings deploy) throws DocumentException, IOException { final File pom = this.project.getFile(); final SAXReader reader = new CustomSAXReader(); reader.setDocumentFactory(new LocatorAwareDocumentFactory()); final Document doc = reader.read(new InputStreamReader(new FileInputStream(pom))); final Element pluginsNode = createToPath(doc.getRootElement(), "build", "plugins"); Element springPluginNode = null; for (final Element element : pluginsNode.elements()) { final String groupId = XmlUtils.getChildValue(element, "groupId"); final String artifactId = XmlUtils.getChildValue(element, "artifactId"); final String version = XmlUtils.getChildValue(element, "version"); if (plugin.getGroupId().equals(groupId) && plugin.getArtifactId().equals(artifactId) && (version == null || StringUtils.equals(plugin.getVersion(), version))) { springPluginNode = element; } } if (springPluginNode == null) { springPluginNode = createMavenSpringPluginNode(pluginsNode); } Element newNode; if (app != null || deploy != null) { final Element configurationNode = createToPath(springPluginNode, "configuration"); if (app != null) { app.applyToDom4j(configurationNode); } if (deploy != null) { final Element deployNode = createToPath(configurationNode, "deployment"); deploy.applyToDom4j(deployNode); ResourcesUtils.applyDefaultResourcesToDom4j(deployNode); } newNode = configurationNode; } else { newNode = springPluginNode; } while (!(newNode.getParent() instanceof LocationAwareElement)) { newNode = newNode.getParent(); } FileUtils.fileWrite(pom, formatElement(FileUtils.fileRead(pom), (LocationAwareElement) newNode.getParent(), newNode)); } PomXmlUpdater(MavenProject project, PluginDescriptor plugin); } | PomXmlUpdater { public void updateSettings(AppSettings app, DeploymentSettings deploy) throws DocumentException, IOException { final File pom = this.project.getFile(); final SAXReader reader = new CustomSAXReader(); reader.setDocumentFactory(new LocatorAwareDocumentFactory()); final Document doc = reader.read(new InputStreamReader(new FileInputStream(pom))); final Element pluginsNode = createToPath(doc.getRootElement(), "build", "plugins"); Element springPluginNode = null; for (final Element element : pluginsNode.elements()) { final String groupId = XmlUtils.getChildValue(element, "groupId"); final String artifactId = XmlUtils.getChildValue(element, "artifactId"); final String version = XmlUtils.getChildValue(element, "version"); if (plugin.getGroupId().equals(groupId) && plugin.getArtifactId().equals(artifactId) && (version == null || StringUtils.equals(plugin.getVersion(), version))) { springPluginNode = element; } } if (springPluginNode == null) { springPluginNode = createMavenSpringPluginNode(pluginsNode); } Element newNode; if (app != null || deploy != null) { final Element configurationNode = createToPath(springPluginNode, "configuration"); if (app != null) { app.applyToDom4j(configurationNode); } if (deploy != null) { final Element deployNode = createToPath(configurationNode, "deployment"); deploy.applyToDom4j(deployNode); ResourcesUtils.applyDefaultResourcesToDom4j(deployNode); } newNode = configurationNode; } else { newNode = springPluginNode; } while (!(newNode.getParent() instanceof LocationAwareElement)) { newNode = newNode.getParent(); } FileUtils.fileWrite(pom, formatElement(FileUtils.fileRead(pom), (LocationAwareElement) newNode.getParent(), newNode)); } PomXmlUpdater(MavenProject project, PluginDescriptor plugin); void updateSettings(AppSettings app, DeploymentSettings deploy); } | PomXmlUpdater { public void updateSettings(AppSettings app, DeploymentSettings deploy) throws DocumentException, IOException { final File pom = this.project.getFile(); final SAXReader reader = new CustomSAXReader(); reader.setDocumentFactory(new LocatorAwareDocumentFactory()); final Document doc = reader.read(new InputStreamReader(new FileInputStream(pom))); final Element pluginsNode = createToPath(doc.getRootElement(), "build", "plugins"); Element springPluginNode = null; for (final Element element : pluginsNode.elements()) { final String groupId = XmlUtils.getChildValue(element, "groupId"); final String artifactId = XmlUtils.getChildValue(element, "artifactId"); final String version = XmlUtils.getChildValue(element, "version"); if (plugin.getGroupId().equals(groupId) && plugin.getArtifactId().equals(artifactId) && (version == null || StringUtils.equals(plugin.getVersion(), version))) { springPluginNode = element; } } if (springPluginNode == null) { springPluginNode = createMavenSpringPluginNode(pluginsNode); } Element newNode; if (app != null || deploy != null) { final Element configurationNode = createToPath(springPluginNode, "configuration"); if (app != null) { app.applyToDom4j(configurationNode); } if (deploy != null) { final Element deployNode = createToPath(configurationNode, "deployment"); deploy.applyToDom4j(deployNode); ResourcesUtils.applyDefaultResourcesToDom4j(deployNode); } newNode = configurationNode; } else { newNode = springPluginNode; } while (!(newNode.getParent() instanceof LocationAwareElement)) { newNode = newNode.getParent(); } FileUtils.fileWrite(pom, formatElement(FileUtils.fileRead(pom), (LocationAwareElement) newNode.getParent(), newNode)); } PomXmlUpdater(MavenProject project, PluginDescriptor plugin); void updateSettings(AppSettings app, DeploymentSettings deploy); } |
@Test public void testDuplicateAdd() throws IOException { try { this.validator.collectSingleProperty("Deployment", "cpu", Mockito.mock(JsonNode.class)); fail("should throw IAE"); } catch (IllegalArgumentException ex) { } } | public void collectSingleProperty(String resource, String property, JsonNode schema) throws JsonProcessingException { Preconditions.checkArgument(StringUtils.isNotBlank(resource), "Parameter 'resource' should not be null or empty."); Preconditions.checkArgument(StringUtils.isNotBlank(property), "Parameter 'property' should not be null or empty."); Preconditions.checkArgument(!schemaMap.containsKey(combineToKey(resource, property)), String.format("Duplicate property '%s'.", combineToKey(resource, property))); schemas.put(combineToKey(resource, property), schema); schemaMap.put(combineToKey(resource, property), mapper.treeToValue(schema, Map.class)); } | SchemaValidator { public void collectSingleProperty(String resource, String property, JsonNode schema) throws JsonProcessingException { Preconditions.checkArgument(StringUtils.isNotBlank(resource), "Parameter 'resource' should not be null or empty."); Preconditions.checkArgument(StringUtils.isNotBlank(property), "Parameter 'property' should not be null or empty."); Preconditions.checkArgument(!schemaMap.containsKey(combineToKey(resource, property)), String.format("Duplicate property '%s'.", combineToKey(resource, property))); schemas.put(combineToKey(resource, property), schema); schemaMap.put(combineToKey(resource, property), mapper.treeToValue(schema, Map.class)); } } | SchemaValidator { public void collectSingleProperty(String resource, String property, JsonNode schema) throws JsonProcessingException { Preconditions.checkArgument(StringUtils.isNotBlank(resource), "Parameter 'resource' should not be null or empty."); Preconditions.checkArgument(StringUtils.isNotBlank(property), "Parameter 'property' should not be null or empty."); Preconditions.checkArgument(!schemaMap.containsKey(combineToKey(resource, property)), String.format("Duplicate property '%s'.", combineToKey(resource, property))); schemas.put(combineToKey(resource, property), schema); schemaMap.put(combineToKey(resource, property), mapper.treeToValue(schema, Map.class)); } SchemaValidator(); } | SchemaValidator { public void collectSingleProperty(String resource, String property, JsonNode schema) throws JsonProcessingException { Preconditions.checkArgument(StringUtils.isNotBlank(resource), "Parameter 'resource' should not be null or empty."); Preconditions.checkArgument(StringUtils.isNotBlank(property), "Parameter 'property' should not be null or empty."); Preconditions.checkArgument(!schemaMap.containsKey(combineToKey(resource, property)), String.format("Duplicate property '%s'.", combineToKey(resource, property))); schemas.put(combineToKey(resource, property), schema); schemaMap.put(combineToKey(resource, property), mapper.treeToValue(schema, Map.class)); } SchemaValidator(); void collectSingleProperty(String resource, String property, JsonNode schema); Map<String, Object> getSchemaMap(String resource, String property); String validateSingleProperty(String resource, String property, String value); } | SchemaValidator { public void collectSingleProperty(String resource, String property, JsonNode schema) throws JsonProcessingException { Preconditions.checkArgument(StringUtils.isNotBlank(resource), "Parameter 'resource' should not be null or empty."); Preconditions.checkArgument(StringUtils.isNotBlank(property), "Parameter 'property' should not be null or empty."); Preconditions.checkArgument(!schemaMap.containsKey(combineToKey(resource, property)), String.format("Duplicate property '%s'.", combineToKey(resource, property))); schemas.put(combineToKey(resource, property), schema); schemaMap.put(combineToKey(resource, property), mapper.treeToValue(schema, Map.class)); } SchemaValidator(); void collectSingleProperty(String resource, String property, JsonNode schema); Map<String, Object> getSchemaMap(String resource, String property); String validateSingleProperty(String resource, String property, String value); } |
@Test public void testTypeNotSupported() throws Exception { final String err = validator.validateSingleProperty("Deployment", "testProperties", "foo"); assertTrue(err.contains("Type 'array' is not supported in schema validation.")); } | public String validateSingleProperty(String resource, String property, String value) { checkExistSchema(resource, property); final JsonNode schema = this.schemas.get(combineToKey(resource, property)); final String type = (String) schemaMap.get(combineToKey(resource, property)).get("type"); try { final ProcessingReport reports = validator.validate(schema, stringToJsonObject(type, value)); return formatValidationResults(reports); } catch (IllegalArgumentException | ProcessingException e) { return e.getMessage(); } } | SchemaValidator { public String validateSingleProperty(String resource, String property, String value) { checkExistSchema(resource, property); final JsonNode schema = this.schemas.get(combineToKey(resource, property)); final String type = (String) schemaMap.get(combineToKey(resource, property)).get("type"); try { final ProcessingReport reports = validator.validate(schema, stringToJsonObject(type, value)); return formatValidationResults(reports); } catch (IllegalArgumentException | ProcessingException e) { return e.getMessage(); } } } | SchemaValidator { public String validateSingleProperty(String resource, String property, String value) { checkExistSchema(resource, property); final JsonNode schema = this.schemas.get(combineToKey(resource, property)); final String type = (String) schemaMap.get(combineToKey(resource, property)).get("type"); try { final ProcessingReport reports = validator.validate(schema, stringToJsonObject(type, value)); return formatValidationResults(reports); } catch (IllegalArgumentException | ProcessingException e) { return e.getMessage(); } } SchemaValidator(); } | SchemaValidator { public String validateSingleProperty(String resource, String property, String value) { checkExistSchema(resource, property); final JsonNode schema = this.schemas.get(combineToKey(resource, property)); final String type = (String) schemaMap.get(combineToKey(resource, property)).get("type"); try { final ProcessingReport reports = validator.validate(schema, stringToJsonObject(type, value)); return formatValidationResults(reports); } catch (IllegalArgumentException | ProcessingException e) { return e.getMessage(); } } SchemaValidator(); void collectSingleProperty(String resource, String property, JsonNode schema); Map<String, Object> getSchemaMap(String resource, String property); String validateSingleProperty(String resource, String property, String value); } | SchemaValidator { public String validateSingleProperty(String resource, String property, String value) { checkExistSchema(resource, property); final JsonNode schema = this.schemas.get(combineToKey(resource, property)); final String type = (String) schemaMap.get(combineToKey(resource, property)).get("type"); try { final ProcessingReport reports = validator.validate(schema, stringToJsonObject(type, value)); return formatValidationResults(reports); } catch (IllegalArgumentException | ProcessingException e) { return e.getMessage(); } } SchemaValidator(); void collectSingleProperty(String resource, String property, JsonNode schema); Map<String, Object> getSchemaMap(String resource, String property); String validateSingleProperty(String resource, String property, String value); } |
@Test public void testMoreThanOneViolations() throws Exception { final String err = validator.validateSingleProperty("App", "appName", "_thisisaverylonglonglonglonglongtext"); assertTrue(err.contains("The input violates the validation rules")); } | public String validateSingleProperty(String resource, String property, String value) { checkExistSchema(resource, property); final JsonNode schema = this.schemas.get(combineToKey(resource, property)); final String type = (String) schemaMap.get(combineToKey(resource, property)).get("type"); try { final ProcessingReport reports = validator.validate(schema, stringToJsonObject(type, value)); return formatValidationResults(reports); } catch (IllegalArgumentException | ProcessingException e) { return e.getMessage(); } } | SchemaValidator { public String validateSingleProperty(String resource, String property, String value) { checkExistSchema(resource, property); final JsonNode schema = this.schemas.get(combineToKey(resource, property)); final String type = (String) schemaMap.get(combineToKey(resource, property)).get("type"); try { final ProcessingReport reports = validator.validate(schema, stringToJsonObject(type, value)); return formatValidationResults(reports); } catch (IllegalArgumentException | ProcessingException e) { return e.getMessage(); } } } | SchemaValidator { public String validateSingleProperty(String resource, String property, String value) { checkExistSchema(resource, property); final JsonNode schema = this.schemas.get(combineToKey(resource, property)); final String type = (String) schemaMap.get(combineToKey(resource, property)).get("type"); try { final ProcessingReport reports = validator.validate(schema, stringToJsonObject(type, value)); return formatValidationResults(reports); } catch (IllegalArgumentException | ProcessingException e) { return e.getMessage(); } } SchemaValidator(); } | SchemaValidator { public String validateSingleProperty(String resource, String property, String value) { checkExistSchema(resource, property); final JsonNode schema = this.schemas.get(combineToKey(resource, property)); final String type = (String) schemaMap.get(combineToKey(resource, property)).get("type"); try { final ProcessingReport reports = validator.validate(schema, stringToJsonObject(type, value)); return formatValidationResults(reports); } catch (IllegalArgumentException | ProcessingException e) { return e.getMessage(); } } SchemaValidator(); void collectSingleProperty(String resource, String property, JsonNode schema); Map<String, Object> getSchemaMap(String resource, String property); String validateSingleProperty(String resource, String property, String value); } | SchemaValidator { public String validateSingleProperty(String resource, String property, String value) { checkExistSchema(resource, property); final JsonNode schema = this.schemas.get(combineToKey(resource, property)); final String type = (String) schemaMap.get(combineToKey(resource, property)).get("type"); try { final ProcessingReport reports = validator.validate(schema, stringToJsonObject(type, value)); return formatValidationResults(reports); } catch (IllegalArgumentException | ProcessingException e) { return e.getMessage(); } } SchemaValidator(); void collectSingleProperty(String resource, String property, JsonNode schema); Map<String, Object> getSchemaMap(String resource, String property); String validateSingleProperty(String resource, String property, String value); } |
@Test public void publish() throws AzureExecutionException, IOException { final WebApp app = mock(WebApp.class); final DeployTarget target = new DeployTarget(app, DeployTargetType.WEBAPP); final File file = mock(File.class); buildHandler(); doReturn(file).when(handlerSpy).getZipFile(); doNothing().when(app).zipDeploy(file); doNothing().when(handlerSpy).assureStagingDirectoryNotEmpty(); handlerSpy.publish(target); verify(handlerSpy, times(1)).assureStagingDirectoryNotEmpty(); verify(handlerSpy, times(1)).getZipFile(); verify(handlerSpy, times(1)).publish(target); verifyNoMoreInteractions(handlerSpy); } | @Override public void publish(DeployTarget target) throws AzureExecutionException { assureStagingDirectoryNotEmpty(); final File zipFile = getZipFile(); Log.prompt(String.format(DEPLOY_START, target.getName())); int retryCount = 0; while (retryCount < DEFAULT_MAX_RETRY_TIMES) { retryCount += 1; try { target.zipDeploy(zipFile); Log.prompt(String.format(DEPLOY_FINISH, target.getDefaultHostName())); return; } catch (Exception e) { Log.debug( String.format("Exception occurred when deploying the zip package: %s, " + "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES)); } } throw new AzureExecutionException(String.format("The zip deploy failed after %d times of retry.", retryCount)); } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(DeployTarget target) throws AzureExecutionException { assureStagingDirectoryNotEmpty(); final File zipFile = getZipFile(); Log.prompt(String.format(DEPLOY_START, target.getName())); int retryCount = 0; while (retryCount < DEFAULT_MAX_RETRY_TIMES) { retryCount += 1; try { target.zipDeploy(zipFile); Log.prompt(String.format(DEPLOY_FINISH, target.getDefaultHostName())); return; } catch (Exception e) { Log.debug( String.format("Exception occurred when deploying the zip package: %s, " + "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES)); } } throw new AzureExecutionException(String.format("The zip deploy failed after %d times of retry.", retryCount)); } } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(DeployTarget target) throws AzureExecutionException { assureStagingDirectoryNotEmpty(); final File zipFile = getZipFile(); Log.prompt(String.format(DEPLOY_START, target.getName())); int retryCount = 0; while (retryCount < DEFAULT_MAX_RETRY_TIMES) { retryCount += 1; try { target.zipDeploy(zipFile); Log.prompt(String.format(DEPLOY_FINISH, target.getDefaultHostName())); return; } catch (Exception e) { Log.debug( String.format("Exception occurred when deploying the zip package: %s, " + "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES)); } } throw new AzureExecutionException(String.format("The zip deploy failed after %d times of retry.", retryCount)); } protected ZIPArtifactHandlerImpl(final Builder builder); } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(DeployTarget target) throws AzureExecutionException { assureStagingDirectoryNotEmpty(); final File zipFile = getZipFile(); Log.prompt(String.format(DEPLOY_START, target.getName())); int retryCount = 0; while (retryCount < DEFAULT_MAX_RETRY_TIMES) { retryCount += 1; try { target.zipDeploy(zipFile); Log.prompt(String.format(DEPLOY_FINISH, target.getDefaultHostName())); return; } catch (Exception e) { Log.debug( String.format("Exception occurred when deploying the zip package: %s, " + "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES)); } } throw new AzureExecutionException(String.format("The zip deploy failed after %d times of retry.", retryCount)); } protected ZIPArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget target); } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(DeployTarget target) throws AzureExecutionException { assureStagingDirectoryNotEmpty(); final File zipFile = getZipFile(); Log.prompt(String.format(DEPLOY_START, target.getName())); int retryCount = 0; while (retryCount < DEFAULT_MAX_RETRY_TIMES) { retryCount += 1; try { target.zipDeploy(zipFile); Log.prompt(String.format(DEPLOY_FINISH, target.getDefaultHostName())); return; } catch (Exception e) { Log.debug( String.format("Exception occurred when deploying the zip package: %s, " + "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES)); } } throw new AzureExecutionException(String.format("The zip deploy failed after %d times of retry.", retryCount)); } protected ZIPArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget target); } |
@Test public void publishThrowResourceNotConfiguredException() throws IOException { buildHandler(); final WebApp app = mock(WebApp.class); final DeployTarget target = new DeployTarget(app, DeployTargetType.WEBAPP); try { handlerSpy.publish(target); } catch (final AzureExecutionException e) { assertEquals("<resources> is empty. Please make sure it is configured in pom.xml.", e.getMessage()); } } | @Override public void publish(DeployTarget target) throws AzureExecutionException { assureStagingDirectoryNotEmpty(); final File zipFile = getZipFile(); Log.prompt(String.format(DEPLOY_START, target.getName())); int retryCount = 0; while (retryCount < DEFAULT_MAX_RETRY_TIMES) { retryCount += 1; try { target.zipDeploy(zipFile); Log.prompt(String.format(DEPLOY_FINISH, target.getDefaultHostName())); return; } catch (Exception e) { Log.debug( String.format("Exception occurred when deploying the zip package: %s, " + "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES)); } } throw new AzureExecutionException(String.format("The zip deploy failed after %d times of retry.", retryCount)); } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(DeployTarget target) throws AzureExecutionException { assureStagingDirectoryNotEmpty(); final File zipFile = getZipFile(); Log.prompt(String.format(DEPLOY_START, target.getName())); int retryCount = 0; while (retryCount < DEFAULT_MAX_RETRY_TIMES) { retryCount += 1; try { target.zipDeploy(zipFile); Log.prompt(String.format(DEPLOY_FINISH, target.getDefaultHostName())); return; } catch (Exception e) { Log.debug( String.format("Exception occurred when deploying the zip package: %s, " + "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES)); } } throw new AzureExecutionException(String.format("The zip deploy failed after %d times of retry.", retryCount)); } } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(DeployTarget target) throws AzureExecutionException { assureStagingDirectoryNotEmpty(); final File zipFile = getZipFile(); Log.prompt(String.format(DEPLOY_START, target.getName())); int retryCount = 0; while (retryCount < DEFAULT_MAX_RETRY_TIMES) { retryCount += 1; try { target.zipDeploy(zipFile); Log.prompt(String.format(DEPLOY_FINISH, target.getDefaultHostName())); return; } catch (Exception e) { Log.debug( String.format("Exception occurred when deploying the zip package: %s, " + "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES)); } } throw new AzureExecutionException(String.format("The zip deploy failed after %d times of retry.", retryCount)); } protected ZIPArtifactHandlerImpl(final Builder builder); } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(DeployTarget target) throws AzureExecutionException { assureStagingDirectoryNotEmpty(); final File zipFile = getZipFile(); Log.prompt(String.format(DEPLOY_START, target.getName())); int retryCount = 0; while (retryCount < DEFAULT_MAX_RETRY_TIMES) { retryCount += 1; try { target.zipDeploy(zipFile); Log.prompt(String.format(DEPLOY_FINISH, target.getDefaultHostName())); return; } catch (Exception e) { Log.debug( String.format("Exception occurred when deploying the zip package: %s, " + "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES)); } } throw new AzureExecutionException(String.format("The zip deploy failed after %d times of retry.", retryCount)); } protected ZIPArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget target); } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(DeployTarget target) throws AzureExecutionException { assureStagingDirectoryNotEmpty(); final File zipFile = getZipFile(); Log.prompt(String.format(DEPLOY_START, target.getName())); int retryCount = 0; while (retryCount < DEFAULT_MAX_RETRY_TIMES) { retryCount += 1; try { target.zipDeploy(zipFile); Log.prompt(String.format(DEPLOY_FINISH, target.getDefaultHostName())); return; } catch (Exception e) { Log.debug( String.format("Exception occurred when deploying the zip package: %s, " + "retrying immediately (%d/%d)", e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES)); } } throw new AzureExecutionException(String.format("The zip deploy failed after %d times of retry.", retryCount)); } protected ZIPArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget target); } |
@Test public void getZipFile() { final File zipTestDirectory = new File("src/test/resources/ziptest"); buildHandler(); assertEquals(zipTestDirectory.getAbsolutePath() + ".zip", handlerSpy.getZipFile().getAbsolutePath()); } | protected File getZipFile() { final File zipFile = new File(stagingDirectoryPath + ".zip"); final File stagingDirectory = new File(stagingDirectoryPath); ZipUtil.pack(stagingDirectory, zipFile); ZipUtil.removeEntry(zipFile, LOCAL_SETTINGS_FILE); return zipFile; } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { protected File getZipFile() { final File zipFile = new File(stagingDirectoryPath + ".zip"); final File stagingDirectory = new File(stagingDirectoryPath); ZipUtil.pack(stagingDirectory, zipFile); ZipUtil.removeEntry(zipFile, LOCAL_SETTINGS_FILE); return zipFile; } } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { protected File getZipFile() { final File zipFile = new File(stagingDirectoryPath + ".zip"); final File stagingDirectory = new File(stagingDirectoryPath); ZipUtil.pack(stagingDirectory, zipFile); ZipUtil.removeEntry(zipFile, LOCAL_SETTINGS_FILE); return zipFile; } protected ZIPArtifactHandlerImpl(final Builder builder); } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { protected File getZipFile() { final File zipFile = new File(stagingDirectoryPath + ".zip"); final File stagingDirectory = new File(stagingDirectoryPath); ZipUtil.pack(stagingDirectory, zipFile); ZipUtil.removeEntry(zipFile, LOCAL_SETTINGS_FILE); return zipFile; } protected ZIPArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget target); } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { protected File getZipFile() { final File zipFile = new File(stagingDirectoryPath + ".zip"); final File stagingDirectory = new File(stagingDirectoryPath); ZipUtil.pack(stagingDirectory, zipFile); ZipUtil.removeEntry(zipFile, LOCAL_SETTINGS_FILE); return zipFile; } protected ZIPArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget target); } |
@Test public void runFunctions() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); final CommandHandler commandHandlerMock = mock(CommandHandlerImpl.class); doNothing().when(commandHandlerMock).runCommandWithReturnCodeCheck(anyString(), anyBoolean(), anyString(), ArgumentMatchers.anyList(), anyString()); doReturn("buildDirectory").when(mojoSpy).getDeploymentStagingDirectoryPath(); mojoSpy.runFunctions(commandHandlerMock); verify(commandHandlerMock, times(1)) .runCommandWithReturnCodeCheck( mojoSpy.getStartFunctionHostCommand(), true, mojoSpy.getDeploymentStagingDirectoryPath(), CommandUtils.getValidReturnCodes(), RUN_FUNCTIONS_FAILURE ); } | protected void runFunctions(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getStartFunctionHostCommand(), true, getDeploymentStagingDirectoryPath(), CommandUtils.getValidReturnCodes(), RUN_FUNCTIONS_FAILURE ); } | RunMojo extends AbstractFunctionMojo { protected void runFunctions(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getStartFunctionHostCommand(), true, getDeploymentStagingDirectoryPath(), CommandUtils.getValidReturnCodes(), RUN_FUNCTIONS_FAILURE ); } } | RunMojo extends AbstractFunctionMojo { protected void runFunctions(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getStartFunctionHostCommand(), true, getDeploymentStagingDirectoryPath(), CommandUtils.getValidReturnCodes(), RUN_FUNCTIONS_FAILURE ); } } | RunMojo extends AbstractFunctionMojo { protected void runFunctions(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getStartFunctionHostCommand(), true, getDeploymentStagingDirectoryPath(), CommandUtils.getValidReturnCodes(), RUN_FUNCTIONS_FAILURE ); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } | RunMojo extends AbstractFunctionMojo { protected void runFunctions(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getStartFunctionHostCommand(), true, getDeploymentStagingDirectoryPath(), CommandUtils.getValidReturnCodes(), RUN_FUNCTIONS_FAILURE ); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } |
@Test(expected = ZipException.class) public void getZipFileThrowException() { handler = builder.stagingDirectoryPath("").build(); handlerSpy = spy(handler); handlerSpy.getZipFile(); } | protected File getZipFile() { final File zipFile = new File(stagingDirectoryPath + ".zip"); final File stagingDirectory = new File(stagingDirectoryPath); ZipUtil.pack(stagingDirectory, zipFile); ZipUtil.removeEntry(zipFile, LOCAL_SETTINGS_FILE); return zipFile; } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { protected File getZipFile() { final File zipFile = new File(stagingDirectoryPath + ".zip"); final File stagingDirectory = new File(stagingDirectoryPath); ZipUtil.pack(stagingDirectory, zipFile); ZipUtil.removeEntry(zipFile, LOCAL_SETTINGS_FILE); return zipFile; } } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { protected File getZipFile() { final File zipFile = new File(stagingDirectoryPath + ".zip"); final File stagingDirectory = new File(stagingDirectoryPath); ZipUtil.pack(stagingDirectory, zipFile); ZipUtil.removeEntry(zipFile, LOCAL_SETTINGS_FILE); return zipFile; } protected ZIPArtifactHandlerImpl(final Builder builder); } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { protected File getZipFile() { final File zipFile = new File(stagingDirectoryPath + ".zip"); final File stagingDirectory = new File(stagingDirectoryPath); ZipUtil.pack(stagingDirectory, zipFile); ZipUtil.removeEntry(zipFile, LOCAL_SETTINGS_FILE); return zipFile; } protected ZIPArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget target); } | ZIPArtifactHandlerImpl extends ArtifactHandlerBase { protected File getZipFile() { final File zipFile = new File(stagingDirectoryPath + ".zip"); final File stagingDirectory = new File(stagingDirectoryPath); ZipUtil.pack(stagingDirectory, zipFile); ZipUtil.removeEntry(zipFile, LOCAL_SETTINGS_FILE); return zipFile; } protected ZIPArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget target); } |
@Test(expected = AzureExecutionException.class) public void assureStagingDirectoryNotEmptyThrowException() throws AzureExecutionException { handler = builder.project(mock(IProject.class)) .stagingDirectoryPath("") .build(); handler.assureStagingDirectoryNotEmpty(); } | protected void assureStagingDirectoryNotEmpty() throws AzureExecutionException { final File stagingDirectory = new File(stagingDirectoryPath); final File[] files = stagingDirectory.listFiles(); if (!stagingDirectory.exists() || !stagingDirectory.isDirectory() || files == null || files.length == 0) { throw new AzureExecutionException(String.format(STAGING_FOLDER_EMPTY, stagingDirectory.getAbsolutePath())); } } | ArtifactHandlerBase implements ArtifactHandler { protected void assureStagingDirectoryNotEmpty() throws AzureExecutionException { final File stagingDirectory = new File(stagingDirectoryPath); final File[] files = stagingDirectory.listFiles(); if (!stagingDirectory.exists() || !stagingDirectory.isDirectory() || files == null || files.length == 0) { throw new AzureExecutionException(String.format(STAGING_FOLDER_EMPTY, stagingDirectory.getAbsolutePath())); } } } | ArtifactHandlerBase implements ArtifactHandler { protected void assureStagingDirectoryNotEmpty() throws AzureExecutionException { final File stagingDirectory = new File(stagingDirectoryPath); final File[] files = stagingDirectory.listFiles(); if (!stagingDirectory.exists() || !stagingDirectory.isDirectory() || files == null || files.length == 0) { throw new AzureExecutionException(String.format(STAGING_FOLDER_EMPTY, stagingDirectory.getAbsolutePath())); } } protected ArtifactHandlerBase(Builder<?> builder); } | ArtifactHandlerBase implements ArtifactHandler { protected void assureStagingDirectoryNotEmpty() throws AzureExecutionException { final File stagingDirectory = new File(stagingDirectoryPath); final File[] files = stagingDirectory.listFiles(); if (!stagingDirectory.exists() || !stagingDirectory.isDirectory() || files == null || files.length == 0) { throw new AzureExecutionException(String.format(STAGING_FOLDER_EMPTY, stagingDirectory.getAbsolutePath())); } } protected ArtifactHandlerBase(Builder<?> builder); } | ArtifactHandlerBase implements ArtifactHandler { protected void assureStagingDirectoryNotEmpty() throws AzureExecutionException { final File stagingDirectory = new File(stagingDirectoryPath); final File[] files = stagingDirectory.listFiles(); if (!stagingDirectory.exists() || !stagingDirectory.isDirectory() || files == null || files.length == 0) { throw new AzureExecutionException(String.format(STAGING_FOLDER_EMPTY, stagingDirectory.getAbsolutePath())); } } protected ArtifactHandlerBase(Builder<?> builder); } |
@Test public void assureStagingDirectoryNotEmpty() throws AzureExecutionException { buildHandler(); doNothing().when(handlerSpy).assureStagingDirectoryNotEmpty(); handlerSpy.assureStagingDirectoryNotEmpty(); verify(handlerSpy, times(1)).assureStagingDirectoryNotEmpty(); verifyNoMoreInteractions(handlerSpy); } | protected void assureStagingDirectoryNotEmpty() throws AzureExecutionException { final File stagingDirectory = new File(stagingDirectoryPath); final File[] files = stagingDirectory.listFiles(); if (!stagingDirectory.exists() || !stagingDirectory.isDirectory() || files == null || files.length == 0) { throw new AzureExecutionException(String.format(STAGING_FOLDER_EMPTY, stagingDirectory.getAbsolutePath())); } } | ArtifactHandlerBase implements ArtifactHandler { protected void assureStagingDirectoryNotEmpty() throws AzureExecutionException { final File stagingDirectory = new File(stagingDirectoryPath); final File[] files = stagingDirectory.listFiles(); if (!stagingDirectory.exists() || !stagingDirectory.isDirectory() || files == null || files.length == 0) { throw new AzureExecutionException(String.format(STAGING_FOLDER_EMPTY, stagingDirectory.getAbsolutePath())); } } } | ArtifactHandlerBase implements ArtifactHandler { protected void assureStagingDirectoryNotEmpty() throws AzureExecutionException { final File stagingDirectory = new File(stagingDirectoryPath); final File[] files = stagingDirectory.listFiles(); if (!stagingDirectory.exists() || !stagingDirectory.isDirectory() || files == null || files.length == 0) { throw new AzureExecutionException(String.format(STAGING_FOLDER_EMPTY, stagingDirectory.getAbsolutePath())); } } protected ArtifactHandlerBase(Builder<?> builder); } | ArtifactHandlerBase implements ArtifactHandler { protected void assureStagingDirectoryNotEmpty() throws AzureExecutionException { final File stagingDirectory = new File(stagingDirectoryPath); final File[] files = stagingDirectory.listFiles(); if (!stagingDirectory.exists() || !stagingDirectory.isDirectory() || files == null || files.length == 0) { throw new AzureExecutionException(String.format(STAGING_FOLDER_EMPTY, stagingDirectory.getAbsolutePath())); } } protected ArtifactHandlerBase(Builder<?> builder); } | ArtifactHandlerBase implements ArtifactHandler { protected void assureStagingDirectoryNotEmpty() throws AzureExecutionException { final File stagingDirectory = new File(stagingDirectoryPath); final File[] files = stagingDirectory.listFiles(); if (!stagingDirectory.exists() || !stagingDirectory.isDirectory() || files == null || files.length == 0) { throw new AzureExecutionException(String.format(STAGING_FOLDER_EMPTY, stagingDirectory.getAbsolutePath())); } } protected ArtifactHandlerBase(Builder<?> builder); } |
@Test public void uploadDirectoryToFTP() throws Exception { final String ftpUrl = "ftp.azurewebsites.net/site/wwwroot"; final PublishingProfile profile = mock(PublishingProfile.class); final WebApp app = mock(WebApp.class); final DeployTarget deployTarget = new DeployTarget(app, DeployTargetType.WEBAPP); final FTPUploader uploader = mock(FTPUploader.class); doReturn(ftpUrl).when(profile).ftpUrl(); doReturn(profile).when(app).getPublishingProfile(); buildHandler(); doReturn(uploader).when(handlerSpy).getUploader(); handlerSpy.uploadDirectoryToFTP(deployTarget); verify(app, times(1)).getPublishingProfile(); verifyNoMoreInteractions(app); verify(profile, times(1)).ftpUrl(); verify(profile, times(1)).ftpUsername(); verify(profile, times(1)).ftpPassword(); verifyNoMoreInteractions(profile); verify(uploader, times(1)) .uploadDirectoryWithRetries("ftp.azurewebsites.net", null, null, "target/classes", "/site/wwwroot", 3); verifyNoMoreInteractions(uploader); } | protected void uploadDirectoryToFTP(DeployTarget target) throws AzureExecutionException { final FTPUploader uploader = getUploader(); final PublishingProfile profile = target.getPublishingProfile(); final String serverUrl = profile.ftpUrl().split("/", 2)[0]; uploader.uploadDirectoryWithRetries(serverUrl, profile.ftpUsername(), profile.ftpPassword(), stagingDirectoryPath, DEFAULT_WEBAPP_ROOT, DEFAULT_MAX_RETRY_TIMES); } | FTPArtifactHandlerImpl extends ArtifactHandlerBase { protected void uploadDirectoryToFTP(DeployTarget target) throws AzureExecutionException { final FTPUploader uploader = getUploader(); final PublishingProfile profile = target.getPublishingProfile(); final String serverUrl = profile.ftpUrl().split("/", 2)[0]; uploader.uploadDirectoryWithRetries(serverUrl, profile.ftpUsername(), profile.ftpPassword(), stagingDirectoryPath, DEFAULT_WEBAPP_ROOT, DEFAULT_MAX_RETRY_TIMES); } } | FTPArtifactHandlerImpl extends ArtifactHandlerBase { protected void uploadDirectoryToFTP(DeployTarget target) throws AzureExecutionException { final FTPUploader uploader = getUploader(); final PublishingProfile profile = target.getPublishingProfile(); final String serverUrl = profile.ftpUrl().split("/", 2)[0]; uploader.uploadDirectoryWithRetries(serverUrl, profile.ftpUsername(), profile.ftpPassword(), stagingDirectoryPath, DEFAULT_WEBAPP_ROOT, DEFAULT_MAX_RETRY_TIMES); } private FTPArtifactHandlerImpl(final Builder builder); } | FTPArtifactHandlerImpl extends ArtifactHandlerBase { protected void uploadDirectoryToFTP(DeployTarget target) throws AzureExecutionException { final FTPUploader uploader = getUploader(); final PublishingProfile profile = target.getPublishingProfile(); final String serverUrl = profile.ftpUrl().split("/", 2)[0]; uploader.uploadDirectoryWithRetries(serverUrl, profile.ftpUsername(), profile.ftpPassword(), stagingDirectoryPath, DEFAULT_WEBAPP_ROOT, DEFAULT_MAX_RETRY_TIMES); } private FTPArtifactHandlerImpl(final Builder builder); @Override void publish(final DeployTarget target); } | FTPArtifactHandlerImpl extends ArtifactHandlerBase { protected void uploadDirectoryToFTP(DeployTarget target) throws AzureExecutionException { final FTPUploader uploader = getUploader(); final PublishingProfile profile = target.getPublishingProfile(); final String serverUrl = profile.ftpUrl().split("/", 2)[0]; uploader.uploadDirectoryWithRetries(serverUrl, profile.ftpUsername(), profile.ftpPassword(), stagingDirectoryPath, DEFAULT_WEBAPP_ROOT, DEFAULT_MAX_RETRY_TIMES); } private FTPArtifactHandlerImpl(final Builder builder); @Override void publish(final DeployTarget target); } |
@Test public void testWrap() { final Object obj = new Object(); final InputValidateResult<Object> wrapper = InputValidateResult.wrap(obj); assertNotNull(wrapper); assertSame(obj, wrapper.getObj()); assertNull(wrapper.getErrorMessage()); } | public static <T> InputValidateResult<T> wrap(T obj) { final InputValidateResult<T> res = new InputValidateResult<>(); res.obj = obj; return res; } | InputValidateResult { public static <T> InputValidateResult<T> wrap(T obj) { final InputValidateResult<T> res = new InputValidateResult<>(); res.obj = obj; return res; } } | InputValidateResult { public static <T> InputValidateResult<T> wrap(T obj) { final InputValidateResult<T> res = new InputValidateResult<>(); res.obj = obj; return res; } } | InputValidateResult { public static <T> InputValidateResult<T> wrap(T obj) { final InputValidateResult<T> res = new InputValidateResult<>(); res.obj = obj; return res; } T getObj(); String getErrorMessage(); static InputValidateResult<T> wrap(T obj); static InputValidateResult<T> error(String errorMessage); } | InputValidateResult { public static <T> InputValidateResult<T> wrap(T obj) { final InputValidateResult<T> res = new InputValidateResult<>(); res.obj = obj; return res; } T getObj(); String getErrorMessage(); static InputValidateResult<T> wrap(T obj); static InputValidateResult<T> error(String errorMessage); } |
@Test public void testError() { final InputValidateResult<Object> wrapper = InputValidateResult.error("message"); assertNotNull(wrapper); assertEquals("message", wrapper.getErrorMessage()); assertNull(wrapper.getObj()); } | public static <T> InputValidateResult<T> error(String errorMessage) { final InputValidateResult<T> res = new InputValidateResult<>(); res.errorMessage = errorMessage; return res; } | InputValidateResult { public static <T> InputValidateResult<T> error(String errorMessage) { final InputValidateResult<T> res = new InputValidateResult<>(); res.errorMessage = errorMessage; return res; } } | InputValidateResult { public static <T> InputValidateResult<T> error(String errorMessage) { final InputValidateResult<T> res = new InputValidateResult<>(); res.errorMessage = errorMessage; return res; } } | InputValidateResult { public static <T> InputValidateResult<T> error(String errorMessage) { final InputValidateResult<T> res = new InputValidateResult<>(); res.errorMessage = errorMessage; return res; } T getObj(); String getErrorMessage(); static InputValidateResult<T> wrap(T obj); static InputValidateResult<T> error(String errorMessage); } | InputValidateResult { public static <T> InputValidateResult<T> error(String errorMessage) { final InputValidateResult<T> res = new InputValidateResult<>(); res.errorMessage = errorMessage; return res; } T getObj(); String getErrorMessage(); static InputValidateResult<T> wrap(T obj); static InputValidateResult<T> error(String errorMessage); } |
@Test public void testPromoteStringRequired() throws Exception { when(reader.readLine()).thenReturn("bar"); String result = prompter.promoteString("Please input a string", "foo", input -> { if (StringUtils.equals("bar", input)) { try { when(reader.readLine()).thenReturn(" 10 "); } catch (IOException e) { SneakyThrowUtils.sneakyThrow(e); } return InputValidateResult.error("cannot input bar"); } return InputValidateResult.wrap(input.trim()); }, true); assertEquals("10", result); when(reader.readLine()).thenReturn(""); result = prompter.promoteString("Please input a string", "foo", input -> { throw new RuntimeException(); }, true); assertEquals("foo", result); when(reader.readLine()).thenReturn("").thenReturn("").thenReturn("a"); result = prompter.promoteString("Please input a string", null, InputValidateResult::wrap, true); assertEquals("a", result); } | public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void testPromoteStringNotRequired() throws Exception { when(reader.readLine()).thenReturn(""); String result = prompter.promoteString("Please input a string", "foo", input -> { throw new RuntimeException(); }, false); assertEquals("foo", result); result = prompter.promoteString("Please input a string", null, input -> { throw new RuntimeException(); }, false); assertNull(result); } | public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void testPromoteStringEmpty() throws Exception { when(reader.readLine()).thenReturn(":"); final String result = prompter.promoteString("Please input a string", "foo", input -> { throw new RuntimeException(); }, false); assertEquals("", result); } | public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (!isRequired && StringUtils.equals(EMPTY_REPLACEMENT, input.trim())) { return InputValidateResult.wrap(""); } final InputValidateResult<String> result = verify.apply(input); if (result.getErrorMessage() != null) { return InputValidateResult.error(result.getErrorMessage()); } else { return InputValidateResult.wrap(result.getObj()); } }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void testPromoteYesNo() throws Exception { when(reader.readLine()).thenReturn("Y").thenReturn("y").thenReturn("n"); Boolean result = prompter.promoteYesNo("Do you want to continue(y/n)", null, true); assertNotNull(result); assertTrue(result); result = prompter.promoteYesNo("Do you want to continue(y/n)", null, true); assertNotNull(result); assertTrue(result); result = prompter.promoteYesNo("Do you want to continue(y/n)", null, true); assertNotNull(result); assertFalse(result); when(reader.readLine()).thenReturn("").thenReturn(""); result = prompter.promoteYesNo("Do you want to continue(Y/n)", true, false); assertNotNull(result); assertTrue(result); result = prompter.promoteYesNo("Do you want to continue(Y/n)", false, false); assertNotNull(result); assertFalse(result); } | public Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultValue != null; System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (input.equalsIgnoreCase("Y")) { return InputValidateResult.wrap(Boolean.TRUE); } if (input.equalsIgnoreCase("N")) { return InputValidateResult.wrap(Boolean.FALSE); } return InputValidateResult.error(String.format("Invalid input (%s).", input)); }); } | DefaultPrompter implements IPrompter { public Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultValue != null; System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (input.equalsIgnoreCase("Y")) { return InputValidateResult.wrap(Boolean.TRUE); } if (input.equalsIgnoreCase("N")) { return InputValidateResult.wrap(Boolean.FALSE); } return InputValidateResult.error(String.format("Invalid input (%s).", input)); }); } } | DefaultPrompter implements IPrompter { public Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultValue != null; System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (input.equalsIgnoreCase("Y")) { return InputValidateResult.wrap(Boolean.TRUE); } if (input.equalsIgnoreCase("N")) { return InputValidateResult.wrap(Boolean.FALSE); } return InputValidateResult.error(String.format("Invalid input (%s).", input)); }); } } | DefaultPrompter implements IPrompter { public Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultValue != null; System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (input.equalsIgnoreCase("Y")) { return InputValidateResult.wrap(Boolean.TRUE); } if (input.equalsIgnoreCase("N")) { return InputValidateResult.wrap(Boolean.FALSE); } return InputValidateResult.error(String.format("Invalid input (%s).", input)); }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultValue != null; System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (input.equalsIgnoreCase("Y")) { return InputValidateResult.wrap(Boolean.TRUE); } if (input.equalsIgnoreCase("N")) { return InputValidateResult.wrap(Boolean.FALSE); } return InputValidateResult.error(String.format("Invalid input (%s).", input)); }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void getCheckRuntimeCommand() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); assertEquals(FUNC_CMD, mojoSpy.getCheckRuntimeCommand()); } | protected String getCheckRuntimeCommand() { return FUNC_CMD; } | RunMojo extends AbstractFunctionMojo { protected String getCheckRuntimeCommand() { return FUNC_CMD; } } | RunMojo extends AbstractFunctionMojo { protected String getCheckRuntimeCommand() { return FUNC_CMD; } } | RunMojo extends AbstractFunctionMojo { protected String getCheckRuntimeCommand() { return FUNC_CMD; } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } | RunMojo extends AbstractFunctionMojo { protected String getCheckRuntimeCommand() { return FUNC_CMD; } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } |
@Test public void testPromoteYesNoBadInput() throws Exception { when(reader.readLine()).thenReturn("foo").thenReturn("bar").thenReturn("Y"); final Boolean result = prompter.promoteYesNo("Do you want to continue(Y/n)", null, true); assertNotNull(result); assertTrue(result); } | public Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultValue != null; System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (input.equalsIgnoreCase("Y")) { return InputValidateResult.wrap(Boolean.TRUE); } if (input.equalsIgnoreCase("N")) { return InputValidateResult.wrap(Boolean.FALSE); } return InputValidateResult.error(String.format("Invalid input (%s).", input)); }); } | DefaultPrompter implements IPrompter { public Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultValue != null; System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (input.equalsIgnoreCase("Y")) { return InputValidateResult.wrap(Boolean.TRUE); } if (input.equalsIgnoreCase("N")) { return InputValidateResult.wrap(Boolean.FALSE); } return InputValidateResult.error(String.format("Invalid input (%s).", input)); }); } } | DefaultPrompter implements IPrompter { public Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultValue != null; System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (input.equalsIgnoreCase("Y")) { return InputValidateResult.wrap(Boolean.TRUE); } if (input.equalsIgnoreCase("N")) { return InputValidateResult.wrap(Boolean.FALSE); } return InputValidateResult.error(String.format("Invalid input (%s).", input)); }); } } | DefaultPrompter implements IPrompter { public Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultValue != null; System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (input.equalsIgnoreCase("Y")) { return InputValidateResult.wrap(Boolean.TRUE); } if (input.equalsIgnoreCase("N")) { return InputValidateResult.wrap(Boolean.FALSE); } return InputValidateResult.error(String.format("Invalid input (%s).", input)); }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultValue != null; System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, input -> { if (input.equalsIgnoreCase("Y")) { return InputValidateResult.wrap(Boolean.TRUE); } if (input.equalsIgnoreCase("N")) { return InputValidateResult.wrap(Boolean.FALSE); } return InputValidateResult.error(String.format("Invalid input (%s).", input)); }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void testPromoteMultipleEntities() throws Exception { when(reader.readLine()).thenReturn("1").thenReturn("1-2").thenReturn("1-2,3-5").thenReturn("3-1000000,1-2,3-5"); final List<Integer> integers = new ArrayList<>(); for (int i = 0; i < 10; i++) { integers.add(i); } List<Integer> selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), false, "to select none", Collections.emptyList()); assertEquals("0", TestHelper.joinIntegers(selected)); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), false, "to select none", Collections.emptyList()); assertEquals("0,1", TestHelper.joinIntegers(selected)); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), false, "to select none", Collections.emptyList()); assertEquals("0,1,2,3,4", TestHelper.joinIntegers(selected)); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), false, "to select none", Collections.emptyList()); assertEquals("2,3,4,5,6,7,8,9,0,1", TestHelper.joinIntegers(selected)); when(reader.readLine()).thenReturn("bad value").thenReturn("100").thenReturn(""); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), true, "to select none", Collections.emptyList()); assertTrue(selected.isEmpty()); when(reader.readLine()).thenReturn(""); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", Collections.singletonList(1), t -> t.toString(), true, "to select none", Collections.emptyList()); assertTrue(selected.isEmpty()); when(reader.readLine()).thenReturn(""); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), true, "to select none", Arrays.asList(4, 5)); assertEquals("4,5", TestHelper.joinIntegers(selected)); } | public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void testPromoteMultipleEntitiesAllowEmpty() throws Exception { when(reader.readLine()).thenReturn("1").thenReturn("1-2").thenReturn("1-2,3-5").thenReturn("3-1000000,1-2,3-5"); final List<Integer> integers = new ArrayList<>(); for (int i = 0; i < 10; i++) { integers.add(i); } List<Integer> selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), true, "to select none", Collections.emptyList()); assertEquals("0", TestHelper.joinIntegers(selected)); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), true, "to select none", Collections.emptyList()); assertEquals("0,1", TestHelper.joinIntegers(selected)); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), true, "to select none", Collections.emptyList()); assertEquals("0,1,2,3,4", TestHelper.joinIntegers(selected)); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), true, "to select none", Collections.emptyList()); assertEquals("2,3,4,5,6,7,8,9,0,1", TestHelper.joinIntegers(selected)); when(reader.readLine()).thenReturn("bad value").thenReturn("100").thenReturn(""); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), true, "to select none", Collections.emptyList()); assertTrue(selected.isEmpty()); when(reader.readLine()).thenReturn(""); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", Collections.singletonList(1), t -> t.toString(), true, "to select none", Collections.emptyList()); assertTrue(selected.isEmpty()); when(reader.readLine()).thenReturn(""); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", integers, t -> t.toString(), true, "to select none", Arrays.asList(4, 5)); assertEquals("4,5", TestHelper.joinIntegers(selected)); } | public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void testPromoteMultipleEntitiesOnlyOne() throws Exception { final List<Integer> selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", Collections.singletonList(100), t -> t.toString(), false, "to select none", Collections.emptyList()); assertEquals("100", TestHelper.joinIntegers(selected)); } | public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void testPromoteMultipleEntitiesNotAllowEmptyNoDefaultValue() throws Exception { when(reader.readLine()).thenReturn("1000-11111").thenReturn("10001111111111111111111111111").thenReturn("2");; final List<Integer> selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", Arrays.asList(98, 99, 100), t -> t.toString(), false, "to select none", Collections.emptyList()); assertEquals("99", TestHelper.joinIntegers(selected)); } | public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void testPromoteMultipleEntitiesSelectNone() throws Exception { when(reader.readLine()).thenReturn(""); List<Integer> selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", Collections.singletonList(100), t -> t.toString(), true, "to select none", Collections.emptyList()); assertEquals(0, selected.size()); when(reader.readLine()).thenReturn("100000000000000").thenReturn("1"); selected = prompter.promoteMultipleEntities("This is header", "Please input range", "You have select no entities", Collections.singletonList(100), t -> t.toString(), true, "to select none", Collections.emptyList()); assertEquals("100", TestHelper.joinIntegers(selected)); } | public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultValue != null && defaultValue.size() > 0; final List<T> res = new ArrayList<>(); if (!allowEmpty && entities.size() == 1) { return entities; } printOptionList(header, entities, null, getNameFunc); final String example = TextUtils.blue("[1-2,4,6]"); final String hintMessage = String.format("(input numbers separated by comma, eg: %s, %s %s)", example, TextUtils.blue("ENTER"), enterPromote); final String promoteMessage = String.format("%s%s: ", promotePrefix, hintMessage); for (;;) { System.out.print(promoteMessage); System.out.flush(); final String input = reader.readLine(); if (StringUtils.isBlank(input)) { if (hasDefaultValue) { return defaultValue; } if (allowEmpty) { return res; } System.out.println(selectNoneMessage); } if (isValidIntRangeInput(input)) { try { for (final int i : parseIntRanges(input, entities.size())) { res.add(entities.get(i - 1)); } if (res.size() > 0 || allowEmpty) { return res; } System.out.print(selectNoneMessage); } catch (NumberFormatException ex) { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } } else { System.out.println(TextUtils.yellow(String.format("The input value('%s') is invalid.", input))); } System.out.flush(); } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void testPromoteSingle() throws Exception { when(reader.readLine()).thenReturn("1").thenReturn("10001111111111111111111111111").thenReturn("1000").thenReturn("2").thenReturn(""); final List<Integer> integers = new ArrayList<>(); for (int i = 1; i <= 3; i++) { integers.add(i); } Integer value = prompter.promoteSingleEntity("This is header", "Please input index for integer", integers, 2, t -> t.toString(), false); assertEquals(Integer.valueOf(1), value); value = prompter.promoteSingleEntity("This is header", "Please input index for integer", integers, 2, t -> t.toString(), false); assertEquals(Integer.valueOf(2), value); value = prompter.promoteSingleEntity("This is header", "Please input index for integer", integers, 2, t -> t.toString(), false); assertEquals(Integer.valueOf(2), value); when(reader.readLine()).thenReturn("bad number").thenReturn("10").thenReturn("3"); value = prompter.promoteSingleEntity("This is header", "Please input index for integer", integers, 2, t -> t.toString(), false); assertEquals(Integer.valueOf(3), value); } | public <T> T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultEntity != null; printOptionList(header, entities, defaultEntity, getNameFunc); final int selectedIndex = entities.indexOf(defaultEntity); final String defaultValueMessage = selectedIndex >= 0 ? " (" + TextUtils.blue(Integer.toString(selectedIndex + 1)) + ")" : ""; final String hintMessage = String.format("[1-%d]%s", entities.size(), defaultValueMessage); final String promoteMessage = String.format("%s %s: ", message, hintMessage); System.out.print(promoteMessage); System.out.flush(); return loopInput(defaultEntity, hasDefaultValue, isRequired, null, promoteMessage, input -> { final InputValidateResult<Integer> selectIndex = validateUserInputAsInteger(input, entities.size(), String.format("You have input a wrong value %s.", TextUtils.red(input))); if (selectIndex.getErrorMessage() == null) { return InputValidateResult.wrap(entities.get(selectIndex.getObj() - 1)); } return InputValidateResult.error(selectIndex.getErrorMessage()); }); } | DefaultPrompter implements IPrompter { public <T> T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultEntity != null; printOptionList(header, entities, defaultEntity, getNameFunc); final int selectedIndex = entities.indexOf(defaultEntity); final String defaultValueMessage = selectedIndex >= 0 ? " (" + TextUtils.blue(Integer.toString(selectedIndex + 1)) + ")" : ""; final String hintMessage = String.format("[1-%d]%s", entities.size(), defaultValueMessage); final String promoteMessage = String.format("%s %s: ", message, hintMessage); System.out.print(promoteMessage); System.out.flush(); return loopInput(defaultEntity, hasDefaultValue, isRequired, null, promoteMessage, input -> { final InputValidateResult<Integer> selectIndex = validateUserInputAsInteger(input, entities.size(), String.format("You have input a wrong value %s.", TextUtils.red(input))); if (selectIndex.getErrorMessage() == null) { return InputValidateResult.wrap(entities.get(selectIndex.getObj() - 1)); } return InputValidateResult.error(selectIndex.getErrorMessage()); }); } } | DefaultPrompter implements IPrompter { public <T> T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultEntity != null; printOptionList(header, entities, defaultEntity, getNameFunc); final int selectedIndex = entities.indexOf(defaultEntity); final String defaultValueMessage = selectedIndex >= 0 ? " (" + TextUtils.blue(Integer.toString(selectedIndex + 1)) + ")" : ""; final String hintMessage = String.format("[1-%d]%s", entities.size(), defaultValueMessage); final String promoteMessage = String.format("%s %s: ", message, hintMessage); System.out.print(promoteMessage); System.out.flush(); return loopInput(defaultEntity, hasDefaultValue, isRequired, null, promoteMessage, input -> { final InputValidateResult<Integer> selectIndex = validateUserInputAsInteger(input, entities.size(), String.format("You have input a wrong value %s.", TextUtils.red(input))); if (selectIndex.getErrorMessage() == null) { return InputValidateResult.wrap(entities.get(selectIndex.getObj() - 1)); } return InputValidateResult.error(selectIndex.getErrorMessage()); }); } } | DefaultPrompter implements IPrompter { public <T> T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultEntity != null; printOptionList(header, entities, defaultEntity, getNameFunc); final int selectedIndex = entities.indexOf(defaultEntity); final String defaultValueMessage = selectedIndex >= 0 ? " (" + TextUtils.blue(Integer.toString(selectedIndex + 1)) + ")" : ""; final String hintMessage = String.format("[1-%d]%s", entities.size(), defaultValueMessage); final String promoteMessage = String.format("%s %s: ", message, hintMessage); System.out.print(promoteMessage); System.out.flush(); return loopInput(defaultEntity, hasDefaultValue, isRequired, null, promoteMessage, input -> { final InputValidateResult<Integer> selectIndex = validateUserInputAsInteger(input, entities.size(), String.format("You have input a wrong value %s.", TextUtils.red(input))); if (selectIndex.getErrorMessage() == null) { return InputValidateResult.wrap(entities.get(selectIndex.getObj() - 1)); } return InputValidateResult.error(selectIndex.getErrorMessage()); }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public <T> T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultEntity != null; printOptionList(header, entities, defaultEntity, getNameFunc); final int selectedIndex = entities.indexOf(defaultEntity); final String defaultValueMessage = selectedIndex >= 0 ? " (" + TextUtils.blue(Integer.toString(selectedIndex + 1)) + ")" : ""; final String hintMessage = String.format("[1-%d]%s", entities.size(), defaultValueMessage); final String promoteMessage = String.format("%s %s: ", message, hintMessage); System.out.print(promoteMessage); System.out.flush(); return loopInput(defaultEntity, hasDefaultValue, isRequired, null, promoteMessage, input -> { final InputValidateResult<Integer> selectIndex = validateUserInputAsInteger(input, entities.size(), String.format("You have input a wrong value %s.", TextUtils.red(input))); if (selectIndex.getErrorMessage() == null) { return InputValidateResult.wrap(entities.get(selectIndex.getObj() - 1)); } return InputValidateResult.error(selectIndex.getErrorMessage()); }); } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void testClose() throws Exception { PowerMockito.doNothing().when(reader).close(); this.prompter.close(); } | public void close() { try { reader.close(); } catch (IOException e) { } } | DefaultPrompter implements IPrompter { public void close() { try { reader.close(); } catch (IOException e) { } } } | DefaultPrompter implements IPrompter { public void close() { try { reader.close(); } catch (IOException e) { } } } | DefaultPrompter implements IPrompter { public void close() { try { reader.close(); } catch (IOException e) { } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } | DefaultPrompter implements IPrompter { public void close() { try { reader.close(); } catch (IOException e) { } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); } |
@Test public void testBlue() { System.out.println("This is a " + TextUtils.blue("blue") + " text."); assertEquals("1b5b33346d611b5b6d", Hex.encodeHexString(TextUtils.blue("a").getBytes())); } | public static String blue(String message) { return applyColorToText(message, Color.BLUE); } | TextUtils { public static String blue(String message) { return applyColorToText(message, Color.BLUE); } } | TextUtils { public static String blue(String message) { return applyColorToText(message, Color.BLUE); } private TextUtils(); } | TextUtils { public static String blue(String message) { return applyColorToText(message, Color.BLUE); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } | TextUtils { public static String blue(String message) { return applyColorToText(message, Color.BLUE); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } |
@Test public void testRed() { System.out.println("This is a " + TextUtils.red("red") + " text."); assertEquals("1b5b33316d611b5b6d", Hex.encodeHexString(TextUtils.red("a").getBytes())); } | public static String red(String message) { return applyColorToText(message, Color.RED); } | TextUtils { public static String red(String message) { return applyColorToText(message, Color.RED); } } | TextUtils { public static String red(String message) { return applyColorToText(message, Color.RED); } private TextUtils(); } | TextUtils { public static String red(String message) { return applyColorToText(message, Color.RED); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } | TextUtils { public static String red(String message) { return applyColorToText(message, Color.RED); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } |
@Test public void getStartFunctionHostCommand() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); assertEquals(FUNC_HOST_START_CMD, mojoSpy.getStartFunctionHostCommand()); System.setProperty("enableDebug", "true"); assertTrue(mojoSpy.getStartFunctionHostCommand().contains("-agentlib:jdwp")); } | protected String getStartFunctionHostCommand() { final String enableDebug = System.getProperty("enableDebug"); if (StringUtils.isNotEmpty(enableDebug) && enableDebug.equalsIgnoreCase("true")) { return getStartFunctionHostWithDebugCommand(); } else { return FUNC_HOST_START_CMD; } } | RunMojo extends AbstractFunctionMojo { protected String getStartFunctionHostCommand() { final String enableDebug = System.getProperty("enableDebug"); if (StringUtils.isNotEmpty(enableDebug) && enableDebug.equalsIgnoreCase("true")) { return getStartFunctionHostWithDebugCommand(); } else { return FUNC_HOST_START_CMD; } } } | RunMojo extends AbstractFunctionMojo { protected String getStartFunctionHostCommand() { final String enableDebug = System.getProperty("enableDebug"); if (StringUtils.isNotEmpty(enableDebug) && enableDebug.equalsIgnoreCase("true")) { return getStartFunctionHostWithDebugCommand(); } else { return FUNC_HOST_START_CMD; } } } | RunMojo extends AbstractFunctionMojo { protected String getStartFunctionHostCommand() { final String enableDebug = System.getProperty("enableDebug"); if (StringUtils.isNotEmpty(enableDebug) && enableDebug.equalsIgnoreCase("true")) { return getStartFunctionHostWithDebugCommand(); } else { return FUNC_HOST_START_CMD; } } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } | RunMojo extends AbstractFunctionMojo { protected String getStartFunctionHostCommand() { final String enableDebug = System.getProperty("enableDebug"); if (StringUtils.isNotEmpty(enableDebug) && enableDebug.equalsIgnoreCase("true")) { return getStartFunctionHostWithDebugCommand(); } else { return FUNC_HOST_START_CMD; } } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } |
@Test public void testYellow() { System.out.println("This is a " + TextUtils.yellow("yellow") + " text."); assertEquals("1b5b33336d611b5b6d", Hex.encodeHexString(TextUtils.yellow("a").getBytes())); } | public static String yellow(String message) { return applyColorToText(message, Color.YELLOW); } | TextUtils { public static String yellow(String message) { return applyColorToText(message, Color.YELLOW); } } | TextUtils { public static String yellow(String message) { return applyColorToText(message, Color.YELLOW); } private TextUtils(); } | TextUtils { public static String yellow(String message) { return applyColorToText(message, Color.YELLOW); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } | TextUtils { public static String yellow(String message) { return applyColorToText(message, Color.YELLOW); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } |
@Test public void testGreen() { System.out.println("This is a " + TextUtils.green("green") + " text."); assertEquals("1b5b33326d611b5b6d", Hex.encodeHexString(TextUtils.green("a").getBytes())); } | public static String green(String message) { return applyColorToText(message, Color.GREEN); } | TextUtils { public static String green(String message) { return applyColorToText(message, Color.GREEN); } } | TextUtils { public static String green(String message) { return applyColorToText(message, Color.GREEN); } private TextUtils(); } | TextUtils { public static String green(String message) { return applyColorToText(message, Color.GREEN); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } | TextUtils { public static String green(String message) { return applyColorToText(message, Color.GREEN); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } |
@Test public void testApplyColorToText() { System.out.println("This is a " + TextUtils.applyColorToText("magenta", Color.MAGENTA) + " text."); assertEquals("1b5b33356d611b5b6d", Hex.encodeHexString(TextUtils.applyColorToText("a", Color.MAGENTA).getBytes())); assertEquals(" ", TextUtils.applyColorToText(" ", Color.MAGENTA)); assertNull(TextUtils.applyColorToText(null, Color.MAGENTA)); } | public static String applyColorToText(String text, Color colorCode) { if (StringUtils.isBlank(text)) { return text; } return Ansi.ansi().fg(colorCode).a(text).reset().toString(); } | TextUtils { public static String applyColorToText(String text, Color colorCode) { if (StringUtils.isBlank(text)) { return text; } return Ansi.ansi().fg(colorCode).a(text).reset().toString(); } } | TextUtils { public static String applyColorToText(String text, Color colorCode) { if (StringUtils.isBlank(text)) { return text; } return Ansi.ansi().fg(colorCode).a(text).reset().toString(); } private TextUtils(); } | TextUtils { public static String applyColorToText(String text, Color colorCode) { if (StringUtils.isBlank(text)) { return text; } return Ansi.ansi().fg(colorCode).a(text).reset().toString(); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } | TextUtils { public static String applyColorToText(String text, Color colorCode) { if (StringUtils.isBlank(text)) { return text; } return Ansi.ansi().fg(colorCode).a(text).reset().toString(); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } |
@Test public void testSplitLines() { final String[] lines = TextUtils.splitLines("foo \n bar \n baz"); assertEquals(3, lines.length); assertEquals("foo ", lines[0]); assertEquals(" bar ", lines[1]); assertEquals(" baz", lines[2]); } | public static String[] splitLines(String text) { Preconditions.checkNotNull(text, "The parameter 'text' cannot be null"); return text.split("\\r?\\n"); } | TextUtils { public static String[] splitLines(String text) { Preconditions.checkNotNull(text, "The parameter 'text' cannot be null"); return text.split("\\r?\\n"); } } | TextUtils { public static String[] splitLines(String text) { Preconditions.checkNotNull(text, "The parameter 'text' cannot be null"); return text.split("\\r?\\n"); } private TextUtils(); } | TextUtils { public static String[] splitLines(String text) { Preconditions.checkNotNull(text, "The parameter 'text' cannot be null"); return text.split("\\r?\\n"); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } | TextUtils { public static String[] splitLines(String text) { Preconditions.checkNotNull(text, "The parameter 'text' cannot be null"); return text.split("\\r?\\n"); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.