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(expected=UnsupportedOperationException.class) public void testSetValueNotSupported() { new ListMinimumSizeModel(new ArrayListModel<String>(), 2).setValue(true); }
public void setValue(Object value) { throw new UnsupportedOperationException(); }
ListMinimumSizeModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } }
ListMinimumSizeModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } ListMinimumSizeModel(ListModel list, int minSize); }
ListMinimumSizeModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } ListMinimumSizeModel(ListModel list, int minSize); Boolean getValue(); void setValue(Object value); }
ListMinimumSizeModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } ListMinimumSizeModel(ListModel list, int minSize); Boolean getValue(); void setValue(Object value); }
@Test public void testRemoving() { assertTrue(d_filledList.remove("Daan")); assertEquals(Arrays.asList("Gert", "Margreth"), d_filledList); assertEquals("Gert", d_filledList.remove(0)); assertEquals(Arrays.asList("Margreth"), d_filledList); resetFilledList(); d_filledList.clear(); assertEquals(Collections.emptyList(), d_filledList); resetFilledList(); ListIterator<String> it = d_filledList.listIterator(); int i = 0; while (it.hasNext()) { it.next(); if (i % 2 == 0) { it.remove(); } ++i; } assertEquals(Collections.singletonList("Gert"), d_filledList); }
@Override public E remove(int index) { if (index >= 0 && index < size()) { E e = get(index); d_set.remove(e); d_listenerManager.fireIntervalRemoved(index, index); return e; } throw new IndexOutOfBoundsException(); }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public E remove(int index) { if (index >= 0 && index < size()) { E e = get(index); d_set.remove(e); d_listenerManager.fireIntervalRemoved(index, index); return e; } throw new IndexOutOfBoundsException(); } }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public E remove(int index) { if (index >= 0 && index < size()) { E e = get(index); d_set.remove(e); d_listenerManager.fireIntervalRemoved(index, index); return e; } throw new IndexOutOfBoundsException(); } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public E remove(int index) { if (index >= 0 && index < size()) { E e = get(index); d_set.remove(e); d_listenerManager.fireIntervalRemoved(index, index); return e; } throw new IndexOutOfBoundsException(); } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public E remove(int index) { if (index >= 0 && index < size()) { E e = get(index); d_set.remove(e); d_listenerManager.fireIntervalRemoved(index, index); return e; } throw new IndexOutOfBoundsException(); } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); }
@Test public void testAdding() { SortedSetModel<String> ssm = new SortedSetModel<String>(); ssm.add(0, "Gert"); assertEquals(Arrays.asList("Gert"), ssm); ssm.add(0, "Margreth"); assertEquals(Arrays.asList("Gert", "Margreth"), ssm); }
@Override public void add(int index, E element) { if (!d_set.contains(element)) { d_set.add(element); int idx = indexOf(element); d_listenerManager.fireIntervalAdded(idx, idx); } }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public void add(int index, E element) { if (!d_set.contains(element)) { d_set.add(element); int idx = indexOf(element); d_listenerManager.fireIntervalAdded(idx, idx); } } }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public void add(int index, E element) { if (!d_set.contains(element)) { d_set.add(element); int idx = indexOf(element); d_listenerManager.fireIntervalAdded(idx, idx); } } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public void add(int index, E element) { if (!d_set.contains(element)) { d_set.add(element); int idx = indexOf(element); d_listenerManager.fireIntervalAdded(idx, idx); } } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public void add(int index, E element) { if (!d_set.contains(element)) { d_set.add(element); int idx = indexOf(element); d_listenerManager.fireIntervalAdded(idx, idx); } } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); }
@Test public void testGetSet() { assertEquals(new TreeSet<String>(d_filledList), d_filledList.getSet()); }
public SortedSet<E> getSet() { return new TreeSet<E>(d_set); }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { public SortedSet<E> getSet() { return new TreeSet<E>(d_set); } }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { public SortedSet<E> getSet() { return new TreeSet<E>(d_set); } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { public SortedSet<E> getSet() { return new TreeSet<E>(d_set); } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { public SortedSet<E> getSet() { return new TreeSet<E>(d_set); } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int index, E element); @Override E remove(int index); @Override boolean remove(Object o); int getSize(); Object getElementAt(int index); void addListDataListener(ListDataListener l); void removeListDataListener(ListDataListener l); SortedSet<E> getSet(); }
@Test public void testEqualsExpected() { ValueHolder valueModel = new ValueHolder("name"); ValueEqualsModel equalsModel = new ValueEqualsModel(valueModel, "name"); assertEquals(Boolean.TRUE, equalsModel.getValue()); PropertyChangeListener listener = EasyMock.createStrictMock(PropertyChangeListener.class); listener.propertyChange(JUnitUtil.eqPropertyChangeEvent(new PropertyChangeEvent(equalsModel, "value", true, false))); EasyMock.replay(listener); equalsModel.addPropertyChangeListener(listener); valueModel.setValue("naem"); EasyMock.verify(listener); }
public void setValue(final Object newValue) { throw new UnsupportedOperationException(getClass().getSimpleName() + " is read-only"); }
ValueEqualsModel extends AbstractConverter { public void setValue(final Object newValue) { throw new UnsupportedOperationException(getClass().getSimpleName() + " is read-only"); } }
ValueEqualsModel extends AbstractConverter { public void setValue(final Object newValue) { throw new UnsupportedOperationException(getClass().getSimpleName() + " is read-only"); } ValueEqualsModel(final ValueModel model, final Object expectedValue); }
ValueEqualsModel extends AbstractConverter { public void setValue(final Object newValue) { throw new UnsupportedOperationException(getClass().getSimpleName() + " is read-only"); } ValueEqualsModel(final ValueModel model, final Object expectedValue); void setValue(final Object newValue); Object convertFromSubject(final Object subjectValue); void setExpected(Object expectedValue); }
ValueEqualsModel extends AbstractConverter { public void setValue(final Object newValue) { throw new UnsupportedOperationException(getClass().getSimpleName() + " is read-only"); } ValueEqualsModel(final ValueModel model, final Object expectedValue); void setValue(final Object newValue); Object convertFromSubject(final Object subjectValue); void setExpected(Object expectedValue); }
@Test public void testChangeExpected() { ValueHolder valueModel = new ValueHolder("name"); ValueEqualsModel equalsModel = new ValueEqualsModel(valueModel, "name"); assertEquals(Boolean.TRUE, equalsModel.getValue()); PropertyChangeListener listener = EasyMock.createStrictMock(PropertyChangeListener.class); listener.propertyChange(JUnitUtil.eqPropertyChangeEvent(new PropertyChangeEvent(equalsModel, "value", true, false))); EasyMock.replay(listener); equalsModel.addPropertyChangeListener(listener); equalsModel.setExpected(15); EasyMock.verify(listener); }
public void setExpected(Object expectedValue) { Object oldVal = getValue(); d_expectedValue = expectedValue; firePropertyChange("value", oldVal, getValue()); }
ValueEqualsModel extends AbstractConverter { public void setExpected(Object expectedValue) { Object oldVal = getValue(); d_expectedValue = expectedValue; firePropertyChange("value", oldVal, getValue()); } }
ValueEqualsModel extends AbstractConverter { public void setExpected(Object expectedValue) { Object oldVal = getValue(); d_expectedValue = expectedValue; firePropertyChange("value", oldVal, getValue()); } ValueEqualsModel(final ValueModel model, final Object expectedValue); }
ValueEqualsModel extends AbstractConverter { public void setExpected(Object expectedValue) { Object oldVal = getValue(); d_expectedValue = expectedValue; firePropertyChange("value", oldVal, getValue()); } ValueEqualsModel(final ValueModel model, final Object expectedValue); void setValue(final Object newValue); Object convertFromSubject(final Object subjectValue); void setExpected(Object expectedValue); }
ValueEqualsModel extends AbstractConverter { public void setExpected(Object expectedValue) { Object oldVal = getValue(); d_expectedValue = expectedValue; firePropertyChange("value", oldVal, getValue()); } ValueEqualsModel(final ValueModel model, final Object expectedValue); void setValue(final Object newValue); Object convertFromSubject(final Object subjectValue); void setExpected(Object expectedValue); }
@SuppressWarnings("deprecation") @Test public void testGetCurrentDateWithoutTime() { Date now = new Date(); Date woTime = DateUtil.getCurrentDateWithoutTime(); assertEquals(now.getYear(), woTime.getYear()); assertEquals(now.getMonth(), woTime.getMonth()); assertEquals(now.getDay(), woTime.getDay()); assertEquals(0, woTime.getHours()); assertEquals(0, woTime.getMinutes()); assertEquals(0, woTime.getSeconds()); }
public static Date getCurrentDateWithoutTime() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.AM_PM, Calendar.AM); Date date = cal.getTime(); return date; }
DateUtil { public static Date getCurrentDateWithoutTime() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.AM_PM, Calendar.AM); Date date = cal.getTime(); return date; } }
DateUtil { public static Date getCurrentDateWithoutTime() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.AM_PM, Calendar.AM); Date date = cal.getTime(); return date; } }
DateUtil { public static Date getCurrentDateWithoutTime() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.AM_PM, Calendar.AM); Date date = cal.getTime(); return date; } static Date getCurrentDateWithoutTime(); }
DateUtil { public static Date getCurrentDateWithoutTime() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.AM_PM, Calendar.AM); Date date = cal.getTime(); return date; } static Date getCurrentDateWithoutTime(); }
@Test public void testMeanDifference() { EstimateWithPrecision e = Statistics.meanDifference( -2.5, 1.6, 177, -2.6, 1.5, 176); assertEquals(-0.1, e.getPointEstimate(), EPSILON); assertEquals(0.1650678, e.getStandardError(), EPSILON); }
public static EstimateWithPrecision meanDifference( double m0, double s0, double n0, double m1, double s1, double n1) { double md = m1 - m0; double se = Math.sqrt((s0 * s0) / n0 + (s1 * s1) / n1); return new EstimateWithPrecision(md, se); }
Statistics { public static EstimateWithPrecision meanDifference( double m0, double s0, double n0, double m1, double s1, double n1) { double md = m1 - m0; double se = Math.sqrt((s0 * s0) / n0 + (s1 * s1) / n1); return new EstimateWithPrecision(md, se); } }
Statistics { public static EstimateWithPrecision meanDifference( double m0, double s0, double n0, double m1, double s1, double n1) { double md = m1 - m0; double se = Math.sqrt((s0 * s0) / n0 + (s1 * s1) / n1); return new EstimateWithPrecision(md, se); } private Statistics(); }
Statistics { public static EstimateWithPrecision meanDifference( double m0, double s0, double n0, double m1, double s1, double n1) { double md = m1 - m0; double se = Math.sqrt((s0 * s0) / n0 + (s1 * s1) / n1); return new EstimateWithPrecision(md, se); } private Statistics(); static double logit(double p); static double ilogit(double x); static EstimateWithPrecision logOddsRatio( int a, int n, int c, int m, boolean corrected); static EstimateWithPrecision meanDifference( double m0, double s0, double n0, double m1, double s1, double n1); }
Statistics { public static EstimateWithPrecision meanDifference( double m0, double s0, double n0, double m1, double s1, double n1) { double md = m1 - m0; double se = Math.sqrt((s0 * s0) / n0 + (s1 * s1) / n1); return new EstimateWithPrecision(md, se); } private Statistics(); static double logit(double p); static double ilogit(double x); static EstimateWithPrecision logOddsRatio( int a, int n, int c, int m, boolean corrected); static EstimateWithPrecision meanDifference( double m0, double s0, double n0, double m1, double s1, double n1); }
@Test public void wakeUpWakesNested() { Suspendable mockSuspendable = createStrictMock(Suspendable.class); expect(mockSuspendable.wakeUp()).andReturn(true); replay(mockSuspendable); SimpleTask task = new SimpleSuspendableTask(mockSuspendable); task.wakeUp(); verify(mockSuspendable); }
public boolean wakeUp() { return d_suspendable.wakeUp(); }
SimpleSuspendableTask implements SimpleTask { public boolean wakeUp() { return d_suspendable.wakeUp(); } }
SimpleSuspendableTask implements SimpleTask { public boolean wakeUp() { return d_suspendable.wakeUp(); } SimpleSuspendableTask(Suspendable suspendable, String str); SimpleSuspendableTask(Runnable runnable, String str); SimpleSuspendableTask(Runnable runnable); SimpleSuspendableTask(Suspendable suspendable); }
SimpleSuspendableTask implements SimpleTask { public boolean wakeUp() { return d_suspendable.wakeUp(); } SimpleSuspendableTask(Suspendable suspendable, String str); SimpleSuspendableTask(Runnable runnable, String str); SimpleSuspendableTask(Runnable runnable); SimpleSuspendableTask(Suspendable suspendable); void addTaskListener(TaskListener l); void removeTaskListener(TaskListener l); void run(); boolean isStarted(); boolean isFinished(); boolean isFailed(); Throwable getFailureCause(); boolean isAborted(); boolean isSuspended(); boolean suspend(); boolean wakeUp(); boolean abort(); @Override String toString(); }
SimpleSuspendableTask implements SimpleTask { public boolean wakeUp() { return d_suspendable.wakeUp(); } SimpleSuspendableTask(Suspendable suspendable, String str); SimpleSuspendableTask(Runnable runnable, String str); SimpleSuspendableTask(Runnable runnable); SimpleSuspendableTask(Suspendable suspendable); void addTaskListener(TaskListener l); void removeTaskListener(TaskListener l); void run(); boolean isStarted(); boolean isFinished(); boolean isFailed(); Throwable getFailureCause(); boolean isAborted(); boolean isSuspended(); boolean suspend(); boolean wakeUp(); boolean abort(); @Override String toString(); }
@Test public void wakeUpAbortsNested() { Suspendable mockSuspendable = createStrictMock(Suspendable.class); expect(mockSuspendable.abort()).andReturn(true); replay(mockSuspendable); SimpleTask task = new SimpleSuspendableTask(mockSuspendable); task.abort(); verify(mockSuspendable); }
public boolean abort() { return d_suspendable.abort(); }
SimpleSuspendableTask implements SimpleTask { public boolean abort() { return d_suspendable.abort(); } }
SimpleSuspendableTask implements SimpleTask { public boolean abort() { return d_suspendable.abort(); } SimpleSuspendableTask(Suspendable suspendable, String str); SimpleSuspendableTask(Runnable runnable, String str); SimpleSuspendableTask(Runnable runnable); SimpleSuspendableTask(Suspendable suspendable); }
SimpleSuspendableTask implements SimpleTask { public boolean abort() { return d_suspendable.abort(); } SimpleSuspendableTask(Suspendable suspendable, String str); SimpleSuspendableTask(Runnable runnable, String str); SimpleSuspendableTask(Runnable runnable); SimpleSuspendableTask(Suspendable suspendable); void addTaskListener(TaskListener l); void removeTaskListener(TaskListener l); void run(); boolean isStarted(); boolean isFinished(); boolean isFailed(); Throwable getFailureCause(); boolean isAborted(); boolean isSuspended(); boolean suspend(); boolean wakeUp(); boolean abort(); @Override String toString(); }
SimpleSuspendableTask implements SimpleTask { public boolean abort() { return d_suspendable.abort(); } SimpleSuspendableTask(Suspendable suspendable, String str); SimpleSuspendableTask(Runnable runnable, String str); SimpleSuspendableTask(Runnable runnable); SimpleSuspendableTask(Suspendable suspendable); void addTaskListener(TaskListener l); void removeTaskListener(TaskListener l); void run(); boolean isStarted(); boolean isFinished(); boolean isFailed(); Throwable getFailureCause(); boolean isAborted(); boolean isSuspended(); boolean suspend(); boolean wakeUp(); boolean abort(); @Override String toString(); }
@Test public void testTrueCondition() { MockTask source = new MockTask(); Task ifTask = new MockTask(); Task elTask = new MockTask(); Condition condition = createStrictMock(Condition.class); expect(condition.evaluate()).andReturn(true); replay(condition); Transition trans = new DecisionTransition(source, ifTask, elTask, condition); source.start(); source.finish(); assertEquals(Collections.singletonList(ifTask), trans.transition()); verify(condition); }
public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } }
DecisionTransition implements Transition { public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } } }
DecisionTransition implements Transition { public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } } DecisionTransition(Task source, Task ifTask, Task elTask, Condition condition); }
DecisionTransition implements Transition { public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } } DecisionTransition(Task source, Task ifTask, Task elTask, Condition condition); List<Task> getSources(); List<Task> getTargets(); boolean isReady(); List<Task> transition(); }
DecisionTransition implements Transition { public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } } DecisionTransition(Task source, Task ifTask, Task elTask, Condition condition); List<Task> getSources(); List<Task> getTargets(); boolean isReady(); List<Task> transition(); }
@Test public void testInitialValues() { assertFalse(new StringNotEmptyModel(new ValueHolder(null)).getValue()); assertFalse(new StringNotEmptyModel(new ValueHolder(new Object())).getValue()); assertFalse(new StringNotEmptyModel(new ValueHolder("")).getValue()); assertTrue(new StringNotEmptyModel(new ValueHolder("Test")).getValue()); }
public Boolean getValue() { return d_val; }
StringNotEmptyModel extends AbstractValueModel { public Boolean getValue() { return d_val; } }
StringNotEmptyModel extends AbstractValueModel { public Boolean getValue() { return d_val; } StringNotEmptyModel(ValueModel nested); }
StringNotEmptyModel extends AbstractValueModel { public Boolean getValue() { return d_val; } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); }
StringNotEmptyModel extends AbstractValueModel { public Boolean getValue() { return d_val; } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); }
@Test public void testFalseCondition() { MockTask source = new MockTask(); Task ifTask = new MockTask(); Task elTask = new MockTask(); Condition condition = createStrictMock(Condition.class); expect(condition.evaluate()).andReturn(false); replay(condition); Transition trans = new DecisionTransition(source, ifTask, elTask, condition); source.start(); source.finish(); assertEquals(Collections.singletonList(elTask), trans.transition()); verify(condition); }
public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } }
DecisionTransition implements Transition { public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } } }
DecisionTransition implements Transition { public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } } DecisionTransition(Task source, Task ifTask, Task elTask, Condition condition); }
DecisionTransition implements Transition { public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } } DecisionTransition(Task source, Task ifTask, Task elTask, Condition condition); List<Task> getSources(); List<Task> getTargets(); boolean isReady(); List<Task> transition(); }
DecisionTransition implements Transition { public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } } DecisionTransition(Task source, Task ifTask, Task elTask, Condition condition); List<Task> getSources(); List<Task> getTargets(); boolean isReady(); List<Task> transition(); }
@Test public void testInitialState() { MockTask start = new MockTask(); start.start(); MockTask end = new MockTask(); Transition trans = new DirectTransition(start, end); ActivityModel model = new ActivityModel(start, end, Collections.singleton(trans)); assertEquals(Collections.singleton(start), model.getNextStates()); }
public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); }
ActivityModel { public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); } }
ActivityModel { public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); }
ActivityModel { public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); Set<Task> getNextStates(); boolean isFinished(); Task getStartState(); Task getEndState(); Set<Task> getStates(); Task getStateByName(String name); Set<Transition> getTransitions(); }
ActivityModel { public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); Set<Task> getNextStates(); boolean isFinished(); Task getStartState(); Task getEndState(); Set<Task> getStates(); Task getStateByName(String name); Set<Transition> getTransitions(); }
@Test public void testSimpleTransition() { MockTask start = new MockTask(); start.start(); MockTask end = new MockTask(); Transition trans = new DirectTransition(start, end); ActivityModel model = new ActivityModel(start, end, Collections.singleton(trans)); start.finish(); assertEquals(Collections.singleton(end), model.getNextStates()); }
public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); }
ActivityModel { public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); } }
ActivityModel { public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); }
ActivityModel { public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); Set<Task> getNextStates(); boolean isFinished(); Task getStartState(); Task getEndState(); Set<Task> getStates(); Task getStateByName(String name); Set<Transition> getTransitions(); }
ActivityModel { public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); Set<Task> getNextStates(); boolean isFinished(); Task getStartState(); Task getEndState(); Set<Task> getStates(); Task getStateByName(String name); Set<Transition> getTransitions(); }
@Test public void testIsFinished() { MockTask start = new MockTask(); start.start(); MockTask end = new MockTask(); Transition trans = new DirectTransition(start, end); ActivityModel model = new ActivityModel(start, end, Collections.singleton(trans)); start.finish(); end.start(); end.finish(); assertTrue(model.isFinished()); assertEquals(Collections.<Task>emptySet(), model.getNextStates()); }
public boolean isFinished() { return d_end.isFinished(); }
ActivityModel { public boolean isFinished() { return d_end.isFinished(); } }
ActivityModel { public boolean isFinished() { return d_end.isFinished(); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); }
ActivityModel { public boolean isFinished() { return d_end.isFinished(); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); Set<Task> getNextStates(); boolean isFinished(); Task getStartState(); Task getEndState(); Set<Task> getStates(); Task getStateByName(String name); Set<Transition> getTransitions(); }
ActivityModel { public boolean isFinished() { return d_end.isFinished(); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); Set<Task> getNextStates(); boolean isFinished(); Task getStartState(); Task getEndState(); Set<Task> getStates(); Task getStateByName(String name); Set<Transition> getTransitions(); }
@Test public void testNotifyProgress() { IterativeComputation comp = new ShortComputation(10); IterativeTask task = new IterativeTask(comp); task.setReportingInterval(3); TaskListener listener = createStrictMock(TaskListener.class); listener.taskEvent(new TaskStartedEvent(task)); listener.taskEvent(new TaskProgressEvent(task, 0, 10)); listener.taskEvent(new TaskProgressEvent(task, 3, 10)); listener.taskEvent(new TaskProgressEvent(task, 6, 10)); listener.taskEvent(new TaskProgressEvent(task, 9, 10)); listener.taskEvent(new TaskProgressEvent(task, 10, 10)); listener.taskEvent(new TaskFinishedEvent(task)); replay(listener); task.addTaskListener(listener); task.run(); verify(listener); }
public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); }
IterativeTask extends SimpleSuspendableTask { public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); } }
IterativeTask extends SimpleSuspendableTask { public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); } IterativeTask(IterativeComputation computation, String str); IterativeTask(IterativeComputation computation); }
IterativeTask extends SimpleSuspendableTask { public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); } IterativeTask(IterativeComputation computation, String str); IterativeTask(IterativeComputation computation); void setReportingInterval(int interval); @Override String toString(); }
IterativeTask extends SimpleSuspendableTask { public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); } IterativeTask(IterativeComputation computation, String str); IterativeTask(IterativeComputation computation); void setReportingInterval(int interval); @Override String toString(); }
@Test public void testNotifyProgress2() { IterativeComputation comp = new ShortComputation(9); IterativeTask task = new IterativeTask(comp); task.setReportingInterval(3); TaskListener listener = createStrictMock(TaskListener.class); listener.taskEvent(new TaskStartedEvent(task)); listener.taskEvent(new TaskProgressEvent(task, 0, 9)); listener.taskEvent(new TaskProgressEvent(task, 3, 9)); listener.taskEvent(new TaskProgressEvent(task, 6, 9)); listener.taskEvent(new TaskProgressEvent(task, 9, 9)); listener.taskEvent(new TaskFinishedEvent(task)); replay(listener); task.addTaskListener(listener); task.run(); verify(listener); }
public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); }
IterativeTask extends SimpleSuspendableTask { public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); } }
IterativeTask extends SimpleSuspendableTask { public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); } IterativeTask(IterativeComputation computation, String str); IterativeTask(IterativeComputation computation); }
IterativeTask extends SimpleSuspendableTask { public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); } IterativeTask(IterativeComputation computation, String str); IterativeTask(IterativeComputation computation); void setReportingInterval(int interval); @Override String toString(); }
IterativeTask extends SimpleSuspendableTask { public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); } IterativeTask(IterativeComputation computation, String str); IterativeTask(IterativeComputation computation); void setReportingInterval(int interval); @Override String toString(); }
@Test(expected=UnsupportedOperationException.class) public void testSetValueNotSupported() { new StringNotEmptyModel(new ValueHolder(null)).setValue(true); }
public void setValue(Object value) { throw new UnsupportedOperationException(); }
StringNotEmptyModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } }
StringNotEmptyModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } StringNotEmptyModel(ValueModel nested); }
StringNotEmptyModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); }
StringNotEmptyModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); }
@Test public void testEventChaining() { ValueHolder holder = new ValueHolder(null); StringNotEmptyModel model = new StringNotEmptyModel(holder); PropertyChangeListener mock = JUnitUtil.mockStrictListener(model, "value", false, true); model.addValueChangeListener(mock); holder.setValue("test"); holder.setValue("test2"); verify(mock); model.removeValueChangeListener(mock); mock = JUnitUtil.mockStrictListener(model, "value", true, false); model.addValueChangeListener(mock); holder.setValue(""); verify(mock); }
public void setValue(Object value) { throw new UnsupportedOperationException(); }
StringNotEmptyModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } }
StringNotEmptyModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } StringNotEmptyModel(ValueModel nested); }
StringNotEmptyModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); }
StringNotEmptyModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); }
@Test public void testTable() { assertEquals(12.706, StudentTTable.getT(1), 0.001); assertEquals(1.998, StudentTTable.getT(63), 0.001); assertEquals(1.96, StudentTTable.getT(1000), 0.01); assertEquals(1.96, StudentTTable.getT(2000), 0.01); assertEquals(StudentTTable.getT(160) / 2 + StudentTTable.getT(140) / 2, StudentTTable.getT(150), 0.01); assertEquals(3 * StudentTTable.getT(160) / 4 + StudentTTable.getT(140) / 4, StudentTTable.getT(155), 0.01); }
public static double getT(int v) { if (v < 1) { throw new IllegalArgumentException("student T distribution defined only for positive degrees of freedom"); } TDistribution dist = new TDistribution(v); return dist.inverseCumulativeProbability(0.975); }
StudentTTable { public static double getT(int v) { if (v < 1) { throw new IllegalArgumentException("student T distribution defined only for positive degrees of freedom"); } TDistribution dist = new TDistribution(v); return dist.inverseCumulativeProbability(0.975); } }
StudentTTable { public static double getT(int v) { if (v < 1) { throw new IllegalArgumentException("student T distribution defined only for positive degrees of freedom"); } TDistribution dist = new TDistribution(v); return dist.inverseCumulativeProbability(0.975); } }
StudentTTable { public static double getT(int v) { if (v < 1) { throw new IllegalArgumentException("student T distribution defined only for positive degrees of freedom"); } TDistribution dist = new TDistribution(v); return dist.inverseCumulativeProbability(0.975); } static double getT(int v); }
StudentTTable { public static double getT(int v) { if (v < 1) { throw new IllegalArgumentException("student T distribution defined only for positive degrees of freedom"); } TDistribution dist = new TDistribution(v); return dist.inverseCumulativeProbability(0.975); } static double getT(int v); }
@Test public void testGetLength() { Interval<Double> in = new Interval<Double>(1.0, 6.0); assertEquals(5.0, in.getLength(), 0.00001); }
public double getLength() { return d_upperBound.doubleValue() - d_lowerBound.doubleValue(); }
Interval { public double getLength() { return d_upperBound.doubleValue() - d_lowerBound.doubleValue(); } }
Interval { public double getLength() { return d_upperBound.doubleValue() - d_lowerBound.doubleValue(); } Interval(N lowerBound, N upperBound); }
Interval { public double getLength() { return d_upperBound.doubleValue() - d_lowerBound.doubleValue(); } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
Interval { public double getLength() { return d_upperBound.doubleValue() - d_lowerBound.doubleValue(); } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testEquals() { Interval<Double> in = new Interval<Double>(1.0, 6.0); Interval<Integer> in2 = new Interval<Integer>(1, 6); assertNotEquals(in, in2); Double d = new Double(1.0); Integer i = new Integer(6); assertNotEquals(d, in); assertNotEquals(i, in2); Interval<Double> in3 = new Interval<Double>(1.0, 6.0); Interval<Integer> in4 = new Interval<Integer>(1, 6); assertEquals(in, in3); assertEquals(in.hashCode(), in3.hashCode()); assertEquals(in2, in4); assertEquals(in2.hashCode(), in4.hashCode()); Interval<Double> in5 = new Interval<Double>(2.0, 5.0); assertNotEquals(in, in5); }
@Override public boolean equals(Object o) { if (o instanceof Interval<?>) { Interval<?> other = (Interval<?>) o; if (other.canEqual(this)) { if (other.getLowerBound().getClass().equals(getLowerBound().getClass())) { return ((getLowerBound().equals(other.getLowerBound())) && (getUpperBound().equals(other.getUpperBound()))); } } } return false; }
Interval { @Override public boolean equals(Object o) { if (o instanceof Interval<?>) { Interval<?> other = (Interval<?>) o; if (other.canEqual(this)) { if (other.getLowerBound().getClass().equals(getLowerBound().getClass())) { return ((getLowerBound().equals(other.getLowerBound())) && (getUpperBound().equals(other.getUpperBound()))); } } } return false; } }
Interval { @Override public boolean equals(Object o) { if (o instanceof Interval<?>) { Interval<?> other = (Interval<?>) o; if (other.canEqual(this)) { if (other.getLowerBound().getClass().equals(getLowerBound().getClass())) { return ((getLowerBound().equals(other.getLowerBound())) && (getUpperBound().equals(other.getUpperBound()))); } } } return false; } Interval(N lowerBound, N upperBound); }
Interval { @Override public boolean equals(Object o) { if (o instanceof Interval<?>) { Interval<?> other = (Interval<?>) o; if (other.canEqual(this)) { if (other.getLowerBound().getClass().equals(getLowerBound().getClass())) { return ((getLowerBound().equals(other.getLowerBound())) && (getUpperBound().equals(other.getUpperBound()))); } } } return false; } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
Interval { @Override public boolean equals(Object o) { if (o instanceof Interval<?>) { Interval<?> other = (Interval<?>) o; if (other.canEqual(this)) { if (other.getLowerBound().getClass().equals(getLowerBound().getClass())) { return ((getLowerBound().equals(other.getLowerBound())) && (getUpperBound().equals(other.getUpperBound()))); } } } return false; } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testToString() { Interval<Double> in = new Interval<Double>(1.0, 6.0); assertEquals("1.0-6.0", in.toString()); }
@Override public String toString() { return getLowerBound().toString() + "-" + getUpperBound().toString(); }
Interval { @Override public String toString() { return getLowerBound().toString() + "-" + getUpperBound().toString(); } }
Interval { @Override public String toString() { return getLowerBound().toString() + "-" + getUpperBound().toString(); } Interval(N lowerBound, N upperBound); }
Interval { @Override public String toString() { return getLowerBound().toString() + "-" + getUpperBound().toString(); } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
Interval { @Override public String toString() { return getLowerBound().toString() + "-" + getUpperBound().toString(); } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void test_lineSeparator_suffix() { SimpleMessage message = new SimpleMessage("Hello, World!"); LogEvent logEvent = Log4jLogEvent .newBuilder() .setLoggerName(LogstashLayoutTest.class.getSimpleName()) .setLevel(Level.INFO) .setMessage(message) .build(); test_lineSeparator_suffix(logEvent, true); test_lineSeparator_suffix(logEvent, false); }
@PluginBuilderFactory @SuppressWarnings("WeakerAccess") public static Builder newBuilder() { return new Builder(); }
LogstashLayout implements Layout<String> { @PluginBuilderFactory @SuppressWarnings("WeakerAccess") public static Builder newBuilder() { return new Builder(); } }
LogstashLayout implements Layout<String> { @PluginBuilderFactory @SuppressWarnings("WeakerAccess") public static Builder newBuilder() { return new Builder(); } private LogstashLayout(Builder builder); }
LogstashLayout implements Layout<String> { @PluginBuilderFactory @SuppressWarnings("WeakerAccess") public static Builder newBuilder() { return new Builder(); } private LogstashLayout(Builder builder); @Override String toSerializable(LogEvent event); @Override byte[] toByteArray(LogEvent event); @Override void encode(LogEvent event, ByteBufferDestination destination); @Override byte[] getFooter(); @Override byte[] getHeader(); @Override String getContentType(); @Override Map<String, String> getContentFormat(); @PluginBuilderFactory @SuppressWarnings("WeakerAccess") static Builder newBuilder(); }
LogstashLayout implements Layout<String> { @PluginBuilderFactory @SuppressWarnings("WeakerAccess") public static Builder newBuilder() { return new Builder(); } private LogstashLayout(Builder builder); @Override String toSerializable(LogEvent event); @Override byte[] toByteArray(LogEvent event); @Override void encode(LogEvent event, ByteBufferDestination destination); @Override byte[] getFooter(); @Override byte[] getHeader(); @Override String getContentType(); @Override Map<String, String> getContentFormat(); @PluginBuilderFactory @SuppressWarnings("WeakerAccess") static Builder newBuilder(); }
@Test public void initViews를호출하면버튼의Listener가설정된다() { EditText weightText = mock(EditText.class); EditText heightText = mock(EditText.class); TextView resultText = mock(TextView.class); Button resultButton = mock(Button.class); View.OnClickListener buttonListener = mock(View.OnClickListener.class); MainActivity activity = spy(new MainActivity()); when(activity.findViewById(R.id.text_weight)).thenReturn(weightText); when(activity.findViewById(R.id.text_height)).thenReturn(heightText); when(activity.findViewById(R.id.text_result)).thenReturn(resultText); when(activity.findViewById(R.id.button_calculate)).thenReturn(resultButton); when(activity.createButtonListener(weightText, heightText, resultText)).thenReturn(buttonListener); activity.initViews(); verify(activity, times(1)).createButtonListener(weightText, heightText, resultText); verify(resultButton, times(1)).setOnClickListener(buttonListener); }
@VisibleForTesting void initViews() { EditText weightText = (EditText)findViewById(R.id.text_weight); EditText heightText = (EditText)findViewById(R.id.text_height); TextView resultText = (TextView)findViewById(R.id.text_result); mCalcButton = (Button)findViewById(R.id.button_calculate); View.OnClickListener buttonListener = createButtonListener(weightText, heightText, resultText); mCalcButton.setOnClickListener(buttonListener); }
MainActivity extends AppCompatActivity { @VisibleForTesting void initViews() { EditText weightText = (EditText)findViewById(R.id.text_weight); EditText heightText = (EditText)findViewById(R.id.text_height); TextView resultText = (TextView)findViewById(R.id.text_result); mCalcButton = (Button)findViewById(R.id.button_calculate); View.OnClickListener buttonListener = createButtonListener(weightText, heightText, resultText); mCalcButton.setOnClickListener(buttonListener); } }
MainActivity extends AppCompatActivity { @VisibleForTesting void initViews() { EditText weightText = (EditText)findViewById(R.id.text_weight); EditText heightText = (EditText)findViewById(R.id.text_height); TextView resultText = (TextView)findViewById(R.id.text_result); mCalcButton = (Button)findViewById(R.id.button_calculate); View.OnClickListener buttonListener = createButtonListener(weightText, heightText, resultText); mCalcButton.setOnClickListener(buttonListener); } }
MainActivity extends AppCompatActivity { @VisibleForTesting void initViews() { EditText weightText = (EditText)findViewById(R.id.text_weight); EditText heightText = (EditText)findViewById(R.id.text_height); TextView resultText = (TextView)findViewById(R.id.text_result); mCalcButton = (Button)findViewById(R.id.button_calculate); View.OnClickListener buttonListener = createButtonListener(weightText, heightText, resultText); mCalcButton.setOnClickListener(buttonListener); } }
MainActivity extends AppCompatActivity { @VisibleForTesting void initViews() { EditText weightText = (EditText)findViewById(R.id.text_weight); EditText heightText = (EditText)findViewById(R.id.text_height); TextView resultText = (TextView)findViewById(R.id.text_result); mCalcButton = (Button)findViewById(R.id.button_calculate); View.OnClickListener buttonListener = createButtonListener(weightText, heightText, resultText); mCalcButton.setOnClickListener(buttonListener); } }
@Test public void static인start메소드를호출하면startService된다() { Context context = mock(Context.class); SaveBmiService.start(context, mock(BmiValue.class)); verify(context, times(1)).startService((Intent) any()); }
public static void start(Context context, BmiValue bmiValue) { Intent intent = new Intent(context, SaveBmiService.class); intent.putExtra(PARAM_KEY_BMI_VALUE, bmiValue); context.startService(intent); }
SaveBmiService extends IntentService { public static void start(Context context, BmiValue bmiValue) { Intent intent = new Intent(context, SaveBmiService.class); intent.putExtra(PARAM_KEY_BMI_VALUE, bmiValue); context.startService(intent); } }
SaveBmiService extends IntentService { public static void start(Context context, BmiValue bmiValue) { Intent intent = new Intent(context, SaveBmiService.class); intent.putExtra(PARAM_KEY_BMI_VALUE, bmiValue); context.startService(intent); } SaveBmiService(); }
SaveBmiService extends IntentService { public static void start(Context context, BmiValue bmiValue) { Intent intent = new Intent(context, SaveBmiService.class); intent.putExtra(PARAM_KEY_BMI_VALUE, bmiValue); context.startService(intent); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); }
SaveBmiService extends IntentService { public static void start(Context context, BmiValue bmiValue) { Intent intent = new Intent(context, SaveBmiService.class); intent.putExtra(PARAM_KEY_BMI_VALUE, bmiValue); context.startService(intent); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); static final String ACTION_RESULT; static final String PARAM_RESULT; }
@Test public void onHandleIntentにnull을전달하면아무것도하지않는다() { SaveBmiService service = spy(new SaveBmiService()); service.onHandleIntent(null); verify(service, never()).sendLocalBroadcast(anyBoolean()); verify(service, never()).saveToRemoteServer((BmiValue) any()); }
@Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); static final String ACTION_RESULT; static final String PARAM_RESULT; }
@Test public void onHandleIntent에파라미터없는Intent를전달하면아무것도하지않는다() { SaveBmiService service = spy(new SaveBmiService()); service.onHandleIntent(mock(Intent.class)); verify(service, never()).sendLocalBroadcast(anyBoolean()); verify(service, never()).saveToRemoteServer((BmiValue)any()); }
@Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); static final String ACTION_RESULT; static final String PARAM_RESULT; }
@Test public void onHandleIntent에BmiValue형이외의데이터가들어간Intent를전달하면아무것도하지않는다() { Intent intent = mock(Intent.class); when(intent.getSerializableExtra(SaveBmiService.PARAM_KEY_BMI_VALUE)).thenReturn("hoge"); SaveBmiService service = spy(new SaveBmiService()); service.onHandleIntent(intent); verify(service, never()).sendLocalBroadcast(anyBoolean()); verify(service, never()).saveToRemoteServer((BmiValue)any()); }
@Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); static final String ACTION_RESULT; static final String PARAM_RESULT; }
@Test public void onHandleIntent에바르게데이터가들어간Intent를전달하면데이터저장과Broadcast가이루어진다() { BmiValue bmiValue = mock(BmiValue.class); Intent intent = mock(Intent.class); when(intent.getSerializableExtra(SaveBmiService.PARAM_KEY_BMI_VALUE)).thenReturn(bmiValue); SaveBmiService service = spy(new SaveBmiService()); doReturn(false).when(service).saveToRemoteServer((BmiValue)any()); doNothing().when(service).sendLocalBroadcast(anyBoolean()); service.onHandleIntent(intent); verify(service, times(1)).sendLocalBroadcast(anyBoolean()); verify(service, times(1)).saveToRemoteServer((BmiValue)any()); }
@Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = saveToRemoteServer(bmiValue); sendLocalBroadcast(result); } SaveBmiService(); @Override void onCreate(); static void start(Context context, BmiValue bmiValue); static final String ACTION_RESULT; static final String PARAM_RESULT; }
@Test(expected = RuntimeException.class) public void 신장에음수값을넘기면예외가발생한다() { calculator.calculate(-1f, 60.0f);
public BmiValue calculate(float heightInMeter, float weightInKg) { if (heightInMeter < 0 || weightInKg < 0) { throw new RuntimeException("키와 몸무게는 양수로 지정해주세요"); } float bmiValue = weightInKg / (heightInMeter * heightInMeter); return createValueObj(bmiValue); }
BmiCalculator { public BmiValue calculate(float heightInMeter, float weightInKg) { if (heightInMeter < 0 || weightInKg < 0) { throw new RuntimeException("키와 몸무게는 양수로 지정해주세요"); } float bmiValue = weightInKg / (heightInMeter * heightInMeter); return createValueObj(bmiValue); } }
BmiCalculator { public BmiValue calculate(float heightInMeter, float weightInKg) { if (heightInMeter < 0 || weightInKg < 0) { throw new RuntimeException("키와 몸무게는 양수로 지정해주세요"); } float bmiValue = weightInKg / (heightInMeter * heightInMeter); return createValueObj(bmiValue); } }
BmiCalculator { public BmiValue calculate(float heightInMeter, float weightInKg) { if (heightInMeter < 0 || weightInKg < 0) { throw new RuntimeException("키와 몸무게는 양수로 지정해주세요"); } float bmiValue = weightInKg / (heightInMeter * heightInMeter); return createValueObj(bmiValue); } BmiValue calculate(float heightInMeter, float weightInKg); }
BmiCalculator { public BmiValue calculate(float heightInMeter, float weightInKg) { if (heightInMeter < 0 || weightInKg < 0) { throw new RuntimeException("키와 몸무게는 양수로 지정해주세요"); } float bmiValue = weightInKg / (heightInMeter * heightInMeter); return createValueObj(bmiValue); } BmiValue calculate(float heightInMeter, float weightInKg); }
@Test public void 생성시에전달한Float값을소수점2자리까지반올림해반환한다() { BmiValue bmiValue = new BmiValue(20.00511f); Assert.assertEquals(20.01f, bmiValue.toFloat()); }
public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; }
BmiValue implements Serializable { public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; } }
BmiValue implements Serializable { public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; } BmiValue(float value); }
BmiValue implements Serializable { public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; } BmiValue(float value); float toFloat(); String getMessage(); }
BmiValue implements Serializable { public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; } BmiValue(float value); float toFloat(); String getMessage(); }
@Test public void 생성시에전달한Float값을소수점2자리까지버림해반환한다() { BmiValue bmiValue = new BmiValue(20.00499f); Assert.assertEquals(20.00f, bmiValue.toFloat()); }
public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; }
BmiValue implements Serializable { public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; } }
BmiValue implements Serializable { public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; } BmiValue(float value); }
BmiValue implements Serializable { public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; } BmiValue(float value); float toFloat(); String getMessage(); }
BmiValue implements Serializable { public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; } BmiValue(float value); float toFloat(); String getMessage(); }
@Test public void testGetGeckcoDriverPath() { String expResult; if (isWin) { expResult = "./lib/Drivers/geckodriver.exe"; } else { expResult = "./lib/Drivers/geckodriver"; } String result = ds.getGeckcoDriverPath(); assertEquals(result, expResult); }
public String getGeckcoDriverPath() { return getProperty("GeckoDriverPath", geckoDriverPath); }
DriverSettings extends AbstractPropSettings { public String getGeckcoDriverPath() { return getProperty("GeckoDriverPath", geckoDriverPath); } }
DriverSettings extends AbstractPropSettings { public String getGeckcoDriverPath() { return getProperty("GeckoDriverPath", geckoDriverPath); } DriverSettings(String location); }
DriverSettings extends AbstractPropSettings { public String getGeckcoDriverPath() { return getProperty("GeckoDriverPath", geckoDriverPath); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
DriverSettings extends AbstractPropSettings { public String getGeckcoDriverPath() { return getProperty("GeckoDriverPath", geckoDriverPath); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
@Test public void testEval_DateTest() { System.out.println("eval date fn"); String s; Object result; s = "Date(0,\"MM-dd-yy\")"; result = FParser.eval(s); assertTrue(result.toString().matches("(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])-\\d{2}"), "date " + result); s = "Date(0,\"MM dd yyyy\")"; result = FParser.eval(s); assertTrue(result.toString().matches("(0[1-9]|1[012]) (0[1-9]|[12][0-9]|3[01]) \\d{4}"), "date " + result); s = "Date(0,\"MM:dd:yyyy\")"; result = FParser.eval(s); assertTrue(result.toString().matches("(0[1-9]|1[012]):(0[1-9]|[12][0-9]|3[01]):\\d{4}"), "date " + result); s = "Date(0,\"dd/MM/yyyy\")"; result = FParser.eval(s); assertTrue(result.toString().matches("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/\\d{4}"), "date " + result); }
public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); }
FParser { public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); } }
FParser { public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); } }
FParser { public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); }
FParser { public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); static List<String> FUNCTIONS; }
@Test(invocationCount = 10) public void testEvaljs() { System.out.println("Evaljs"); String script = "floor(100 + random() * 900)"; String result = FParser.evaljs(script); assertTrue(result.matches("[0-9]{3}"), "Test random "); script = "'test'+ floor(100 + random() * 900)+'[email protected]'"; result = (String) JSONValue.parse(FParser.evaljs(script)); assertTrue(result.matches("test[0-9]{3}[email protected]"), "Test random email "); }
public static String evaljs(String script) { try { return JS.eval("JSON.stringify(" + script + ")").toString(); } catch (ScriptException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return "undefined"; }
FParser { public static String evaljs(String script) { try { return JS.eval("JSON.stringify(" + script + ")").toString(); } catch (ScriptException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return "undefined"; } }
FParser { public static String evaljs(String script) { try { return JS.eval("JSON.stringify(" + script + ")").toString(); } catch (ScriptException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return "undefined"; } }
FParser { public static String evaljs(String script) { try { return JS.eval("JSON.stringify(" + script + ")").toString(); } catch (ScriptException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return "undefined"; } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); }
FParser { public static String evaljs(String script) { try { return JS.eval("JSON.stringify(" + script + ")").toString(); } catch (ScriptException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return "undefined"; } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); static List<String> FUNCTIONS; }
@Test public void testResolveContextVars() { System.out.println("resolveContextVars"); String in = "this is a {scenario}/{testset} -> {testset}/{release} for {project}.{release}.{testcase} "; String expResult = "this is a myscn/ts -> ts/rel for pro.rel.tc "; String result = KeyMap.resolveContextVars(in, vMap); assertEquals(expResult, result); }
public static String resolveContextVars(String in, Map<?,?> vMap) { return replaceKeys(in, CONTEXT_VARS, true, 1, vMap); }
KeyMap { public static String resolveContextVars(String in, Map<?,?> vMap) { return replaceKeys(in, CONTEXT_VARS, true, 1, vMap); } }
KeyMap { public static String resolveContextVars(String in, Map<?,?> vMap) { return replaceKeys(in, CONTEXT_VARS, true, 1, vMap); } }
KeyMap { public static String resolveContextVars(String in, Map<?,?> vMap) { return replaceKeys(in, CONTEXT_VARS, true, 1, vMap); } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); }
KeyMap { public static String resolveContextVars(String in, Map<?,?> vMap) { return replaceKeys(in, CONTEXT_VARS, true, 1, vMap); } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); static final Pattern CONTEXT_VARS; static final Pattern ENV_VARS; static final Pattern USER_VARS; }
@Test public void testResolveEnvVars() { System.out.println("resolveEnvVars"); String in = "${val.1}-${var.1}-${val.2}-${val.1}-${val.3}-${val.4}-${var.4}-${var.1}-${var.2}-"; String expResult = "1-x-b-1-c-val.4-var.4-x-y-"; String result = KeyMap.resolveEnvVars(in); assertEquals(expResult, result); }
public static String resolveEnvVars(String in) { return replaceKeys(in, ENV_VARS); }
KeyMap { public static String resolveEnvVars(String in) { return replaceKeys(in, ENV_VARS); } }
KeyMap { public static String resolveEnvVars(String in) { return replaceKeys(in, ENV_VARS); } }
KeyMap { public static String resolveEnvVars(String in) { return replaceKeys(in, ENV_VARS); } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); }
KeyMap { public static String resolveEnvVars(String in) { return replaceKeys(in, ENV_VARS); } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); static final Pattern CONTEXT_VARS; static final Pattern ENV_VARS; static final Pattern USER_VARS; }
@Test public void testReplaceKeysUserVariables() { System.out.println("replaceKeys"); String in = "this is a %scenario%/%testset% -> %testset%/%release% for %project%.%testcase%/%%release%%. "; boolean preserveKeys = true; String result; String expResult = "this is a myscn/ts -> ts/rel for pro.tc/%rel%. "; result = KeyMap.replaceKeys(in, KeyMap.USER_VARS, preserveKeys, 1, vMap); assertEquals(expResult, result); expResult = "this is a myscn/ts -> ts/rel for pro.tc/L2. "; result = KeyMap.replaceKeys(in, KeyMap.USER_VARS, preserveKeys, 2, vMap); assertEquals(expResult, result); }
public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; }
KeyMap { public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; } }
KeyMap { public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; } }
KeyMap { public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); }
KeyMap { public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); static final Pattern CONTEXT_VARS; static final Pattern ENV_VARS; static final Pattern USER_VARS; }
@Test public void testReplaceKeys_String_Pattern() { System.out.println("replaceKeys"); String in = "${val.1}-${var.1}-${val.2}-${val.1}-${val.3}-${val.4}-${var.4}-${var.1}-${var.2}-"; String expResult = "1-x-b-1-c-val.4-var.4-x-y-"; String result = KeyMap.replaceKeys(in, KeyMap.ENV_VARS); assertEquals(expResult, result); }
public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; }
KeyMap { public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; } }
KeyMap { public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; } }
KeyMap { public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); }
KeyMap { public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; if (maps != null) { for (Map<?, ?> map : maps) { if ((resolved = map.containsKey(key))) { out = out.replace(match, Objects.toString(map.get(key))); break; } } } if (!resolved && !preserveKeys) { out = out.replace(match, key); } } in=out; } return out; } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps); static String replaceKeys(String in, Pattern p); static String resolveSystemVars(String in); static final Pattern CONTEXT_VARS; static final Pattern ENV_VARS; static final Pattern USER_VARS; }
@Test(enabled = false) public void testGetPrefLocation() { System.out.println("getPrefLocation"); File file = new File(ChromeEmulators.getPrefLocation(), "Preferences"); if (!file.exists()) { System.out.println(file.getAbsolutePath()); System.out.println("------------------------"); Stream.of(file.listFiles()) .map(File::getAbsolutePath).forEach(System.out::println); fail("Unable to fine preference file"); } }
public static String getPrefLocation() { if (SystemUtils.IS_OS_WINDOWS) { return SystemUtils.getUserHome().getAbsolutePath() + "/AppData/Local/Google/Chrome/User Data/Default"; } if (SystemUtils.IS_OS_MAC_OSX) { return SystemUtils.getUserHome().getAbsolutePath()+"/Library/Application Support/Google/Chrome/Default"; } if (SystemUtils.IS_OS_LINUX) { return SystemUtils.getUserHome().getAbsolutePath()+"/.config/google-chrome/Default"; } return "OSNotConfigured"; }
ChromeEmulators { public static String getPrefLocation() { if (SystemUtils.IS_OS_WINDOWS) { return SystemUtils.getUserHome().getAbsolutePath() + "/AppData/Local/Google/Chrome/User Data/Default"; } if (SystemUtils.IS_OS_MAC_OSX) { return SystemUtils.getUserHome().getAbsolutePath()+"/Library/Application Support/Google/Chrome/Default"; } if (SystemUtils.IS_OS_LINUX) { return SystemUtils.getUserHome().getAbsolutePath()+"/.config/google-chrome/Default"; } return "OSNotConfigured"; } }
ChromeEmulators { public static String getPrefLocation() { if (SystemUtils.IS_OS_WINDOWS) { return SystemUtils.getUserHome().getAbsolutePath() + "/AppData/Local/Google/Chrome/User Data/Default"; } if (SystemUtils.IS_OS_MAC_OSX) { return SystemUtils.getUserHome().getAbsolutePath()+"/Library/Application Support/Google/Chrome/Default"; } if (SystemUtils.IS_OS_LINUX) { return SystemUtils.getUserHome().getAbsolutePath()+"/.config/google-chrome/Default"; } return "OSNotConfigured"; } }
ChromeEmulators { public static String getPrefLocation() { if (SystemUtils.IS_OS_WINDOWS) { return SystemUtils.getUserHome().getAbsolutePath() + "/AppData/Local/Google/Chrome/User Data/Default"; } if (SystemUtils.IS_OS_MAC_OSX) { return SystemUtils.getUserHome().getAbsolutePath()+"/Library/Application Support/Google/Chrome/Default"; } if (SystemUtils.IS_OS_LINUX) { return SystemUtils.getUserHome().getAbsolutePath()+"/.config/google-chrome/Default"; } return "OSNotConfigured"; } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); }
ChromeEmulators { public static String getPrefLocation() { if (SystemUtils.IS_OS_WINDOWS) { return SystemUtils.getUserHome().getAbsolutePath() + "/AppData/Local/Google/Chrome/User Data/Default"; } if (SystemUtils.IS_OS_MAC_OSX) { return SystemUtils.getUserHome().getAbsolutePath()+"/Library/Application Support/Google/Chrome/Default"; } if (SystemUtils.IS_OS_LINUX) { return SystemUtils.getUserHome().getAbsolutePath()+"/.config/google-chrome/Default"; } return "OSNotConfigured"; } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); }
@Test(enabled = false) public void testSync() { System.out.println("sync"); ChromeEmulators.sync(); assertTrue(!ChromeEmulators.getEmulatorsList().isEmpty(), "EmulatorsList is Empty"); }
public static void sync() { try { LOG.info("Trying to load emulators from Chrome Installation"); File file = new File(getPrefLocation(), "Preferences"); if (file.exists()) { Map map = MAPPER.readValue(file, Map.class); Map devtools = (Map) map.get("devtools"); Map prefs = (Map) devtools.get("preferences"); String stdemulators = (String) prefs.get("standardEmulatedDeviceList"); List list = MAPPER.readValue(stdemulators, List.class); EMULATORS.clear(); EMULATORS.addAll( (List<String>) list.stream() .map((device) -> { return ((Map) device).get("title"); }) .map((val) -> val.toString()) .collect(Collectors.toList())); saveList(); } else { LOG.severe("Either Chrome is not installed or OS not supported"); } } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } }
ChromeEmulators { public static void sync() { try { LOG.info("Trying to load emulators from Chrome Installation"); File file = new File(getPrefLocation(), "Preferences"); if (file.exists()) { Map map = MAPPER.readValue(file, Map.class); Map devtools = (Map) map.get("devtools"); Map prefs = (Map) devtools.get("preferences"); String stdemulators = (String) prefs.get("standardEmulatedDeviceList"); List list = MAPPER.readValue(stdemulators, List.class); EMULATORS.clear(); EMULATORS.addAll( (List<String>) list.stream() .map((device) -> { return ((Map) device).get("title"); }) .map((val) -> val.toString()) .collect(Collectors.toList())); saveList(); } else { LOG.severe("Either Chrome is not installed or OS not supported"); } } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } } }
ChromeEmulators { public static void sync() { try { LOG.info("Trying to load emulators from Chrome Installation"); File file = new File(getPrefLocation(), "Preferences"); if (file.exists()) { Map map = MAPPER.readValue(file, Map.class); Map devtools = (Map) map.get("devtools"); Map prefs = (Map) devtools.get("preferences"); String stdemulators = (String) prefs.get("standardEmulatedDeviceList"); List list = MAPPER.readValue(stdemulators, List.class); EMULATORS.clear(); EMULATORS.addAll( (List<String>) list.stream() .map((device) -> { return ((Map) device).get("title"); }) .map((val) -> val.toString()) .collect(Collectors.toList())); saveList(); } else { LOG.severe("Either Chrome is not installed or OS not supported"); } } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } } }
ChromeEmulators { public static void sync() { try { LOG.info("Trying to load emulators from Chrome Installation"); File file = new File(getPrefLocation(), "Preferences"); if (file.exists()) { Map map = MAPPER.readValue(file, Map.class); Map devtools = (Map) map.get("devtools"); Map prefs = (Map) devtools.get("preferences"); String stdemulators = (String) prefs.get("standardEmulatedDeviceList"); List list = MAPPER.readValue(stdemulators, List.class); EMULATORS.clear(); EMULATORS.addAll( (List<String>) list.stream() .map((device) -> { return ((Map) device).get("title"); }) .map((val) -> val.toString()) .collect(Collectors.toList())); saveList(); } else { LOG.severe("Either Chrome is not installed or OS not supported"); } } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); }
ChromeEmulators { public static void sync() { try { LOG.info("Trying to load emulators from Chrome Installation"); File file = new File(getPrefLocation(), "Preferences"); if (file.exists()) { Map map = MAPPER.readValue(file, Map.class); Map devtools = (Map) map.get("devtools"); Map prefs = (Map) devtools.get("preferences"); String stdemulators = (String) prefs.get("standardEmulatedDeviceList"); List list = MAPPER.readValue(stdemulators, List.class); EMULATORS.clear(); EMULATORS.addAll( (List<String>) list.stream() .map((device) -> { return ((Map) device).get("title"); }) .map((val) -> val.toString()) .collect(Collectors.toList())); saveList(); } else { LOG.severe("Either Chrome is not installed or OS not supported"); } } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); }
@Test(enabled = false) public void testGetEmulatorsList() { System.out.println("getEmulatorsList"); List<String> result = ChromeEmulators.getEmulatorsList(); assertTrue(Stream.of("Nexus 5", "Galaxy S5", "Nexus 6P", "iPhone 5", "iPhone 6 Plus") .allMatch(result::contains), "Some/all emulators missing in the EmulatorsList" ); }
public static List<String> getEmulatorsList() { load(); return EMULATORS; }
ChromeEmulators { public static List<String> getEmulatorsList() { load(); return EMULATORS; } }
ChromeEmulators { public static List<String> getEmulatorsList() { load(); return EMULATORS; } }
ChromeEmulators { public static List<String> getEmulatorsList() { load(); return EMULATORS; } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); }
ChromeEmulators { public static List<String> getEmulatorsList() { load(); return EMULATORS; } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); }
@Test(enabled = false,description = "http-get of remote address") public void testGetHttp() throws Exception { System.out.println("Get-http"); URL targetUrl = new URL("http: BasicHttpClient instance = new BasicHttpClient(targetUrl, "anon", "anon"); JSONObject result = instance.Get(targetUrl, getArgs.toJSONString()); assertEquals(result.get("args"), getArgs); }
public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } BasicHttpClient(URL url, String userName, String password); BasicHttpClient(URL url, String userName, String password, Map<String, String> config); }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } BasicHttpClient(URL url, String userName, String password); BasicHttpClient(URL url, String userName, String password, Map<String, String> config); void auth(HttpRequest req); @Override CloseableHttpResponse execute(HttpUriRequest req); JSONObject put(URL targetUrl, String data); JSONObject put(URL targetUrl, String data, String accessKey, String value); void setHeader(HttpPut httpput); void addHeader(HttpGet httpGet, String Key, String Value); void setPutEntity(String xmlstr, HttpPut httpput); JSONObject post(URL targetUrl, String payload); JSONObject post(URL targetUrl, File toUplod, String key, String value); JSONObject post(URL targetUrl, File toUplod); JSONObject put(URL targetUrl, File toUplod); JSONObject post(URL targetUrl, List<NameValuePair> parameters); JSONObject post(URL targetUrl, String data, File toUplod); void setHeader(HttpPost httppost); @Override HttpResponse doPost(HttpPost httpPost); HttpResponse doPost(HttpPost httpPost, String key, String value); void setPostEntity(File toUplod, HttpPost httppost); void setPutEntity(File toUplod, HttpPut httpput); void setPostEntityJ(File toUplod, HttpPost httppost); void setPostEntity(String data, File file, HttpPost httppost); void setPostEntity(String jsonStr, HttpPost httppost); void setPostEntity(List<NameValuePair> params, HttpPost httppost); JSONObject patch(URL targetUrl, String payload); void setHeader(HttpPatch httppatch); void setPatchEntity(String jsonStr, HttpPatch httppatch); JSONObject Get(URL targetUrl); JSONObject Get(URL targetUrl, String key, String val); JSONObject Get(URL targetUrl, String key, String val, String empty); JSONObject Get(URL targetUrl, boolean isJwtToken, String key, String val ); JSONObject Get(URL targetUrl, String jsonStr); void setHeader(HttpGet httpGet); }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } BasicHttpClient(URL url, String userName, String password); BasicHttpClient(URL url, String userName, String password, Map<String, String> config); void auth(HttpRequest req); @Override CloseableHttpResponse execute(HttpUriRequest req); JSONObject put(URL targetUrl, String data); JSONObject put(URL targetUrl, String data, String accessKey, String value); void setHeader(HttpPut httpput); void addHeader(HttpGet httpGet, String Key, String Value); void setPutEntity(String xmlstr, HttpPut httpput); JSONObject post(URL targetUrl, String payload); JSONObject post(URL targetUrl, File toUplod, String key, String value); JSONObject post(URL targetUrl, File toUplod); JSONObject put(URL targetUrl, File toUplod); JSONObject post(URL targetUrl, List<NameValuePair> parameters); JSONObject post(URL targetUrl, String data, File toUplod); void setHeader(HttpPost httppost); @Override HttpResponse doPost(HttpPost httpPost); HttpResponse doPost(HttpPost httpPost, String key, String value); void setPostEntity(File toUplod, HttpPost httppost); void setPutEntity(File toUplod, HttpPut httpput); void setPostEntityJ(File toUplod, HttpPost httppost); void setPostEntity(String data, File file, HttpPost httppost); void setPostEntity(String jsonStr, HttpPost httppost); void setPostEntity(List<NameValuePair> params, HttpPost httppost); JSONObject patch(URL targetUrl, String payload); void setHeader(HttpPatch httppatch); void setPatchEntity(String jsonStr, HttpPatch httppatch); JSONObject Get(URL targetUrl); JSONObject Get(URL targetUrl, String key, String val); JSONObject Get(URL targetUrl, String key, String val, String empty); JSONObject Get(URL targetUrl, boolean isJwtToken, String key, String val ); JSONObject Get(URL targetUrl, String jsonStr); void setHeader(HttpGet httpGet); final URL url; }
@Test public void testGetChromeDriverPath() { String expResult; if (isWin) { expResult = "./lib/Drivers/chromedriver.exe"; } else { expResult = "./lib/Drivers/chromedriver"; } String result = ds.getChromeDriverPath(); assertEquals(result, expResult); }
public String getChromeDriverPath() { return getProperty("ChromeDriverPath", chromeDriverPath); }
DriverSettings extends AbstractPropSettings { public String getChromeDriverPath() { return getProperty("ChromeDriverPath", chromeDriverPath); } }
DriverSettings extends AbstractPropSettings { public String getChromeDriverPath() { return getProperty("ChromeDriverPath", chromeDriverPath); } DriverSettings(String location); }
DriverSettings extends AbstractPropSettings { public String getChromeDriverPath() { return getProperty("ChromeDriverPath", chromeDriverPath); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
DriverSettings extends AbstractPropSettings { public String getChromeDriverPath() { return getProperty("ChromeDriverPath", chromeDriverPath); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
@Test(enabled = false,description = "https-get of remote address") public void testGetHttps() throws Exception { System.out.println("Get-https"); URL targetUrl = new URL("https: BasicHttpClient instance = new BasicHttpClient(targetUrl, "anon", "anon"); JSONObject result = instance.Get(targetUrl, getArgs.toJSONString()); assertEquals(result.get("args"), getArgs); }
public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } BasicHttpClient(URL url, String userName, String password); BasicHttpClient(URL url, String userName, String password, Map<String, String> config); }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } BasicHttpClient(URL url, String userName, String password); BasicHttpClient(URL url, String userName, String password, Map<String, String> config); void auth(HttpRequest req); @Override CloseableHttpResponse execute(HttpUriRequest req); JSONObject put(URL targetUrl, String data); JSONObject put(URL targetUrl, String data, String accessKey, String value); void setHeader(HttpPut httpput); void addHeader(HttpGet httpGet, String Key, String Value); void setPutEntity(String xmlstr, HttpPut httpput); JSONObject post(URL targetUrl, String payload); JSONObject post(URL targetUrl, File toUplod, String key, String value); JSONObject post(URL targetUrl, File toUplod); JSONObject put(URL targetUrl, File toUplod); JSONObject post(URL targetUrl, List<NameValuePair> parameters); JSONObject post(URL targetUrl, String data, File toUplod); void setHeader(HttpPost httppost); @Override HttpResponse doPost(HttpPost httpPost); HttpResponse doPost(HttpPost httpPost, String key, String value); void setPostEntity(File toUplod, HttpPost httppost); void setPutEntity(File toUplod, HttpPut httpput); void setPostEntityJ(File toUplod, HttpPost httppost); void setPostEntity(String data, File file, HttpPost httppost); void setPostEntity(String jsonStr, HttpPost httppost); void setPostEntity(List<NameValuePair> params, HttpPost httppost); JSONObject patch(URL targetUrl, String payload); void setHeader(HttpPatch httppatch); void setPatchEntity(String jsonStr, HttpPatch httppatch); JSONObject Get(URL targetUrl); JSONObject Get(URL targetUrl, String key, String val); JSONObject Get(URL targetUrl, String key, String val, String empty); JSONObject Get(URL targetUrl, boolean isJwtToken, String key, String val ); JSONObject Get(URL targetUrl, String jsonStr); void setHeader(HttpGet httpGet); }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } BasicHttpClient(URL url, String userName, String password); BasicHttpClient(URL url, String userName, String password, Map<String, String> config); void auth(HttpRequest req); @Override CloseableHttpResponse execute(HttpUriRequest req); JSONObject put(URL targetUrl, String data); JSONObject put(URL targetUrl, String data, String accessKey, String value); void setHeader(HttpPut httpput); void addHeader(HttpGet httpGet, String Key, String Value); void setPutEntity(String xmlstr, HttpPut httpput); JSONObject post(URL targetUrl, String payload); JSONObject post(URL targetUrl, File toUplod, String key, String value); JSONObject post(URL targetUrl, File toUplod); JSONObject put(URL targetUrl, File toUplod); JSONObject post(URL targetUrl, List<NameValuePair> parameters); JSONObject post(URL targetUrl, String data, File toUplod); void setHeader(HttpPost httppost); @Override HttpResponse doPost(HttpPost httpPost); HttpResponse doPost(HttpPost httpPost, String key, String value); void setPostEntity(File toUplod, HttpPost httppost); void setPutEntity(File toUplod, HttpPut httpput); void setPostEntityJ(File toUplod, HttpPost httppost); void setPostEntity(String data, File file, HttpPost httppost); void setPostEntity(String jsonStr, HttpPost httppost); void setPostEntity(List<NameValuePair> params, HttpPost httppost); JSONObject patch(URL targetUrl, String payload); void setHeader(HttpPatch httppatch); void setPatchEntity(String jsonStr, HttpPatch httppatch); JSONObject Get(URL targetUrl); JSONObject Get(URL targetUrl, String key, String val); JSONObject Get(URL targetUrl, String key, String val, String empty); JSONObject Get(URL targetUrl, boolean isJwtToken, String key, String val ); JSONObject Get(URL targetUrl, String jsonStr); void setHeader(HttpGet httpGet); final URL url; }
@Test(enabled = false,description = "http-get of local address") public void testGetHttpLocal() throws Exception { System.out.println("Get-http-local"); URL targetUrl = new URL("http: BasicHttpClient instance = new BasicHttpClient(targetUrl, "anon", "anon"); JSONObject result = instance.Get(targetUrl, "data", "vola"); assertEquals(result.toString(), "{\"data\":\"vola\"}"); }
public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } BasicHttpClient(URL url, String userName, String password); BasicHttpClient(URL url, String userName, String password, Map<String, String> config); }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } BasicHttpClient(URL url, String userName, String password); BasicHttpClient(URL url, String userName, String password, Map<String, String> config); void auth(HttpRequest req); @Override CloseableHttpResponse execute(HttpUriRequest req); JSONObject put(URL targetUrl, String data); JSONObject put(URL targetUrl, String data, String accessKey, String value); void setHeader(HttpPut httpput); void addHeader(HttpGet httpGet, String Key, String Value); void setPutEntity(String xmlstr, HttpPut httpput); JSONObject post(URL targetUrl, String payload); JSONObject post(URL targetUrl, File toUplod, String key, String value); JSONObject post(URL targetUrl, File toUplod); JSONObject put(URL targetUrl, File toUplod); JSONObject post(URL targetUrl, List<NameValuePair> parameters); JSONObject post(URL targetUrl, String data, File toUplod); void setHeader(HttpPost httppost); @Override HttpResponse doPost(HttpPost httpPost); HttpResponse doPost(HttpPost httpPost, String key, String value); void setPostEntity(File toUplod, HttpPost httppost); void setPutEntity(File toUplod, HttpPut httpput); void setPostEntityJ(File toUplod, HttpPost httppost); void setPostEntity(String data, File file, HttpPost httppost); void setPostEntity(String jsonStr, HttpPost httppost); void setPostEntity(List<NameValuePair> params, HttpPost httppost); JSONObject patch(URL targetUrl, String payload); void setHeader(HttpPatch httppatch); void setPatchEntity(String jsonStr, HttpPatch httppatch); JSONObject Get(URL targetUrl); JSONObject Get(URL targetUrl, String key, String val); JSONObject Get(URL targetUrl, String key, String val, String empty); JSONObject Get(URL targetUrl, boolean isJwtToken, String key, String val ); JSONObject Get(URL targetUrl, String jsonStr); void setHeader(HttpGet httpGet); }
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } BasicHttpClient(URL url, String userName, String password); BasicHttpClient(URL url, String userName, String password, Map<String, String> config); void auth(HttpRequest req); @Override CloseableHttpResponse execute(HttpUriRequest req); JSONObject put(URL targetUrl, String data); JSONObject put(URL targetUrl, String data, String accessKey, String value); void setHeader(HttpPut httpput); void addHeader(HttpGet httpGet, String Key, String Value); void setPutEntity(String xmlstr, HttpPut httpput); JSONObject post(URL targetUrl, String payload); JSONObject post(URL targetUrl, File toUplod, String key, String value); JSONObject post(URL targetUrl, File toUplod); JSONObject put(URL targetUrl, File toUplod); JSONObject post(URL targetUrl, List<NameValuePair> parameters); JSONObject post(URL targetUrl, String data, File toUplod); void setHeader(HttpPost httppost); @Override HttpResponse doPost(HttpPost httpPost); HttpResponse doPost(HttpPost httpPost, String key, String value); void setPostEntity(File toUplod, HttpPost httppost); void setPutEntity(File toUplod, HttpPut httpput); void setPostEntityJ(File toUplod, HttpPost httppost); void setPostEntity(String data, File file, HttpPost httppost); void setPostEntity(String jsonStr, HttpPost httppost); void setPostEntity(List<NameValuePair> params, HttpPost httppost); JSONObject patch(URL targetUrl, String payload); void setHeader(HttpPatch httppatch); void setPatchEntity(String jsonStr, HttpPatch httppatch); JSONObject Get(URL targetUrl); JSONObject Get(URL targetUrl, String key, String val); JSONObject Get(URL targetUrl, String key, String val, String empty); JSONObject Get(URL targetUrl, boolean isJwtToken, String key, String val ); JSONObject Get(URL targetUrl, String jsonStr); void setHeader(HttpGet httpGet); final URL url; }
@Test(enabled = false) public void testConnection() throws MalformedURLException { JIRASync sync = new JIRASync(Data.server, Data.uname, Data.pass, Data.project); Assert.assertTrue(sync.isConnected()); }
public boolean isConnected() { try { DLogger.Log(client.Get(new URL(client.url + PROJECT)).toString()); return true; } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); return false; } }
JIRAClient { public boolean isConnected() { try { DLogger.Log(client.Get(new URL(client.url + PROJECT)).toString()); return true; } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); return false; } } }
JIRAClient { public boolean isConnected() { try { DLogger.Log(client.Get(new URL(client.url + PROJECT)).toString()); return true; } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); return false; } } JIRAClient(String urlStr, String userName, String password, Map options); }
JIRAClient { public boolean isConnected() { try { DLogger.Log(client.Get(new URL(client.url + PROJECT)).toString()); return true; } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); return false; } } JIRAClient(String urlStr, String userName, String password, Map options); int updateResult(int status, String tc, String ts, String rc, String proj); void updateResult(int status, int eid); String addAttachment(int eid, File attachment); @SuppressWarnings("unchecked") JSONObject createIssue(JSONObject issue, List<File> attachments); @SuppressWarnings("unchecked") static JSONObject getJsonified(LinkedHashMap<String, String> dataMap); boolean containsProject(String project); boolean isConnected(); }
JIRAClient { public boolean isConnected() { try { DLogger.Log(client.Get(new URL(client.url + PROJECT)).toString()); return true; } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); return false; } } JIRAClient(String urlStr, String userName, String password, Map options); int updateResult(int status, String tc, String ts, String rc, String proj); void updateResult(int status, int eid); String addAttachment(int eid, File attachment); @SuppressWarnings("unchecked") JSONObject createIssue(JSONObject issue, List<File> attachments); @SuppressWarnings("unchecked") static JSONObject getJsonified(LinkedHashMap<String, String> dataMap); boolean containsProject(String project); boolean isConnected(); static final String ISSUE; }
@Test(enabled = false) public void testCreateIssue_JSONObject_List() throws MalformedURLException { JSONObject res = null; JIRAClient jc = new JIRAClient(Data.server, Data.uname, Data.pass, null); Map issue = getIssue(Data.project); List<File> attach = null; res = jc.createIssue((JSONObject) issue, attach); }
@SuppressWarnings("unchecked") public JSONObject createIssue(JSONObject issue, List<File> attachments) { JSONObject res = null; try { res = client.post(new URL(client.url + ISSUE), issue.toString()); String restAttach = ISSUE_ATTACHMENTS.replace("issuekey", (String) res.get("id")); if (attachments != null && !attachments.isEmpty()) { List<JSONObject> attchRes = new ArrayList<>(); res.put("Attachments", attchRes); for (File f : attachments) { attchRes.add(client.post(new URL(client.url + restAttach), f)); } } else { LOG.log(Level.INFO, "no attachments to upload"); } LOG.log(Level.INFO, "issue response {0}", res.toString()); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return res; }
JIRAClient { @SuppressWarnings("unchecked") public JSONObject createIssue(JSONObject issue, List<File> attachments) { JSONObject res = null; try { res = client.post(new URL(client.url + ISSUE), issue.toString()); String restAttach = ISSUE_ATTACHMENTS.replace("issuekey", (String) res.get("id")); if (attachments != null && !attachments.isEmpty()) { List<JSONObject> attchRes = new ArrayList<>(); res.put("Attachments", attchRes); for (File f : attachments) { attchRes.add(client.post(new URL(client.url + restAttach), f)); } } else { LOG.log(Level.INFO, "no attachments to upload"); } LOG.log(Level.INFO, "issue response {0}", res.toString()); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return res; } }
JIRAClient { @SuppressWarnings("unchecked") public JSONObject createIssue(JSONObject issue, List<File> attachments) { JSONObject res = null; try { res = client.post(new URL(client.url + ISSUE), issue.toString()); String restAttach = ISSUE_ATTACHMENTS.replace("issuekey", (String) res.get("id")); if (attachments != null && !attachments.isEmpty()) { List<JSONObject> attchRes = new ArrayList<>(); res.put("Attachments", attchRes); for (File f : attachments) { attchRes.add(client.post(new URL(client.url + restAttach), f)); } } else { LOG.log(Level.INFO, "no attachments to upload"); } LOG.log(Level.INFO, "issue response {0}", res.toString()); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return res; } JIRAClient(String urlStr, String userName, String password, Map options); }
JIRAClient { @SuppressWarnings("unchecked") public JSONObject createIssue(JSONObject issue, List<File> attachments) { JSONObject res = null; try { res = client.post(new URL(client.url + ISSUE), issue.toString()); String restAttach = ISSUE_ATTACHMENTS.replace("issuekey", (String) res.get("id")); if (attachments != null && !attachments.isEmpty()) { List<JSONObject> attchRes = new ArrayList<>(); res.put("Attachments", attchRes); for (File f : attachments) { attchRes.add(client.post(new URL(client.url + restAttach), f)); } } else { LOG.log(Level.INFO, "no attachments to upload"); } LOG.log(Level.INFO, "issue response {0}", res.toString()); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return res; } JIRAClient(String urlStr, String userName, String password, Map options); int updateResult(int status, String tc, String ts, String rc, String proj); void updateResult(int status, int eid); String addAttachment(int eid, File attachment); @SuppressWarnings("unchecked") JSONObject createIssue(JSONObject issue, List<File> attachments); @SuppressWarnings("unchecked") static JSONObject getJsonified(LinkedHashMap<String, String> dataMap); boolean containsProject(String project); boolean isConnected(); }
JIRAClient { @SuppressWarnings("unchecked") public JSONObject createIssue(JSONObject issue, List<File> attachments) { JSONObject res = null; try { res = client.post(new URL(client.url + ISSUE), issue.toString()); String restAttach = ISSUE_ATTACHMENTS.replace("issuekey", (String) res.get("id")); if (attachments != null && !attachments.isEmpty()) { List<JSONObject> attchRes = new ArrayList<>(); res.put("Attachments", attchRes); for (File f : attachments) { attchRes.add(client.post(new URL(client.url + restAttach), f)); } } else { LOG.log(Level.INFO, "no attachments to upload"); } LOG.log(Level.INFO, "issue response {0}", res.toString()); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return res; } JIRAClient(String urlStr, String userName, String password, Map options); int updateResult(int status, String tc, String ts, String rc, String proj); void updateResult(int status, int eid); String addAttachment(int eid, File attachment); @SuppressWarnings("unchecked") JSONObject createIssue(JSONObject issue, List<File> attachments); @SuppressWarnings("unchecked") static JSONObject getJsonified(LinkedHashMap<String, String> dataMap); boolean containsProject(String project); boolean isConnected(); static final String ISSUE; }
@Test public void testGetIEDriverPath() { String expResult = "./lib/Drivers/IEDriverServer.exe"; String result = ds.getIEDriverPath(); assertEquals(result, expResult); }
public String getIEDriverPath() { return getProperty("IEDriverPath", "./lib/Drivers/IEDriverServer.exe"); }
DriverSettings extends AbstractPropSettings { public String getIEDriverPath() { return getProperty("IEDriverPath", "./lib/Drivers/IEDriverServer.exe"); } }
DriverSettings extends AbstractPropSettings { public String getIEDriverPath() { return getProperty("IEDriverPath", "./lib/Drivers/IEDriverServer.exe"); } DriverSettings(String location); }
DriverSettings extends AbstractPropSettings { public String getIEDriverPath() { return getProperty("IEDriverPath", "./lib/Drivers/IEDriverServer.exe"); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
DriverSettings extends AbstractPropSettings { public String getIEDriverPath() { return getProperty("IEDriverPath", "./lib/Drivers/IEDriverServer.exe"); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
@Test public void testGetEdgeDriverPath() { String expResult = "./lib/Drivers/MicrosoftWebDriver.exe"; String result = ds.getEdgeDriverPath(); assertEquals(result, expResult); }
public String getEdgeDriverPath() { return getProperty("EdgeDriverPath", "./lib/Drivers/MicrosoftWebDriver.exe"); }
DriverSettings extends AbstractPropSettings { public String getEdgeDriverPath() { return getProperty("EdgeDriverPath", "./lib/Drivers/MicrosoftWebDriver.exe"); } }
DriverSettings extends AbstractPropSettings { public String getEdgeDriverPath() { return getProperty("EdgeDriverPath", "./lib/Drivers/MicrosoftWebDriver.exe"); } DriverSettings(String location); }
DriverSettings extends AbstractPropSettings { public String getEdgeDriverPath() { return getProperty("EdgeDriverPath", "./lib/Drivers/MicrosoftWebDriver.exe"); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
DriverSettings extends AbstractPropSettings { public String getEdgeDriverPath() { return getProperty("EdgeDriverPath", "./lib/Drivers/MicrosoftWebDriver.exe"); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
@Test public void testSetGeckcoDriverPath() { String path = "./lib/gk"; ds.setGeckcoDriverPath(path); assertEquals(ds.getGeckcoDriverPath(), path); }
public void setGeckcoDriverPath(String path) { setProperty("GeckoDriverPath", path); }
DriverSettings extends AbstractPropSettings { public void setGeckcoDriverPath(String path) { setProperty("GeckoDriverPath", path); } }
DriverSettings extends AbstractPropSettings { public void setGeckcoDriverPath(String path) { setProperty("GeckoDriverPath", path); } DriverSettings(String location); }
DriverSettings extends AbstractPropSettings { public void setGeckcoDriverPath(String path) { setProperty("GeckoDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
DriverSettings extends AbstractPropSettings { public void setGeckcoDriverPath(String path) { setProperty("GeckoDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
@Test public void testSetChromeDriverPath() { String path = "./lib/chrome"; ds.setChromeDriverPath(path); assertEquals(ds.getChromeDriverPath(), path); }
public void setChromeDriverPath(String path) { setProperty("ChromeDriverPath", path); }
DriverSettings extends AbstractPropSettings { public void setChromeDriverPath(String path) { setProperty("ChromeDriverPath", path); } }
DriverSettings extends AbstractPropSettings { public void setChromeDriverPath(String path) { setProperty("ChromeDriverPath", path); } DriverSettings(String location); }
DriverSettings extends AbstractPropSettings { public void setChromeDriverPath(String path) { setProperty("ChromeDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
DriverSettings extends AbstractPropSettings { public void setChromeDriverPath(String path) { setProperty("ChromeDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
@Test public void testSetIEDriverPath() { String path = "./lib/ie"; ds.setIEDriverPath(path); assertEquals(ds.getIEDriverPath(), path); }
public void setIEDriverPath(String path) { setProperty("IEDriverPath", path); }
DriverSettings extends AbstractPropSettings { public void setIEDriverPath(String path) { setProperty("IEDriverPath", path); } }
DriverSettings extends AbstractPropSettings { public void setIEDriverPath(String path) { setProperty("IEDriverPath", path); } DriverSettings(String location); }
DriverSettings extends AbstractPropSettings { public void setIEDriverPath(String path) { setProperty("IEDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
DriverSettings extends AbstractPropSettings { public void setIEDriverPath(String path) { setProperty("IEDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
@Test public void testSetEdgeDriverPath() { String path = "./lib/edge"; ds.setEdgeDriverPath(path); assertEquals(ds.getEdgeDriverPath(), path); }
public void setEdgeDriverPath(String path) { setProperty("EdgeDriverPath", path); }
DriverSettings extends AbstractPropSettings { public void setEdgeDriverPath(String path) { setProperty("EdgeDriverPath", path); } }
DriverSettings extends AbstractPropSettings { public void setEdgeDriverPath(String path) { setProperty("EdgeDriverPath", path); } DriverSettings(String location); }
DriverSettings extends AbstractPropSettings { public void setEdgeDriverPath(String path) { setProperty("EdgeDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
DriverSettings extends AbstractPropSettings { public void setEdgeDriverPath(String path) { setProperty("EdgeDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void setEdgeDriverPath(String path); String getFirefoxBinaryPath(); String getGeckcoDriverPath(); String getChromeDriverPath(); String getIEDriverPath(); String getEdgeDriverPath(); Boolean useProxy(); }
@Test public void testGetFuncList() { System.out.println("getFuncList"); String[] vals = {"Concat", "Random", "Round", "Pow", "Min", "Max", "Date"}; List<String> expResult = Arrays.asList(vals); Collections.sort(expResult); List<String> result = FParser.getFuncList(); Collections.sort(result); assertEquals(expResult.toString(), result.toString()); }
public static List<String> getFuncList() { return FUNCTIONS; }
FParser { public static List<String> getFuncList() { return FUNCTIONS; } }
FParser { public static List<String> getFuncList() { return FUNCTIONS; } }
FParser { public static List<String> getFuncList() { return FUNCTIONS; } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); }
FParser { public static List<String> getFuncList() { return FUNCTIONS; } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); static List<String> FUNCTIONS; }
@Test(invocationCount = 10) public void testEval() { System.out.println("Eval"); String s = "Concat(=Round(=Random(4)),[email protected])"; Object result = FParser.eval(s); assertTrue(result.toString().matches("[0-9]{4}[email protected]"), "random email " + result); }
public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); }
FParser { public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); } }
FParser { public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); } }
FParser { public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); }
FParser { public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); static List<String> FUNCTIONS; }
@Test public void test_messages_are_enqueued_to_redis() throws InterruptedException { LOGGER.debug("creating the logger"); Logger logger = LOGGER_CONTEXT_RESOURCE .getLoggerContext() .getLogger(RedisAppenderTest.class.getCanonicalName()); int expectedMessageCount = MIN_MESSAGE_COUNT + RANDOM.nextInt(MAX_MESSAGE_COUNT - MIN_MESSAGE_COUNT); LOGGER.debug("logging %d messages", expectedMessageCount); LogMessage[] expectedLogMessages = LogMessage.createRandomArray(expectedMessageCount); for (LogMessage expectedLogMessage : expectedLogMessages) { logger.log(expectedLogMessage.level, expectedLogMessage.message); } LOGGER.debug("waiting for throttler to kick in"); Thread.sleep(1_000); LOGGER.debug("checking logged messages"); Jedis redisClient = REDIS_CLIENT_RESOURCE.getClient(); for (int messageIndex = 0; messageIndex < expectedMessageCount; messageIndex++) { LogMessage expectedLogMessage = expectedLogMessages[messageIndex]; String expectedSerializedMessage = String.format( "%s %s", expectedLogMessage.level, expectedLogMessage.message); String actualSerializedMessage = redisClient.lpop(RedisAppenderTestConfig.REDIS_KEY); try { assertThat(actualSerializedMessage).isEqualTo(expectedSerializedMessage); } catch (ComparisonFailure comparisonFailure) { String message = String.format( "comparison failure (messageIndex=%d, messageCount=%d)", messageIndex, expectedMessageCount); throw new RuntimeException(message, comparisonFailure); } } Appender appender = LOGGER_CONTEXT_RESOURCE .getLoggerContext() .getConfiguration() .getAppender(RedisAppenderTestConfig.LOG4J2_APPENDER_NAME); assertThat(appender).isInstanceOf(RedisAppender.class); RedisThrottlerJmxBean jmxBean = ((RedisAppender) appender).getJmxBean(); assertThat(jmxBean.getTotalEventCount()).isEqualTo(expectedMessageCount); assertThat(jmxBean.getIgnoredEventCount()).isEqualTo(0); assertThat(jmxBean.getEventRateLimitFailureCount()).isEqualTo(0); assertThat(jmxBean.getByteRateLimitFailureCount()).isEqualTo(0); assertThat(jmxBean.getUnavailableBufferSpaceFailureCount()).isEqualTo(0); assertThat(jmxBean.getRedisPushSuccessCount()).isEqualTo(expectedMessageCount); assertThat(jmxBean.getRedisPushFailureCount()).isEqualTo(0); }
public RedisThrottlerJmxBean getJmxBean() { return throttler.getJmxBean(); }
RedisAppender implements Appender { public RedisThrottlerJmxBean getJmxBean() { return throttler.getJmxBean(); } }
RedisAppender implements Appender { public RedisThrottlerJmxBean getJmxBean() { return throttler.getJmxBean(); } private RedisAppender(Builder builder); }
RedisAppender implements Appender { public RedisThrottlerJmxBean getJmxBean() { return throttler.getJmxBean(); } private RedisAppender(Builder builder); Configuration getConfig(); @Override String getName(); @Override Layout<? extends Serializable> getLayout(); @Override boolean ignoreExceptions(); @Override ErrorHandler getHandler(); @Override void setHandler(ErrorHandler errorHandler); @Override State getState(); RedisThrottlerJmxBean getJmxBean(); @Override void append(LogEvent event); @Override void initialize(); @Override void start(); @Override synchronized void stop(); @Override boolean isStarted(); @Override boolean isStopped(); @Override String toString(); @PluginBuilderFactory static Builder newBuilder(); }
RedisAppender implements Appender { public RedisThrottlerJmxBean getJmxBean() { return throttler.getJmxBean(); } private RedisAppender(Builder builder); Configuration getConfig(); @Override String getName(); @Override Layout<? extends Serializable> getLayout(); @Override boolean ignoreExceptions(); @Override ErrorHandler getHandler(); @Override void setHandler(ErrorHandler errorHandler); @Override State getState(); RedisThrottlerJmxBean getJmxBean(); @Override void append(LogEvent event); @Override void initialize(); @Override void start(); @Override synchronized void stop(); @Override boolean isStarted(); @Override boolean isStopped(); @Override String toString(); @PluginBuilderFactory static Builder newBuilder(); }
@Test public void testGetKeyLock() { KeyLock keylock = KeyLockManager.getKeyLock(TEST1); assertEquals(true, keylock != null); }
public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params); static Object lockMethod(String lockKey1, String lockKey2, String keyType, KeylockFunction func, Object... params); }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params); static Object lockMethod(String lockKey1, String lockKey2, String keyType, KeylockFunction func, Object... params); static int KEY_LOCK_EXPIRE_TIME; static int KEY_LOCK_CYCLE_SLEEP_TIME; static Map<String, KeyLock> keyLockMap; }
@Test public void testAddMsgListener() throws Exception { TestMsgListener testMsgListener = new TestMsgListener(); boolean result = MsgManager.addMsgListener(testMsgListener); MsgManager.dispatchMsg("createuser", 111, 222); assertEquals(true, result); }
public static boolean addMsgListener(IMsgListener msgListener) throws Exception { Map<String, String> msgs = msgListener.getMsgs(); if (msgs != null) { Object[] msgKeyArray = msgs.keySet().toArray(); for (int i = 0; i < msgKeyArray.length; i++) { String msg = String.valueOf(msgKeyArray[i]); Method method = msgListener.getClass().getMethod(msgs.get(msg), new Class[] { MsgPacket.class }); if (msg == null || msg.equals("")) { if (MsgManager.log != null) { MsgManager.log.warn("消息类型为空,无法注册"); } continue; } ArrayList<Method> methodList = msgListenerMap.get(msg); if (methodList == null) { methodList = new ArrayList<Method>(); msgListenerMap.put(msg, methodList); } if (!methodList.contains(method)) { methodList.add(method); } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + method.getClass().getName() + "注册多遍,请及时处理"); } } if (!msgInstanceMap.containsKey(method)) { msgInstanceMap.put(method, msgListener); } else { if (MsgManager.log != null) { MsgManager.log.warn(method.getName() + "已经被实例化注册过,请及时处理"); } } msgClassInstanceMap.put(msgListener.getClass(), msgListener); } return true; } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + msgListener.getClass().getName() + "监控数据为空"); } return false; } }
MsgManager { public static boolean addMsgListener(IMsgListener msgListener) throws Exception { Map<String, String> msgs = msgListener.getMsgs(); if (msgs != null) { Object[] msgKeyArray = msgs.keySet().toArray(); for (int i = 0; i < msgKeyArray.length; i++) { String msg = String.valueOf(msgKeyArray[i]); Method method = msgListener.getClass().getMethod(msgs.get(msg), new Class[] { MsgPacket.class }); if (msg == null || msg.equals("")) { if (MsgManager.log != null) { MsgManager.log.warn("消息类型为空,无法注册"); } continue; } ArrayList<Method> methodList = msgListenerMap.get(msg); if (methodList == null) { methodList = new ArrayList<Method>(); msgListenerMap.put(msg, methodList); } if (!methodList.contains(method)) { methodList.add(method); } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + method.getClass().getName() + "注册多遍,请及时处理"); } } if (!msgInstanceMap.containsKey(method)) { msgInstanceMap.put(method, msgListener); } else { if (MsgManager.log != null) { MsgManager.log.warn(method.getName() + "已经被实例化注册过,请及时处理"); } } msgClassInstanceMap.put(msgListener.getClass(), msgListener); } return true; } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + msgListener.getClass().getName() + "监控数据为空"); } return false; } } }
MsgManager { public static boolean addMsgListener(IMsgListener msgListener) throws Exception { Map<String, String> msgs = msgListener.getMsgs(); if (msgs != null) { Object[] msgKeyArray = msgs.keySet().toArray(); for (int i = 0; i < msgKeyArray.length; i++) { String msg = String.valueOf(msgKeyArray[i]); Method method = msgListener.getClass().getMethod(msgs.get(msg), new Class[] { MsgPacket.class }); if (msg == null || msg.equals("")) { if (MsgManager.log != null) { MsgManager.log.warn("消息类型为空,无法注册"); } continue; } ArrayList<Method> methodList = msgListenerMap.get(msg); if (methodList == null) { methodList = new ArrayList<Method>(); msgListenerMap.put(msg, methodList); } if (!methodList.contains(method)) { methodList.add(method); } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + method.getClass().getName() + "注册多遍,请及时处理"); } } if (!msgInstanceMap.containsKey(method)) { msgInstanceMap.put(method, msgListener); } else { if (MsgManager.log != null) { MsgManager.log.warn(method.getName() + "已经被实例化注册过,请及时处理"); } } msgClassInstanceMap.put(msgListener.getClass(), msgListener); } return true; } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + msgListener.getClass().getName() + "监控数据为空"); } return false; } } }
MsgManager { public static boolean addMsgListener(IMsgListener msgListener) throws Exception { Map<String, String> msgs = msgListener.getMsgs(); if (msgs != null) { Object[] msgKeyArray = msgs.keySet().toArray(); for (int i = 0; i < msgKeyArray.length; i++) { String msg = String.valueOf(msgKeyArray[i]); Method method = msgListener.getClass().getMethod(msgs.get(msg), new Class[] { MsgPacket.class }); if (msg == null || msg.equals("")) { if (MsgManager.log != null) { MsgManager.log.warn("消息类型为空,无法注册"); } continue; } ArrayList<Method> methodList = msgListenerMap.get(msg); if (methodList == null) { methodList = new ArrayList<Method>(); msgListenerMap.put(msg, methodList); } if (!methodList.contains(method)) { methodList.add(method); } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + method.getClass().getName() + "注册多遍,请及时处理"); } } if (!msgInstanceMap.containsKey(method)) { msgInstanceMap.put(method, msgListener); } else { if (MsgManager.log != null) { MsgManager.log.warn(method.getName() + "已经被实例化注册过,请及时处理"); } } msgClassInstanceMap.put(msgListener.getClass(), msgListener); } return true; } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + msgListener.getClass().getName() + "监控数据为空"); } return false; } } static void init(boolean useMsgMonitor, ILog log); static boolean addMsgListener(IMsgListener msgListener); static boolean dispatchMsg(String msgOpCode, Object data, Object otherData); static boolean handleMsg(MsgPacket msgPacket); }
MsgManager { public static boolean addMsgListener(IMsgListener msgListener) throws Exception { Map<String, String> msgs = msgListener.getMsgs(); if (msgs != null) { Object[] msgKeyArray = msgs.keySet().toArray(); for (int i = 0; i < msgKeyArray.length; i++) { String msg = String.valueOf(msgKeyArray[i]); Method method = msgListener.getClass().getMethod(msgs.get(msg), new Class[] { MsgPacket.class }); if (msg == null || msg.equals("")) { if (MsgManager.log != null) { MsgManager.log.warn("消息类型为空,无法注册"); } continue; } ArrayList<Method> methodList = msgListenerMap.get(msg); if (methodList == null) { methodList = new ArrayList<Method>(); msgListenerMap.put(msg, methodList); } if (!methodList.contains(method)) { methodList.add(method); } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + method.getClass().getName() + "注册多遍,请及时处理"); } } if (!msgInstanceMap.containsKey(method)) { msgInstanceMap.put(method, msgListener); } else { if (MsgManager.log != null) { MsgManager.log.warn(method.getName() + "已经被实例化注册过,请及时处理"); } } msgClassInstanceMap.put(msgListener.getClass(), msgListener); } return true; } else { if (MsgManager.log != null) { MsgManager.log.warn("IMsgListener:" + msgListener.getClass().getName() + "监控数据为空"); } return false; } } static void init(boolean useMsgMonitor, ILog log); static boolean addMsgListener(IMsgListener msgListener); static boolean dispatchMsg(String msgOpCode, Object data, Object otherData); static boolean handleMsg(MsgPacket msgPacket); static Map<String, ArrayList<Method>> msgListenerMap; static Map<Class<?>, Object> msgClassInstanceMap; static boolean USE_MSG_MONITOR; static ILog log; static Method method; }
@Test public void testPutMonitor() { runMonitor.putMonitor("链接"); runMonitor.putMonitor("发送"); runMonitor.putMonitor("断开"); }
public void putMonitor(String content) { long time = System.currentTimeMillis(); contentList.add(content); timeList.add(time); }
RunMonitor { public void putMonitor(String content) { long time = System.currentTimeMillis(); contentList.add(content); timeList.add(time); } }
RunMonitor { public void putMonitor(String content) { long time = System.currentTimeMillis(); contentList.add(content); timeList.add(time); } RunMonitor(String type, String opCode); }
RunMonitor { public void putMonitor(String content) { long time = System.currentTimeMillis(); contentList.add(content); timeList.add(time); } RunMonitor(String type, String opCode); void putMonitor(String content); String toString(String opCode); @Override String toString(); }
RunMonitor { public void putMonitor(String content) { long time = System.currentTimeMillis(); contentList.add(content); timeList.add(time); } RunMonitor(String type, String opCode); void putMonitor(String content); String toString(String opCode); @Override String toString(); }
@Test public void testAddMapping() throws InterruptedException { ThreadMsgManager.dispatchThreadMsg("createuser", 111, 222); ThreadMsgManager.dispatchThreadMsg("updateuser", 111, 222); Thread.sleep(1000); }
public static boolean addMapping(String msgOpCode, int[] threadPriority) { if (msgOpcodeType.containsKey(msgOpCode)) { return false; } if (threadPriority != null) { msgOpcodeType.put(msgOpCode, threadPriority); } return true; }
ThreadMsgManager { public static boolean addMapping(String msgOpCode, int[] threadPriority) { if (msgOpcodeType.containsKey(msgOpCode)) { return false; } if (threadPriority != null) { msgOpcodeType.put(msgOpCode, threadPriority); } return true; } }
ThreadMsgManager { public static boolean addMapping(String msgOpCode, int[] threadPriority) { if (msgOpcodeType.containsKey(msgOpCode)) { return false; } if (threadPriority != null) { msgOpcodeType.put(msgOpCode, threadPriority); } return true; } }
ThreadMsgManager { public static boolean addMapping(String msgOpCode, int[] threadPriority) { if (msgOpcodeType.containsKey(msgOpCode)) { return false; } if (threadPriority != null) { msgOpcodeType.put(msgOpCode, threadPriority); } return true; } static boolean addMapping(String msgOpCode, int[] threadPriority); static boolean dispatchThreadMsg(String msgOpCode, Object data, Object otherData); }
ThreadMsgManager { public static boolean addMapping(String msgOpCode, int[] threadPriority) { if (msgOpcodeType.containsKey(msgOpCode)) { return false; } if (threadPriority != null) { msgOpcodeType.put(msgOpCode, threadPriority); } return true; } static boolean addMapping(String msgOpCode, int[] threadPriority); static boolean dispatchThreadMsg(String msgOpCode, Object data, Object otherData); static HashMap<String, int[]> msgOpcodeType; }
@Test public void testLockMethodOneKey() { String str = (String) KeyLockManager.lockMethod("111", TEST1, (params) -> lockFunction(params), new Object[] { "222", 111 }); assertEquals("222111", str); }
public static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params) { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(keyType); try { keyLock.lock(lockKey); return func.apply(params); } catch (KeyLockException e) { isKeyLockException = true; if (KeyLockManager.log != null) { KeyLockManager.log.error("keylock自定义异常", e); } } catch (Exception e) { if (KeyLockManager.log != null) { KeyLockManager.log.error("业务异常", e); } } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } return null; }
KeyLockManager { public static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params) { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(keyType); try { keyLock.lock(lockKey); return func.apply(params); } catch (KeyLockException e) { isKeyLockException = true; if (KeyLockManager.log != null) { KeyLockManager.log.error("keylock自定义异常", e); } } catch (Exception e) { if (KeyLockManager.log != null) { KeyLockManager.log.error("业务异常", e); } } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } return null; } }
KeyLockManager { public static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params) { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(keyType); try { keyLock.lock(lockKey); return func.apply(params); } catch (KeyLockException e) { isKeyLockException = true; if (KeyLockManager.log != null) { KeyLockManager.log.error("keylock自定义异常", e); } } catch (Exception e) { if (KeyLockManager.log != null) { KeyLockManager.log.error("业务异常", e); } } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } return null; } }
KeyLockManager { public static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params) { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(keyType); try { keyLock.lock(lockKey); return func.apply(params); } catch (KeyLockException e) { isKeyLockException = true; if (KeyLockManager.log != null) { KeyLockManager.log.error("keylock自定义异常", e); } } catch (Exception e) { if (KeyLockManager.log != null) { KeyLockManager.log.error("业务异常", e); } } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } return null; } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params); static Object lockMethod(String lockKey1, String lockKey2, String keyType, KeylockFunction func, Object... params); }
KeyLockManager { public static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params) { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(keyType); try { keyLock.lock(lockKey); return func.apply(params); } catch (KeyLockException e) { isKeyLockException = true; if (KeyLockManager.log != null) { KeyLockManager.log.error("keylock自定义异常", e); } } catch (Exception e) { if (KeyLockManager.log != null) { KeyLockManager.log.error("业务异常", e); } } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } return null; } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params); static Object lockMethod(String lockKey1, String lockKey2, String keyType, KeylockFunction func, Object... params); static int KEY_LOCK_EXPIRE_TIME; static int KEY_LOCK_CYCLE_SLEEP_TIME; static Map<String, KeyLock> keyLockMap; }
@Test public void testLockMethodTwoKey() { String str = (String) KeyLockManager.lockMethod("111", "222", TEST1, (params) -> lockFunction(params), new Object[] { "222", 111 }); assertEquals("222111", str); }
public static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params) { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(keyType); try { keyLock.lock(lockKey); return func.apply(params); } catch (KeyLockException e) { isKeyLockException = true; if (KeyLockManager.log != null) { KeyLockManager.log.error("keylock自定义异常", e); } } catch (Exception e) { if (KeyLockManager.log != null) { KeyLockManager.log.error("业务异常", e); } } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } return null; }
KeyLockManager { public static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params) { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(keyType); try { keyLock.lock(lockKey); return func.apply(params); } catch (KeyLockException e) { isKeyLockException = true; if (KeyLockManager.log != null) { KeyLockManager.log.error("keylock自定义异常", e); } } catch (Exception e) { if (KeyLockManager.log != null) { KeyLockManager.log.error("业务异常", e); } } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } return null; } }
KeyLockManager { public static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params) { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(keyType); try { keyLock.lock(lockKey); return func.apply(params); } catch (KeyLockException e) { isKeyLockException = true; if (KeyLockManager.log != null) { KeyLockManager.log.error("keylock自定义异常", e); } } catch (Exception e) { if (KeyLockManager.log != null) { KeyLockManager.log.error("业务异常", e); } } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } return null; } }
KeyLockManager { public static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params) { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(keyType); try { keyLock.lock(lockKey); return func.apply(params); } catch (KeyLockException e) { isKeyLockException = true; if (KeyLockManager.log != null) { KeyLockManager.log.error("keylock自定义异常", e); } } catch (Exception e) { if (KeyLockManager.log != null) { KeyLockManager.log.error("业务异常", e); } } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } return null; } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params); static Object lockMethod(String lockKey1, String lockKey2, String keyType, KeylockFunction func, Object... params); }
KeyLockManager { public static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params) { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(keyType); try { keyLock.lock(lockKey); return func.apply(params); } catch (KeyLockException e) { isKeyLockException = true; if (KeyLockManager.log != null) { KeyLockManager.log.error("keylock自定义异常", e); } } catch (Exception e) { if (KeyLockManager.log != null) { KeyLockManager.log.error("业务异常", e); } } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } return null; } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params); static Object lockMethod(String lockKey1, String lockKey2, String keyType, KeylockFunction func, Object... params); static int KEY_LOCK_EXPIRE_TIME; static int KEY_LOCK_CYCLE_SLEEP_TIME; static Map<String, KeyLock> keyLockMap; }
@Test public void testLockPartOneKey() { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(TEST1); String lockKey = "111"; boolean result = false; try { keyLock.lock(lockKey); result = true; } catch (KeyLockException e) { isKeyLockException = true; } catch (Exception e) { } finally { if (!isKeyLockException) { keyLock.unlock(lockKey); } else { } } assertEquals(true, result); }
public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params); static Object lockMethod(String lockKey1, String lockKey2, String keyType, KeylockFunction func, Object... params); }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params); static Object lockMethod(String lockKey1, String lockKey2, String keyType, KeylockFunction func, Object... params); static int KEY_LOCK_EXPIRE_TIME; static int KEY_LOCK_CYCLE_SLEEP_TIME; static Map<String, KeyLock> keyLockMap; }
@Test public void testLockPartTwoKey() { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(TEST1); String lockKey1 = "11"; String lockKey2 = "22"; boolean result = false; try { keyLock.lock(lockKey1, lockKey2); result = true; } catch (KeyLockException e) { isKeyLockException = true; } catch (Exception e) { } finally { if (!isKeyLockException) { keyLock.unlock(lockKey1, lockKey2); } else { } } assertEquals(true, result); }
public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params); static Object lockMethod(String lockKey1, String lockKey2, String keyType, KeylockFunction func, Object... params); }
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params); static Object lockMethod(String lockKey1, String lockKey2, String keyType, KeylockFunction func, Object... params); static int KEY_LOCK_EXPIRE_TIME; static int KEY_LOCK_CYCLE_SLEEP_TIME; static Map<String, KeyLock> keyLockMap; }
@Test public void testAddHandle() throws NoSuchMethodException, SecurityException, InterruptedException { PacketTest packetTest = new PacketTest(); Method method = HandlerManagerTest.class.getMethod("handle", new Class[] { Object.class }); ThreadHandle threadHandle = new ThreadHandle(packetTest, method, null); boolean result = AsyncThreadManager.addHandle(threadHandle, 1, 1); Thread.sleep(1000); assertEquals(true, result); }
public static boolean addHandle(IHandle handle, int threadId, int priority) { if (handle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("handle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitHandleQueue.put(handle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("放入handle至异步线程列队失败", e); } return false; } }
AsyncThreadManager { public static boolean addHandle(IHandle handle, int threadId, int priority) { if (handle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("handle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitHandleQueue.put(handle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("放入handle至异步线程列队失败", e); } return false; } } }
AsyncThreadManager { public static boolean addHandle(IHandle handle, int threadId, int priority) { if (handle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("handle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitHandleQueue.put(handle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("放入handle至异步线程列队失败", e); } return false; } } }
AsyncThreadManager { public static boolean addHandle(IHandle handle, int threadId, int priority) { if (handle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("handle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitHandleQueue.put(handle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("放入handle至异步线程列队失败", e); } return false; } } static void init(int asyncThreadCycleInterval, int asyncThreadNum, int asyncThreadPriorityNum, int lockThreadNum, ILog log); static boolean addHandle(IHandle handle, int threadId, int priority); static boolean addCycle(ICycle cycle, int threadId, int priority); static boolean removeCycle(ICycle cycle, int threadId, int priority); static int[] getRandomThreadPriority(); static int[] getRandomThread(); static int[] getLockThreadPriority(int lockNum); static void start(); }
AsyncThreadManager { public static boolean addHandle(IHandle handle, int threadId, int priority) { if (handle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("handle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitHandleQueue.put(handle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("放入handle至异步线程列队失败", e); } return false; } } static void init(int asyncThreadCycleInterval, int asyncThreadNum, int asyncThreadPriorityNum, int lockThreadNum, ILog log); static boolean addHandle(IHandle handle, int threadId, int priority); static boolean addCycle(ICycle cycle, int threadId, int priority); static boolean removeCycle(ICycle cycle, int threadId, int priority); static int[] getRandomThreadPriority(); static int[] getRandomThread(); static int[] getLockThreadPriority(int lockNum); static void start(); }
@Test public void testAddCycle() { CycleTest cycleTest = new CycleTest(); cycleTest.name = "testAddCycle"; boolean result = AsyncThreadManager.addCycle(cycleTest, 1, 1); assertEquals(true, result); }
public static boolean addCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitAddCycleQueue.put(cycle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("放入ICycle至异步线程列队失败", e); } return false; } }
AsyncThreadManager { public static boolean addCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitAddCycleQueue.put(cycle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("放入ICycle至异步线程列队失败", e); } return false; } } }
AsyncThreadManager { public static boolean addCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitAddCycleQueue.put(cycle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("放入ICycle至异步线程列队失败", e); } return false; } } }
AsyncThreadManager { public static boolean addCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitAddCycleQueue.put(cycle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("放入ICycle至异步线程列队失败", e); } return false; } } static void init(int asyncThreadCycleInterval, int asyncThreadNum, int asyncThreadPriorityNum, int lockThreadNum, ILog log); static boolean addHandle(IHandle handle, int threadId, int priority); static boolean addCycle(ICycle cycle, int threadId, int priority); static boolean removeCycle(ICycle cycle, int threadId, int priority); static int[] getRandomThreadPriority(); static int[] getRandomThread(); static int[] getLockThreadPriority(int lockNum); static void start(); }
AsyncThreadManager { public static boolean addCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitAddCycleQueue.put(cycle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("放入ICycle至异步线程列队失败", e); } return false; } } static void init(int asyncThreadCycleInterval, int asyncThreadNum, int asyncThreadPriorityNum, int lockThreadNum, ILog log); static boolean addHandle(IHandle handle, int threadId, int priority); static boolean addCycle(ICycle cycle, int threadId, int priority); static boolean removeCycle(ICycle cycle, int threadId, int priority); static int[] getRandomThreadPriority(); static int[] getRandomThread(); static int[] getLockThreadPriority(int lockNum); static void start(); }
@Test public void testRemoveCycle() { CycleTest cycleTest = new CycleTest(); cycleTest.name = "testRemoveCycle"; boolean result = AsyncThreadManager.addCycle(cycleTest, 1, 1); result = AsyncThreadManager.removeCycle(cycleTest, 1, 1); assertEquals(true, result); }
public static boolean removeCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitRemoveCycleQueue.put(cycle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("移除ICycle至异步线程列队失败", e); } return false; } }
AsyncThreadManager { public static boolean removeCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitRemoveCycleQueue.put(cycle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("移除ICycle至异步线程列队失败", e); } return false; } } }
AsyncThreadManager { public static boolean removeCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitRemoveCycleQueue.put(cycle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("移除ICycle至异步线程列队失败", e); } return false; } } }
AsyncThreadManager { public static boolean removeCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitRemoveCycleQueue.put(cycle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("移除ICycle至异步线程列队失败", e); } return false; } } static void init(int asyncThreadCycleInterval, int asyncThreadNum, int asyncThreadPriorityNum, int lockThreadNum, ILog log); static boolean addHandle(IHandle handle, int threadId, int priority); static boolean addCycle(ICycle cycle, int threadId, int priority); static boolean removeCycle(ICycle cycle, int threadId, int priority); static int[] getRandomThreadPriority(); static int[] getRandomThread(); static int[] getLockThreadPriority(int lockNum); static void start(); }
AsyncThreadManager { public static boolean removeCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在线程id:" + threadId); } return false; } AsyncHandleData asyncHandleData = asyncThread.asyncHandleDataMap.get(priority); if (asyncHandleData == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("不存在优先级:" + priority); } return false; } try { asyncHandleData.waitRemoveCycleQueue.put(cycle); return true; } catch (InterruptedException e) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.error("移除ICycle至异步线程列队失败", e); } return false; } } static void init(int asyncThreadCycleInterval, int asyncThreadNum, int asyncThreadPriorityNum, int lockThreadNum, ILog log); static boolean addHandle(IHandle handle, int threadId, int priority); static boolean addCycle(ICycle cycle, int threadId, int priority); static boolean removeCycle(ICycle cycle, int threadId, int priority); static int[] getRandomThreadPriority(); static int[] getRandomThread(); static int[] getLockThreadPriority(int lockNum); static void start(); }
@Test public void testGetRandomThreadPriority() { int[] threadPriority = AsyncThreadManager.getRandomThreadPriority(); assertEquals(true, threadPriority != null); }
public static int[] getRandomThreadPriority() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); int priority = (int) (Math.random() * asyncThreadPriorityNum + 1); return new int[] { thread, priority }; }
AsyncThreadManager { public static int[] getRandomThreadPriority() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); int priority = (int) (Math.random() * asyncThreadPriorityNum + 1); return new int[] { thread, priority }; } }
AsyncThreadManager { public static int[] getRandomThreadPriority() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); int priority = (int) (Math.random() * asyncThreadPriorityNum + 1); return new int[] { thread, priority }; } }
AsyncThreadManager { public static int[] getRandomThreadPriority() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); int priority = (int) (Math.random() * asyncThreadPriorityNum + 1); return new int[] { thread, priority }; } static void init(int asyncThreadCycleInterval, int asyncThreadNum, int asyncThreadPriorityNum, int lockThreadNum, ILog log); static boolean addHandle(IHandle handle, int threadId, int priority); static boolean addCycle(ICycle cycle, int threadId, int priority); static boolean removeCycle(ICycle cycle, int threadId, int priority); static int[] getRandomThreadPriority(); static int[] getRandomThread(); static int[] getLockThreadPriority(int lockNum); static void start(); }
AsyncThreadManager { public static int[] getRandomThreadPriority() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); int priority = (int) (Math.random() * asyncThreadPriorityNum + 1); return new int[] { thread, priority }; } static void init(int asyncThreadCycleInterval, int asyncThreadNum, int asyncThreadPriorityNum, int lockThreadNum, ILog log); static boolean addHandle(IHandle handle, int threadId, int priority); static boolean addCycle(ICycle cycle, int threadId, int priority); static boolean removeCycle(ICycle cycle, int threadId, int priority); static int[] getRandomThreadPriority(); static int[] getRandomThread(); static int[] getLockThreadPriority(int lockNum); static void start(); }
@Test public void testGetRandomThread() { int[] threadPriority = AsyncThreadManager.getRandomThread(); assertEquals(true, threadPriority != null); }
public static int[] getRandomThread() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); return new int[] { thread, 1 }; }
AsyncThreadManager { public static int[] getRandomThread() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); return new int[] { thread, 1 }; } }
AsyncThreadManager { public static int[] getRandomThread() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); return new int[] { thread, 1 }; } }
AsyncThreadManager { public static int[] getRandomThread() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); return new int[] { thread, 1 }; } static void init(int asyncThreadCycleInterval, int asyncThreadNum, int asyncThreadPriorityNum, int lockThreadNum, ILog log); static boolean addHandle(IHandle handle, int threadId, int priority); static boolean addCycle(ICycle cycle, int threadId, int priority); static boolean removeCycle(ICycle cycle, int threadId, int priority); static int[] getRandomThreadPriority(); static int[] getRandomThread(); static int[] getLockThreadPriority(int lockNum); static void start(); }
AsyncThreadManager { public static int[] getRandomThread() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); return new int[] { thread, 1 }; } static void init(int asyncThreadCycleInterval, int asyncThreadNum, int asyncThreadPriorityNum, int lockThreadNum, ILog log); static boolean addHandle(IHandle handle, int threadId, int priority); static boolean addCycle(ICycle cycle, int threadId, int priority); static boolean removeCycle(ICycle cycle, int threadId, int priority); static int[] getRandomThreadPriority(); static int[] getRandomThread(); static int[] getLockThreadPriority(int lockNum); static void start(); }
@Test public void testGetSchema() throws URISyntaxException { final SpreadsheetDataSetProducer producer = produceTestSpreadsheet(); Collection<String> tableNames = producer.getSchema().tableNames(); assertEquals("Number of tables found [" + tableNames + "]", 12, tableNames.size()); assertTrue("Tables correctly populated [" + tableNames + "]", tableNames.contains("AssetType")); assertTrue("Tables correctly populated [" + tableNames + "]", tableNames.contains("Allowance")); }
@Override public Schema getSchema() { return new Schema() { @Override public Table getTable(String name) { throw new UnsupportedOperationException("Cannot get the metadata of a table for a spreadsheet"); } @Override public boolean isEmptyDatabase() { return tables.isEmpty(); } @Override public boolean tableExists(String name) { return tables.containsKey(name); } @Override public Collection<String> tableNames() { return tables.keySet(); } @Override public Collection<Table> tables() { throw new UnsupportedOperationException("Cannot get the metadata of a table for a spreadsheet"); } @Override public boolean viewExists(String name) { return false; } @Override public View getView(String name) { throw new IllegalArgumentException("Invalid view [" + name + "]. Views are not supported in spreadsheets"); } @Override public Collection<String> viewNames() { return Collections.emptySet(); } @Override public Collection<View> views() { return Collections.emptySet(); } }; }
SpreadsheetDataSetProducer implements DataSetProducer { @Override public Schema getSchema() { return new Schema() { @Override public Table getTable(String name) { throw new UnsupportedOperationException("Cannot get the metadata of a table for a spreadsheet"); } @Override public boolean isEmptyDatabase() { return tables.isEmpty(); } @Override public boolean tableExists(String name) { return tables.containsKey(name); } @Override public Collection<String> tableNames() { return tables.keySet(); } @Override public Collection<Table> tables() { throw new UnsupportedOperationException("Cannot get the metadata of a table for a spreadsheet"); } @Override public boolean viewExists(String name) { return false; } @Override public View getView(String name) { throw new IllegalArgumentException("Invalid view [" + name + "]. Views are not supported in spreadsheets"); } @Override public Collection<String> viewNames() { return Collections.emptySet(); } @Override public Collection<View> views() { return Collections.emptySet(); } }; } }
SpreadsheetDataSetProducer implements DataSetProducer { @Override public Schema getSchema() { return new Schema() { @Override public Table getTable(String name) { throw new UnsupportedOperationException("Cannot get the metadata of a table for a spreadsheet"); } @Override public boolean isEmptyDatabase() { return tables.isEmpty(); } @Override public boolean tableExists(String name) { return tables.containsKey(name); } @Override public Collection<String> tableNames() { return tables.keySet(); } @Override public Collection<Table> tables() { throw new UnsupportedOperationException("Cannot get the metadata of a table for a spreadsheet"); } @Override public boolean viewExists(String name) { return false; } @Override public View getView(String name) { throw new IllegalArgumentException("Invalid view [" + name + "]. Views are not supported in spreadsheets"); } @Override public Collection<String> viewNames() { return Collections.emptySet(); } @Override public Collection<View> views() { return Collections.emptySet(); } }; } SpreadsheetDataSetProducer(final InputStream... excelFiles); }
SpreadsheetDataSetProducer implements DataSetProducer { @Override public Schema getSchema() { return new Schema() { @Override public Table getTable(String name) { throw new UnsupportedOperationException("Cannot get the metadata of a table for a spreadsheet"); } @Override public boolean isEmptyDatabase() { return tables.isEmpty(); } @Override public boolean tableExists(String name) { return tables.containsKey(name); } @Override public Collection<String> tableNames() { return tables.keySet(); } @Override public Collection<Table> tables() { throw new UnsupportedOperationException("Cannot get the metadata of a table for a spreadsheet"); } @Override public boolean viewExists(String name) { return false; } @Override public View getView(String name) { throw new IllegalArgumentException("Invalid view [" + name + "]. Views are not supported in spreadsheets"); } @Override public Collection<String> viewNames() { return Collections.emptySet(); } @Override public Collection<View> views() { return Collections.emptySet(); } }; } SpreadsheetDataSetProducer(final InputStream... excelFiles); @Override Schema getSchema(); @Override void open(); @Override void close(); @Override Iterable<Record> records(String tableName); @Override boolean isTableEmpty(String tableName); }
SpreadsheetDataSetProducer implements DataSetProducer { @Override public Schema getSchema() { return new Schema() { @Override public Table getTable(String name) { throw new UnsupportedOperationException("Cannot get the metadata of a table for a spreadsheet"); } @Override public boolean isEmptyDatabase() { return tables.isEmpty(); } @Override public boolean tableExists(String name) { return tables.containsKey(name); } @Override public Collection<String> tableNames() { return tables.keySet(); } @Override public Collection<Table> tables() { throw new UnsupportedOperationException("Cannot get the metadata of a table for a spreadsheet"); } @Override public boolean viewExists(String name) { return false; } @Override public View getView(String name) { throw new IllegalArgumentException("Invalid view [" + name + "]. Views are not supported in spreadsheets"); } @Override public Collection<String> viewNames() { return Collections.emptySet(); } @Override public Collection<View> views() { return Collections.emptySet(); } }; } SpreadsheetDataSetProducer(final InputStream... excelFiles); @Override Schema getSchema(); @Override void open(); @Override void close(); @Override Iterable<Record> records(String tableName); @Override boolean isTableEmpty(String tableName); }
@Test public void testRemovingIndexFromNonExistentTable() { Schema testSchema = schema(appleTable); removeIndex = new RemoveIndex("Sweets", index("Sweets_1").unique().columns("pieces")); removeIndex.isApplied(testSchema, MockConnectionResources.build()); }
@Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) return false; Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesMatch(index, indexToBeRemoved)) { return false; } } return true; }
RemoveIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) return false; Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesMatch(index, indexToBeRemoved)) { return false; } } return true; } }
RemoveIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) return false; Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesMatch(index, indexToBeRemoved)) { return false; } } return true; } RemoveIndex(String tableName, Index index); }
RemoveIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) return false; Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesMatch(index, indexToBeRemoved)) { return false; } } return true; } RemoveIndex(String tableName, Index index); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Index getIndexToBeRemoved(); }
RemoveIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) return false; Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesMatch(index, indexToBeRemoved)) { return false; } } return true; } RemoveIndex(String tableName, Index index); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Index getIndexToBeRemoved(); }
@Test public void testRemovingIndexFromExistingTable() { Schema testSchema = schema(appleTable); removeIndex.isApplied(testSchema, MockConnectionResources.build()); }
@Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) return false; Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesMatch(index, indexToBeRemoved)) { return false; } } return true; }
RemoveIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) return false; Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesMatch(index, indexToBeRemoved)) { return false; } } return true; } }
RemoveIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) return false; Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesMatch(index, indexToBeRemoved)) { return false; } } return true; } RemoveIndex(String tableName, Index index); }
RemoveIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) return false; Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesMatch(index, indexToBeRemoved)) { return false; } } return true; } RemoveIndex(String tableName, Index index); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Index getIndexToBeRemoved(); }
RemoveIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) return false; Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesMatch(index, indexToBeRemoved)) { return false; } } return true; } RemoveIndex(String tableName, Index index); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Index getIndexToBeRemoved(); }
@Test public void testNoDeployedViewsTable() { Schema schema = schema(table("SomeTable")); assertFalse(onTest.loadViewHashes(schema).isPresent()); }
Optional<Map<String, String>> loadViewHashes(Schema schema) { if (!schema.tableExists(DEPLOYED_VIEWS_NAME)) { return Optional.empty(); } Map<String, String> result = Maps.newHashMap(); SelectStatement upgradeAuditSelect = select(field("name"), field("hash")).from(tableRef(DEPLOYED_VIEWS_NAME)); String sql = dialect.convertStatementToSQL(upgradeAuditSelect); if (log.isDebugEnabled()) log.debug("Loading " + DEPLOYED_VIEWS_NAME + " with SQL [" + sql + "]"); try (Connection connection = dataSource.getConnection(); java.sql.Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { String dbViewName = resultSet.getString(1); String viewName = dbViewName.toUpperCase(); if (!result.containsKey(viewName) || dbViewName.equals(viewName)) { result.put(viewName, resultSet.getString(2)); } } } catch (SQLException e) { throw new RuntimeSqlException("Failed to load deployed views. SQL: [" + sql + "]", e); } return Optional.of(Collections.unmodifiableMap(result)); }
ExistingViewHashLoader { Optional<Map<String, String>> loadViewHashes(Schema schema) { if (!schema.tableExists(DEPLOYED_VIEWS_NAME)) { return Optional.empty(); } Map<String, String> result = Maps.newHashMap(); SelectStatement upgradeAuditSelect = select(field("name"), field("hash")).from(tableRef(DEPLOYED_VIEWS_NAME)); String sql = dialect.convertStatementToSQL(upgradeAuditSelect); if (log.isDebugEnabled()) log.debug("Loading " + DEPLOYED_VIEWS_NAME + " with SQL [" + sql + "]"); try (Connection connection = dataSource.getConnection(); java.sql.Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { String dbViewName = resultSet.getString(1); String viewName = dbViewName.toUpperCase(); if (!result.containsKey(viewName) || dbViewName.equals(viewName)) { result.put(viewName, resultSet.getString(2)); } } } catch (SQLException e) { throw new RuntimeSqlException("Failed to load deployed views. SQL: [" + sql + "]", e); } return Optional.of(Collections.unmodifiableMap(result)); } }
ExistingViewHashLoader { Optional<Map<String, String>> loadViewHashes(Schema schema) { if (!schema.tableExists(DEPLOYED_VIEWS_NAME)) { return Optional.empty(); } Map<String, String> result = Maps.newHashMap(); SelectStatement upgradeAuditSelect = select(field("name"), field("hash")).from(tableRef(DEPLOYED_VIEWS_NAME)); String sql = dialect.convertStatementToSQL(upgradeAuditSelect); if (log.isDebugEnabled()) log.debug("Loading " + DEPLOYED_VIEWS_NAME + " with SQL [" + sql + "]"); try (Connection connection = dataSource.getConnection(); java.sql.Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { String dbViewName = resultSet.getString(1); String viewName = dbViewName.toUpperCase(); if (!result.containsKey(viewName) || dbViewName.equals(viewName)) { result.put(viewName, resultSet.getString(2)); } } } catch (SQLException e) { throw new RuntimeSqlException("Failed to load deployed views. SQL: [" + sql + "]", e); } return Optional.of(Collections.unmodifiableMap(result)); } ExistingViewHashLoader(DataSource dataSource, SqlDialect dialect); }
ExistingViewHashLoader { Optional<Map<String, String>> loadViewHashes(Schema schema) { if (!schema.tableExists(DEPLOYED_VIEWS_NAME)) { return Optional.empty(); } Map<String, String> result = Maps.newHashMap(); SelectStatement upgradeAuditSelect = select(field("name"), field("hash")).from(tableRef(DEPLOYED_VIEWS_NAME)); String sql = dialect.convertStatementToSQL(upgradeAuditSelect); if (log.isDebugEnabled()) log.debug("Loading " + DEPLOYED_VIEWS_NAME + " with SQL [" + sql + "]"); try (Connection connection = dataSource.getConnection(); java.sql.Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { String dbViewName = resultSet.getString(1); String viewName = dbViewName.toUpperCase(); if (!result.containsKey(viewName) || dbViewName.equals(viewName)) { result.put(viewName, resultSet.getString(2)); } } } catch (SQLException e) { throw new RuntimeSqlException("Failed to load deployed views. SQL: [" + sql + "]", e); } return Optional.of(Collections.unmodifiableMap(result)); } ExistingViewHashLoader(DataSource dataSource, SqlDialect dialect); }
ExistingViewHashLoader { Optional<Map<String, String>> loadViewHashes(Schema schema) { if (!schema.tableExists(DEPLOYED_VIEWS_NAME)) { return Optional.empty(); } Map<String, String> result = Maps.newHashMap(); SelectStatement upgradeAuditSelect = select(field("name"), field("hash")).from(tableRef(DEPLOYED_VIEWS_NAME)); String sql = dialect.convertStatementToSQL(upgradeAuditSelect); if (log.isDebugEnabled()) log.debug("Loading " + DEPLOYED_VIEWS_NAME + " with SQL [" + sql + "]"); try (Connection connection = dataSource.getConnection(); java.sql.Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { String dbViewName = resultSet.getString(1); String viewName = dbViewName.toUpperCase(); if (!result.containsKey(viewName) || dbViewName.equals(viewName)) { result.put(viewName, resultSet.getString(2)); } } } catch (SQLException e) { throw new RuntimeSqlException("Failed to load deployed views. SQL: [" + sql + "]", e); } return Optional.of(Collections.unmodifiableMap(result)); } ExistingViewHashLoader(DataSource dataSource, SqlDialect dialect); }
@Test public void testFetch() throws SQLException { Schema schema = schema(table(DatabaseUpgradeTableContribution.DEPLOYED_VIEWS_NAME)); when(dataSource.getConnection()).thenReturn(connection); when(connection.createStatement()).thenReturn(statement); when(statement.executeQuery(anyString())).thenReturn(resultSet); when(resultSet.next()).thenAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { return recordIndex++ < 5; } }); when(resultSet.getString(anyInt())).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { if (((Integer)invocation.getArguments()[0]).equals(1)) { switch (recordIndex) { case 1: return "VIEW1"; case 2: return "view2"; case 3: return "VIEW2"; case 4: return "View1"; case 5: return "view3"; default: throw new IllegalStateException("Unexpected index"); } } else { switch (recordIndex) { case 1: return "hash1"; case 2: return "HASH2"; case 3: return "hash2"; case 4: return "HASH1"; case 5: return "hash3"; default: throw new IllegalStateException("Unexpected index"); } } } }); Map<String, String> result = onTest.loadViewHashes(schema).get(); assertEquals("Result count", 3, result.size()); assertEquals("View 1 hash", "hash1", result.get("VIEW1")); assertEquals("View 2 hash", "hash2", result.get("VIEW2")); }
Optional<Map<String, String>> loadViewHashes(Schema schema) { if (!schema.tableExists(DEPLOYED_VIEWS_NAME)) { return Optional.empty(); } Map<String, String> result = Maps.newHashMap(); SelectStatement upgradeAuditSelect = select(field("name"), field("hash")).from(tableRef(DEPLOYED_VIEWS_NAME)); String sql = dialect.convertStatementToSQL(upgradeAuditSelect); if (log.isDebugEnabled()) log.debug("Loading " + DEPLOYED_VIEWS_NAME + " with SQL [" + sql + "]"); try (Connection connection = dataSource.getConnection(); java.sql.Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { String dbViewName = resultSet.getString(1); String viewName = dbViewName.toUpperCase(); if (!result.containsKey(viewName) || dbViewName.equals(viewName)) { result.put(viewName, resultSet.getString(2)); } } } catch (SQLException e) { throw new RuntimeSqlException("Failed to load deployed views. SQL: [" + sql + "]", e); } return Optional.of(Collections.unmodifiableMap(result)); }
ExistingViewHashLoader { Optional<Map<String, String>> loadViewHashes(Schema schema) { if (!schema.tableExists(DEPLOYED_VIEWS_NAME)) { return Optional.empty(); } Map<String, String> result = Maps.newHashMap(); SelectStatement upgradeAuditSelect = select(field("name"), field("hash")).from(tableRef(DEPLOYED_VIEWS_NAME)); String sql = dialect.convertStatementToSQL(upgradeAuditSelect); if (log.isDebugEnabled()) log.debug("Loading " + DEPLOYED_VIEWS_NAME + " with SQL [" + sql + "]"); try (Connection connection = dataSource.getConnection(); java.sql.Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { String dbViewName = resultSet.getString(1); String viewName = dbViewName.toUpperCase(); if (!result.containsKey(viewName) || dbViewName.equals(viewName)) { result.put(viewName, resultSet.getString(2)); } } } catch (SQLException e) { throw new RuntimeSqlException("Failed to load deployed views. SQL: [" + sql + "]", e); } return Optional.of(Collections.unmodifiableMap(result)); } }
ExistingViewHashLoader { Optional<Map<String, String>> loadViewHashes(Schema schema) { if (!schema.tableExists(DEPLOYED_VIEWS_NAME)) { return Optional.empty(); } Map<String, String> result = Maps.newHashMap(); SelectStatement upgradeAuditSelect = select(field("name"), field("hash")).from(tableRef(DEPLOYED_VIEWS_NAME)); String sql = dialect.convertStatementToSQL(upgradeAuditSelect); if (log.isDebugEnabled()) log.debug("Loading " + DEPLOYED_VIEWS_NAME + " with SQL [" + sql + "]"); try (Connection connection = dataSource.getConnection(); java.sql.Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { String dbViewName = resultSet.getString(1); String viewName = dbViewName.toUpperCase(); if (!result.containsKey(viewName) || dbViewName.equals(viewName)) { result.put(viewName, resultSet.getString(2)); } } } catch (SQLException e) { throw new RuntimeSqlException("Failed to load deployed views. SQL: [" + sql + "]", e); } return Optional.of(Collections.unmodifiableMap(result)); } ExistingViewHashLoader(DataSource dataSource, SqlDialect dialect); }
ExistingViewHashLoader { Optional<Map<String, String>> loadViewHashes(Schema schema) { if (!schema.tableExists(DEPLOYED_VIEWS_NAME)) { return Optional.empty(); } Map<String, String> result = Maps.newHashMap(); SelectStatement upgradeAuditSelect = select(field("name"), field("hash")).from(tableRef(DEPLOYED_VIEWS_NAME)); String sql = dialect.convertStatementToSQL(upgradeAuditSelect); if (log.isDebugEnabled()) log.debug("Loading " + DEPLOYED_VIEWS_NAME + " with SQL [" + sql + "]"); try (Connection connection = dataSource.getConnection(); java.sql.Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { String dbViewName = resultSet.getString(1); String viewName = dbViewName.toUpperCase(); if (!result.containsKey(viewName) || dbViewName.equals(viewName)) { result.put(viewName, resultSet.getString(2)); } } } catch (SQLException e) { throw new RuntimeSqlException("Failed to load deployed views. SQL: [" + sql + "]", e); } return Optional.of(Collections.unmodifiableMap(result)); } ExistingViewHashLoader(DataSource dataSource, SqlDialect dialect); }
ExistingViewHashLoader { Optional<Map<String, String>> loadViewHashes(Schema schema) { if (!schema.tableExists(DEPLOYED_VIEWS_NAME)) { return Optional.empty(); } Map<String, String> result = Maps.newHashMap(); SelectStatement upgradeAuditSelect = select(field("name"), field("hash")).from(tableRef(DEPLOYED_VIEWS_NAME)); String sql = dialect.convertStatementToSQL(upgradeAuditSelect); if (log.isDebugEnabled()) log.debug("Loading " + DEPLOYED_VIEWS_NAME + " with SQL [" + sql + "]"); try (Connection connection = dataSource.getConnection(); java.sql.Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { while (resultSet.next()) { String dbViewName = resultSet.getString(1); String viewName = dbViewName.toUpperCase(); if (!result.containsKey(viewName) || dbViewName.equals(viewName)) { result.put(viewName, resultSet.getString(2)); } } } catch (SQLException e) { throw new RuntimeSqlException("Failed to load deployed views. SQL: [" + sql + "]", e); } return Optional.of(Collections.unmodifiableMap(result)); } ExistingViewHashLoader(DataSource dataSource, SqlDialect dialect); }
@Test public void testExactPath() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(AddJamType.class); upgradeSteps.add(AddCakeTable.class); upgradeSteps.add(AddDiameter.class); upgradeSteps.add(InsertAVictoriaSpongeRowUsingDSL.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps()); Schema current = schema(sconeTable); Schema target = schema(upgradedSconeTable, cakeTable); List<UpgradeStep> path = pathFinder.determinePath(current, target, Sets.<String>newHashSet()).getUpgradeSteps(); assertEquals("Number of upgrades steps", 4, path.size()); assertSame("First upgrades step", AddCakeTable.class, path.get(0).getClass()); assertSame("Second upgrades step", AddDiameter.class, path.get(1).getClass()); assertSame("Third upgrades step", AddJamType.class, path.get(2).getClass()); }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test public void testConditionalUpgradeStepIsExecuted() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(AddJamType.class); upgradeSteps.add(AddDiameter.class); upgradeSteps.add(AddJamAmount.class); upgradeSteps.add(AddJamAmountUnit.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps()); Schema current = schema(sconeTable); Schema target = schema(upgradedSconeTableWithJamAmount); List<UpgradeStep> path = pathFinder.determinePath(current, target, Sets.<String>newHashSet()).getUpgradeSteps(); assertEquals("Number of upgrades steps", 4, path.size()); assertSame("First", AddDiameter.class, path.get(0).getClass()); assertSame("Second", AddJamType.class, path.get(1).getClass()); assertSame("Third", AddJamAmountUnit.class, path.get(2).getClass()); assertSame("Last", AddJamAmount.class, path.get(3).getClass()); }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test public void testConditionalUpgradeStepNotExecuted() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(AddJamType.class); upgradeSteps.add(AddDiameter.class); upgradeSteps.add(AddJamAmount.class); upgradeSteps.add(AddJamAmountUnit.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps(AddJamType.class, AddDiameter.class)); Schema current = schema(upgradedSconeTable); Schema target = schema(upgradedSconeTable); List<UpgradeStep> path = pathFinder.determinePath(current, target, Sets.<String>newHashSet()).getUpgradeSteps(); assertEquals("Number of upgrades steps", 0, path.size()); }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test public void testLinearPath() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(AddWeight.class); upgradeSteps.add(AddJamType.class); upgradeSteps.add(AddCakeTable.class); upgradeSteps.add(AddDiameter.class); upgradeSteps.add(InsertAVictoriaSpongeRowUsingDSL.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps(AddWeight.class)); Schema current = schema(sconeTable); Schema target = schema(upgradedSconeTable, cakeTable); List<UpgradeStep> path = pathFinder.determinePath(current, target, Sets.<String>newHashSet()).getUpgradeSteps(); assertEquals("Number of upgrades steps", 4, path.size()); assertSame("Second upgrades step", AddCakeTable.class, path.get(0).getClass()); assertSame("Third upgrades step", AddDiameter.class, path.get(1).getClass()); assertSame("First upgrades step", AddJamType.class, path.get(2).getClass()); assertSame("Fourth upgrade step", InsertAVictoriaSpongeRowUsingDSL.class, path.get(3).getClass()); }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test public void testAddColumnFailsWhenItAlreadyExists() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(AddWeight.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps()); Schema current = schema(sconeTable); Schema target = schema(upgradedSconeTable); try { pathFinder.determinePath(current, target, Sets.<String>newHashSet()); fail(); } catch(RuntimeException rte) { Throwable ex = rte; while(ex != null) { if (ex.getMessage().contains("[weight]")) return; ex = ex.getCause(); } throw rte; } }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test public void testAddDeleteSameColumn() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(AddStars.class); upgradeSteps.add(AddRating.class); upgradeSteps.add(DeleteRating.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps()); Schema current = schema(cakeTable); Schema target = schema(cakeTablev2); List<UpgradeStep> path = pathFinder.determinePath(current, target, Sets.<String>newHashSet()).getUpgradeSteps(); assertEquals("Should only be one upgrade setep.", 3, path.size()); }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test(expected = IllegalArgumentException.class) public void testRenameTableNotExists() { Schema testSchema = schema(appleTable); RenameTable renameTable = new RenameTable("Pear", "Apple"); renameTable.apply(testSchema); }
@Override public Schema apply(Schema schema) { return applyChange(schema, oldTableName, newTableName); }
RenameTable implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, oldTableName, newTableName); } }
RenameTable implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, oldTableName, newTableName); } RenameTable(String oldTableName, String newTableName); }
RenameTable implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, oldTableName, newTableName); } RenameTable(String oldTableName, String newTableName); String getOldTableName(); String getNewTableName(); @Override Schema apply(Schema schema); @Override Schema reverse(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override void accept(SchemaChangeVisitor visitor); }
RenameTable implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, oldTableName, newTableName); } RenameTable(String oldTableName, String newTableName); String getOldTableName(); String getNewTableName(); @Override Schema apply(Schema schema); @Override Schema reverse(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override void accept(SchemaChangeVisitor visitor); }
@Test public void testSchemasMatchWithUnappliedDataChange() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(AddRating.class); upgradeSteps.add(DeleteRating.class); upgradeSteps.add(InsertAVictoriaSpongeRowUsingDSL.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps()); Schema current = schema(cakeTable); Schema target = schema(cakeTable); List<UpgradeStep> path = pathFinder.determinePath(current, target, Sets.<String>newHashSet()).getUpgradeSteps(); assertEquals("Should only be one upgrade step.", 3, path.size()); assertEquals("Upgrade step 1 should be Insert row using DSL.", InsertAVictoriaSpongeRowUsingDSL.class, path.get(0).getClass()); }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test public void testUpgradeWithSkippedStep() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(AddWeight.class); upgradeSteps.add(AddJamType.class); upgradeSteps.add(AddCakeTable.class); upgradeSteps.add(AddDiameter.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps(AddWeight.class, AddDiameter.class)); Table newScone = table("Scone").columns( column("raisins", DataType.BOOLEAN).nullable(), column("flour", DataType.STRING).nullable(), column("weight", DataType.DECIMAL).nullable(), column("diameter", DataType.DECIMAL).nullable() ); Schema current = schema(newScone); Schema target = schema(upgradedSconeTable, cakeTable); List<UpgradeStep> path = pathFinder.determinePath(current, target, Sets.<String>newHashSet()).getUpgradeSteps(); assertEquals("Number of upgrades steps", 2, path.size()); assertSame("Second upgrades step", AddCakeTable.class, path.get(0).getClass()); assertSame("First upgrades step", AddJamType.class, path.get(1).getClass()); }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test public void testNoUpgradeExists() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(AddJamType.class); upgradeSteps.add(AddCakeTable.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps()); Schema current = schema(sconeTable); Schema target = schema(upgradedSconeTable, cakeTable); try { pathFinder.determinePath(current, target, Sets.<String>newHashSet()); fail("No upgrade path exists so an exception should be thrown"); } catch (NoUpgradePathExistsException e) { assertEquals("Message text", "No upgrade path exists", e.getMessage()); assertTrue("Message is instance of IllegalStateException", e instanceof IllegalStateException); } }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test public void testInterdependentSequence() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(AddJamType.class); upgradeSteps.add(AddDiameter.class); upgradeSteps.add(ChangeGramsToWeight.class); upgradeSteps.add(AddGrams.class); upgradeSteps.add(AddCakeTable.class); upgradeSteps.add(InsertAVictoriaSpongeRowUsingDSL.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps(AddDiameter.class, AddJamType.class, AddGrams.class, ChangeGramsToWeight.class)); Schema current = schema(upgradedSconeTable); Schema target = schema(upgradedSconeTable, cakeTable); List<UpgradeStep> path = pathFinder.determinePath(current, target, Sets.<String>newHashSet()).getUpgradeSteps(); assertEquals("Number of upgrade steps", 2, path.size()); assertEquals("Type of upgrade step", AddCakeTable.class, path.get(0).getClass()); }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test public void testAddAssumedUUIDWhenUpgradeAuditUUIDPresent() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(MockAddUpgradeAudit.class); upgradeSteps.add(MockProvisionHistoryUpgrade.class); upgradeSteps.add(MockWidenIndustryCodeUpgrade.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps(MockAddUpgradeAudit.class)); List<UpgradeStep> path = pathFinder.determinePath(schema(), schema(), Sets.<String>newHashSet()).getUpgradeSteps(); assertEquals("There should be no upgrade steps - all the ones in 5.0.18 and earlier should be assumed to be applied.", 0, path.size()); }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test public void testDontAddAssumedUUIDWhenEarlierStepsPresent() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(MockAddUpgradeAudit.class); upgradeSteps.add(MockProvisionHistoryUpgrade.class); upgradeSteps.add(MockWidenIndustryCodeUpgrade.class); UpgradePathFinder pathFinder = makeFinder(upgradeSteps, appliedSteps(MockAddUpgradeAudit.class, MockProvisionHistoryUpgrade.class)); List<UpgradeStep> path = pathFinder.determinePath(schema(), schema(), Sets.<String>newHashSet()).getUpgradeSteps(); assertEquals("Earlier steps should be applied", 1, path.size()); assertEquals("Earlier steps should be applied", MockWidenIndustryCodeUpgrade.class, path.get(0).getClass()); }
public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!schemasMatch(target, trialUpgradedSchema, "target domain schema", "trial upgraded schema", exceptionRegexes)) { throw new NoUpgradePathExistsException(); } Schema reversal = schemaChangeSequence.applyInReverseToSchema(trialUpgradedSchema); if (!schemasMatch(reversal, current, "upgraded schema reversal", "current schema", exceptionRegexes)) { throw new IllegalStateException("Upgrade reversals are invalid"); } return schemaChangeSequence; } UpgradePathFinder(Collection<Class<? extends UpgradeStep>> availableUpgradeSteps, Set<java.util.UUID> stepsAlreadyApplied); boolean hasStepsToApply(); SchemaChangeSequence getSchemaChangeSequence(); SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes); static java.util.UUID readUUID(Class<? extends UpgradeStep> upgradeStepClass); static java.util.UUID readOnlyWithUUID(Class<? extends UpgradeStep> upgradeStepClass); }
@Test public void testAddAuditRecord() throws ParseException { SchemaChangeVisitor visitor = mock(SchemaChangeVisitor.class); Schema schema = mock(Schema.class); UUID uuid = UUID.randomUUID(); String description = "Description"; given(schema.tableExists("UpgradeAudit")).willReturn(true); AuditRecordHelper.addAuditRecord(visitor, schema, uuid, description); ArgumentCaptor<ExecuteStatement> argument = ArgumentCaptor.forClass(ExecuteStatement.class); verify(visitor).visit(argument.capture()); InsertStatement statement = (InsertStatement) argument.getValue().getStatement(); assertAuditInsertStatement(uuid, description, statement); }
public static void addAuditRecord(SchemaChangeVisitor visitor, Schema schema, UUID uuid, String description) { if (!schema.tableExists("UpgradeAudit")) return; InsertStatement auditRecord = createAuditInsertStatement(uuid, description); visitor.visit(new ExecuteStatement(auditRecord)); }
AuditRecordHelper { public static void addAuditRecord(SchemaChangeVisitor visitor, Schema schema, UUID uuid, String description) { if (!schema.tableExists("UpgradeAudit")) return; InsertStatement auditRecord = createAuditInsertStatement(uuid, description); visitor.visit(new ExecuteStatement(auditRecord)); } }
AuditRecordHelper { public static void addAuditRecord(SchemaChangeVisitor visitor, Schema schema, UUID uuid, String description) { if (!schema.tableExists("UpgradeAudit")) return; InsertStatement auditRecord = createAuditInsertStatement(uuid, description); visitor.visit(new ExecuteStatement(auditRecord)); } }
AuditRecordHelper { public static void addAuditRecord(SchemaChangeVisitor visitor, Schema schema, UUID uuid, String description) { if (!schema.tableExists("UpgradeAudit")) return; InsertStatement auditRecord = createAuditInsertStatement(uuid, description); visitor.visit(new ExecuteStatement(auditRecord)); } static void addAuditRecord(SchemaChangeVisitor visitor, Schema schema, UUID uuid, String description); static InsertStatement createAuditInsertStatement(UUID uuid, String description); }
AuditRecordHelper { public static void addAuditRecord(SchemaChangeVisitor visitor, Schema schema, UUID uuid, String description) { if (!schema.tableExists("UpgradeAudit")) return; InsertStatement auditRecord = createAuditInsertStatement(uuid, description); visitor.visit(new ExecuteStatement(auditRecord)); } static void addAuditRecord(SchemaChangeVisitor visitor, Schema schema, UUID uuid, String description); static InsertStatement createAuditInsertStatement(UUID uuid, String description); }
@Test public void createAuditInsertStatement() throws Exception { UUID uuid = UUID.randomUUID(); String description = "Description"; InsertStatement statement = AuditRecordHelper.createAuditInsertStatement(uuid, description); assertAuditInsertStatement(uuid, description, statement); }
public static InsertStatement createAuditInsertStatement(UUID uuid, String description) { InsertStatement auditRecord = new InsertStatement().into( new TableReference("UpgradeAudit")).values( new FieldLiteral(uuid.toString()).as("upgradeUUID"), new FieldLiteral(description).as("description"), cast(dateToYyyyMMddHHmmss(now())).asType(DataType.DECIMAL, 14).as("appliedTime") ); return auditRecord; }
AuditRecordHelper { public static InsertStatement createAuditInsertStatement(UUID uuid, String description) { InsertStatement auditRecord = new InsertStatement().into( new TableReference("UpgradeAudit")).values( new FieldLiteral(uuid.toString()).as("upgradeUUID"), new FieldLiteral(description).as("description"), cast(dateToYyyyMMddHHmmss(now())).asType(DataType.DECIMAL, 14).as("appliedTime") ); return auditRecord; } }
AuditRecordHelper { public static InsertStatement createAuditInsertStatement(UUID uuid, String description) { InsertStatement auditRecord = new InsertStatement().into( new TableReference("UpgradeAudit")).values( new FieldLiteral(uuid.toString()).as("upgradeUUID"), new FieldLiteral(description).as("description"), cast(dateToYyyyMMddHHmmss(now())).asType(DataType.DECIMAL, 14).as("appliedTime") ); return auditRecord; } }
AuditRecordHelper { public static InsertStatement createAuditInsertStatement(UUID uuid, String description) { InsertStatement auditRecord = new InsertStatement().into( new TableReference("UpgradeAudit")).values( new FieldLiteral(uuid.toString()).as("upgradeUUID"), new FieldLiteral(description).as("description"), cast(dateToYyyyMMddHHmmss(now())).asType(DataType.DECIMAL, 14).as("appliedTime") ); return auditRecord; } static void addAuditRecord(SchemaChangeVisitor visitor, Schema schema, UUID uuid, String description); static InsertStatement createAuditInsertStatement(UUID uuid, String description); }
AuditRecordHelper { public static InsertStatement createAuditInsertStatement(UUID uuid, String description) { InsertStatement auditRecord = new InsertStatement().into( new TableReference("UpgradeAudit")).values( new FieldLiteral(uuid.toString()).as("upgradeUUID"), new FieldLiteral(description).as("description"), cast(dateToYyyyMMddHHmmss(now())).asType(DataType.DECIMAL, 14).as("appliedTime") ); return auditRecord; } static void addAuditRecord(SchemaChangeVisitor visitor, Schema schema, UUID uuid, String description); static InsertStatement createAuditInsertStatement(UUID uuid, String description); }
@Test public void testGetPath() { Table testTable = table("Foo").columns(column("name", DataType.STRING, 32)); View testView = view("FooView", select(field("name")).from(tableRef("Foo"))); View testView2 = view("BarView", select(field("name")).from(tableRef("MooView")), "MooView"); View testView3 = view("MooView", select(field("name")).from(tableRef("FooView")), "FooView"); when(dialect.tableDeploymentStatements(same(testTable))).thenReturn(ImmutableList.of("A")); when(dialect.viewDeploymentStatements(same(testView))).thenReturn(ImmutableList.of("B")); when(dialect.viewDeploymentStatements(same(testView2))).thenReturn(ImmutableList.of("C")); when(dialect.viewDeploymentStatements(same(testView3))).thenReturn(ImmutableList.of("D")); Schema targetSchema = schema( schema(testTable), schema(testView, testView2, testView3) ); Deployment deployment = new Deployment(dialect, executorProvider, upgradePathFactory); UpgradePath path = deployment.getPath(targetSchema, Lists.<Class<? extends UpgradeStep>>newArrayList()); assertTrue("Steps to apply", path.hasStepsToApply()); assertEquals("Steps", "[]", path.getSteps().toString()); assertEquals("SQL", ImmutableList.of("A", "B", "D", "C"), path.getSql()); deployment.deploy(targetSchema); verify(executor).execute(ImmutableList.of("A", "B", "D", "C")); }
public UpgradePath getPath(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps) { final UpgradePath path = upgradePathFactory.create(sqlDialect); writeStatements(targetSchema, path); writeUpgradeSteps(upgradeSteps, path); return path; }
Deployment { public UpgradePath getPath(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps) { final UpgradePath path = upgradePathFactory.create(sqlDialect); writeStatements(targetSchema, path); writeUpgradeSteps(upgradeSteps, path); return path; } }
Deployment { public UpgradePath getPath(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps) { final UpgradePath path = upgradePathFactory.create(sqlDialect); writeStatements(targetSchema, path); writeUpgradeSteps(upgradeSteps, path); return path; } @Inject Deployment(SqlDialect sqlDialect, SqlScriptExecutorProvider sqlScriptExecutorProvider, UpgradePathFactory upgradePathFactory); private Deployment(UpgradePathFactory upgradePathFactory, @Assisted ConnectionResources connectionResources); }
Deployment { public UpgradePath getPath(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps) { final UpgradePath path = upgradePathFactory.create(sqlDialect); writeStatements(targetSchema, path); writeUpgradeSteps(upgradeSteps, path); return path; } @Inject Deployment(SqlDialect sqlDialect, SqlScriptExecutorProvider sqlScriptExecutorProvider, UpgradePathFactory upgradePathFactory); private Deployment(UpgradePathFactory upgradePathFactory, @Assisted ConnectionResources connectionResources); void deploy(Schema targetSchema); void deploy(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps); static void deploySchema(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps, ConnectionResources connectionResources); UpgradePath getPath(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps); }
Deployment { public UpgradePath getPath(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps) { final UpgradePath path = upgradePathFactory.create(sqlDialect); writeStatements(targetSchema, path); writeUpgradeSteps(upgradeSteps, path); return path; } @Inject Deployment(SqlDialect sqlDialect, SqlScriptExecutorProvider sqlScriptExecutorProvider, UpgradePathFactory upgradePathFactory); private Deployment(UpgradePathFactory upgradePathFactory, @Assisted ConnectionResources connectionResources); void deploy(Schema targetSchema); void deploy(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps); static void deploySchema(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps, ConnectionResources connectionResources); UpgradePath getPath(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps); }
@Test public void testIncreaseColumnLength() { Schema testSchema = schema(appleTable); ChangeColumn changeColumn = new ChangeColumn("Apple", column("colour", DataType.STRING, 10).nullable(), column("colour", DataType.STRING, 35).nullable()); Schema updatedSchema = changeColumn.apply(testSchema); Table resultTable = updatedSchema.getTable("Apple"); assertNotNull(resultTable); assertEquals("Post upgrade column count", 9, resultTable.columns().size()); Column columnOne = resultTable.columns().get(0); Column columnTwo = resultTable.columns().get(1); Column columnThree = resultTable.columns().get(2); Column columnFour = resultTable.columns().get(3); Column columnFive = resultTable.columns().get(4); Column columnSix = resultTable.columns().get(5); Column columnSeven = resultTable.columns().get(6); Column columnEight = resultTable.columns().get(7); Column columnNine = resultTable.columns().get(8); assertEquals("Post upgrade existing column name 1", "id", columnOne.getName()); assertEquals("Post upgrade existing column name 2", "version", columnTwo.getName()); assertEquals("Post upgrade existing column name 3", "colour", columnThree.getName()); assertEquals("Post upgrade existing column name 4", "variety", columnFour.getName()); assertEquals("Post upgrade existing column name 5", "ispoisoned", columnFive.getName()); assertEquals("Post upgrade existing column name 6", "datecreated", columnSix.getName()); assertEquals("Post upgrade existing column name 7", "numberavailable", columnSeven.getName()); assertEquals("Post upgrade existing column name 8", "totalvalue", columnEight.getName()); assertEquals("Post upgrade existing column name 9", "nullcheck", columnNine.getName()); assertEquals("Width should have changed", 35, columnThree.getWidth()); assertEquals("Width should not have changed", 15, columnFour.getWidth()); assertEquals("Width should not have changed", 5, columnSeven.getWidth()); assertEquals("Width should not have changed", 9, columnEight.getWidth()); assertEquals("Width should not have changed", 9, columnNine.getWidth()); assertEquals("Scale should not have changed", 0, columnThree.getScale()); assertEquals("Scale should not have changed", 0, columnFour.getScale()); assertEquals("Scale should not have changed", 0, columnFive.getScale()); assertEquals("Scale should not have changed", 0, columnSeven.getScale()); assertEquals("Scale should not have changed", 2, columnEight.getScale()); assertEquals("Scale should not have changed", 0, columnNine.getScale()); assertEquals("Type should not have changed", DataType.STRING, columnThree.getType()); assertEquals("Type should not have changed", DataType.STRING, columnFour.getType()); assertEquals("Type should not have changed", DataType.BOOLEAN, columnFive.getType()); assertEquals("Type should not have changed", DataType.DATE, columnSix.getType()); assertEquals("Type should not have changed", DataType.DECIMAL, columnSeven.getType()); assertEquals("Type should not have changed", DataType.DECIMAL, columnEight.getType()); assertEquals("Type should not have changed", DataType.DECIMAL, columnNine.getType()); assertTrue("Nullable should not have changed", columnThree.isNullable()); assertTrue("Nullable should not have changed", columnFour.isNullable()); assertTrue("Nullable should not have changed", columnFive.isNullable()); assertTrue("Nullable should not have changed", columnSix.isNullable()); assertFalse("Nullable should not have changed", columnSeven.isNullable()); assertFalse("Nullable should not have changed", columnEight.isNullable()); assertTrue("Nullable should not have changed", columnNine.isNullable()); }
@Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }
@Test(expected = IllegalArgumentException.class) public void testRenameTableAlreadyExists() { Schema testSchema = schema(appleTable, orangeTable); RenameTable renameTable = new RenameTable("Apple", "Orange"); renameTable.apply(testSchema); }
@Override public Schema apply(Schema schema) { return applyChange(schema, oldTableName, newTableName); }
RenameTable implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, oldTableName, newTableName); } }
RenameTable implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, oldTableName, newTableName); } RenameTable(String oldTableName, String newTableName); }
RenameTable implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, oldTableName, newTableName); } RenameTable(String oldTableName, String newTableName); String getOldTableName(); String getNewTableName(); @Override Schema apply(Schema schema); @Override Schema reverse(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override void accept(SchemaChangeVisitor visitor); }
RenameTable implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, oldTableName, newTableName); } RenameTable(String oldTableName, String newTableName); String getOldTableName(); String getNewTableName(); @Override Schema apply(Schema schema); @Override Schema reverse(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override void accept(SchemaChangeVisitor visitor); }
@Test public void testChangeColumnType() { Schema testSchema = schema(appleTable); ChangeColumn changeColumn = new ChangeColumn("Apple", column("numberavailable", DataType.DECIMAL, 5), column("numberavailable", DataType.BIG_INTEGER)); Schema updatedSchema = changeColumn.apply(testSchema); Table resultTable = updatedSchema.getTable("Apple"); assertNotNull(resultTable); Table expectedAppleTable = table("Apple").columns( idColumn(), versionColumn(), column("colour", DataType.STRING, 10).nullable(), column("variety", DataType.STRING, 15).nullable(), column("ispoisoned", DataType.BOOLEAN).nullable(), column("datecreated", DataType.DATE).nullable(), column("numberavailable", DataType.BIG_INTEGER), column("totalvalue", DataType.DECIMAL, 9, 2), column("nullcheck", DataType.DECIMAL, 9, 0).nullable() ).indexes( index("Apple_1").columns("colour") ); assertTrue(new SchemaHomology(new ThrowingDifferenceWriter(), "expected", "result").tablesMatch(expectedAppleTable, resultTable)); }
@Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }
@Test public void testChangeColumnName() { Schema testSchema = schema(appleTable); ChangeColumn changeColumn = new ChangeColumn("Apple", column("variety", DataType.STRING, 15).nullable(), column("brand", DataType.STRING, 15).nullable()); Schema updatedSchema = changeColumn.apply(testSchema); Table resultTable = updatedSchema.getTable("Apple"); assertNotNull(resultTable); assertEquals("Post upgrade column count", 9, resultTable.columns().size()); Column columnOne = resultTable.columns().get(2); Column columnTwo = resultTable.columns().get(3); Column columnThree = resultTable.columns().get(4); Column columnFour = resultTable.columns().get(5); Column columnFive = resultTable.columns().get(6); Column columnSix = resultTable.columns().get(7); Column columnSeven = resultTable.columns().get(8); assertEquals("Post upgrade existing column name 1", "colour", columnOne.getName()); assertEquals("Post upgrade existing column name 2", "brand", columnTwo.getName()); assertEquals("Post upgrade existing column name 3", "ispoisoned", columnThree.getName()); assertEquals("Post upgrade existing column name 4", "datecreated", columnFour.getName()); assertEquals("Post upgrade existing column name 5", "numberavailable", columnFive.getName()); assertEquals("Post upgrade existing column name 6", "totalvalue", columnSix.getName()); assertEquals("Post upgrade existing column name 7", "nullcheck", columnSeven.getName()); assertEquals("Width should not have changed", 10, columnOne.getWidth()); assertEquals("Width should not have changed", 15, columnTwo.getWidth()); assertEquals("Width should not have changed", 5, columnFive.getWidth()); assertEquals("Width should not have changed", 9, columnSix.getWidth()); assertEquals("Width should not have changed", 9, columnSeven.getWidth()); assertEquals("Scale should not have changed", 0, columnOne.getScale()); assertEquals("Scale should not have changed", 0, columnTwo.getScale()); assertEquals("Scale should not have changed", 0, columnFive.getScale()); assertEquals("Scale should not have changed", 2, columnSix.getScale()); assertEquals("Scale should not have changed", 0, columnSeven.getScale()); assertEquals("Type should not have changed", DataType.STRING, columnOne.getType()); assertEquals("Type should not have changed", DataType.STRING, columnTwo.getType()); assertEquals("Type should not have changed", DataType.BOOLEAN, columnThree.getType()); assertEquals("Type should not have changed", DataType.DATE, columnFour.getType()); assertEquals("Type should not have changed", DataType.DECIMAL, columnFive.getType()); assertEquals("Type should not have changed", DataType.DECIMAL, columnSix.getType()); assertEquals("Type should not have changed", DataType.DECIMAL, columnSeven.getType()); assertTrue("Nullable should not have changed", columnOne.isNullable()); assertTrue("Nullable should not have changed", columnTwo.isNullable()); assertTrue("Nullable should not have changed", columnThree.isNullable()); assertTrue("Nullable should not have changed", columnFour.isNullable()); assertFalse("Nullable should not have changed", columnFive.isNullable()); assertFalse("Nullable should not have changed", columnSix.isNullable()); assertTrue("Nullable should not have changed", columnSeven.isNullable()); }
@Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }
@Test public void testChangeColumnNullable() { Schema testSchema = schema(appleTable); ChangeColumn changeColumn = new ChangeColumn("Apple", column("nullcheck", DataType.DECIMAL, 9, 0).nullable(), column("nullcheck", DataType.DECIMAL, 9, 0)); Schema updatedSchema = changeColumn.apply(testSchema); Table resultTable = updatedSchema.getTable("Apple"); assertNotNull(resultTable); assertEquals("Post upgrade column count", 9, resultTable.columns().size()); Column columnOne = resultTable.columns().get(2); Column columnTwo = resultTable.columns().get(3); Column columnThree = resultTable.columns().get(4); Column columnFour = resultTable.columns().get(5); Column columnFive = resultTable.columns().get(6); Column columnSix = resultTable.columns().get(7); Column columnSeven = resultTable.columns().get(8); assertEquals("Post upgrade existing column name 1", "colour", columnOne.getName()); assertEquals("Post upgrade existing column name 2", "variety", columnTwo.getName()); assertEquals("Post upgrade existing column name 3", "ispoisoned", columnThree.getName()); assertEquals("Post upgrade existing column name 4", "datecreated", columnFour.getName()); assertEquals("Post upgrade existing column name 5", "numberavailable", columnFive.getName()); assertEquals("Post upgrade existing column name 6", "totalvalue", columnSix.getName()); assertEquals("Post upgrade existing column name 7", "nullcheck", columnSeven.getName()); assertEquals("Width should not have changed", 10, columnOne.getWidth()); assertEquals("Width should not have changed", 15, columnTwo.getWidth()); assertEquals("Width should not have changed", 5, columnFive.getWidth()); assertEquals("Width should not have changed", 9, columnSix.getWidth()); assertEquals("Width should not have changed", 9, columnSeven.getWidth()); assertEquals("Scale should not have changed", 0, columnOne.getScale()); assertEquals("Scale should not have changed", 0, columnTwo.getScale()); assertEquals("Scale should not have changed", 0, columnFive.getScale()); assertEquals("Scale should not have changed", 2, columnSix.getScale()); assertEquals("Scale should not have changed", 0, columnSeven.getScale()); assertEquals("Type should not have changed", DataType.STRING, columnOne.getType()); assertEquals("Type should not have changed", DataType.STRING, columnTwo.getType()); assertEquals("Type should not have changed", DataType.BOOLEAN, columnThree.getType()); assertEquals("Type should not have changed", DataType.DATE, columnFour.getType()); assertEquals("Type should not have changed", DataType.DECIMAL, columnFive.getType()); assertEquals("Type should not have changed", DataType.DECIMAL, columnSix.getType()); assertEquals("Type should not have changed", DataType.DECIMAL, columnSeven.getType()); assertTrue("Nullable should not have changed", columnOne.isNullable()); assertTrue("Nullable should not have changed", columnTwo.isNullable()); assertTrue("Nullable should not have changed", columnThree.isNullable()); assertTrue("Nullable should not have changed", columnFour.isNullable()); assertFalse("Nullable should not have changed", columnFive.isNullable()); assertFalse("Nullable should not have changed", columnSix.isNullable()); assertFalse("Nullable should not have changed", columnSeven.isNullable()); }
@Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }
@Test public void testReverseChangeLength() { appleTable = table("Apple").columns( idColumn(), versionColumn(), column("colour", DataType.STRING, 35).nullable(), column("variety", DataType.STRING, 15).nullable(), column("ispoisoned", DataType.BOOLEAN).nullable(), column("datecreated", DataType.DATE).nullable(), column("numberavailable", DataType.DECIMAL, 5, 0), column("totalvalue", DataType.DECIMAL, 9, 2), column("nullcheck", DataType.DECIMAL, 9, 0).nullable() ); Schema testSchema = schema(appleTable); ChangeColumn changeColumn = new ChangeColumn("Apple", column("colour", DataType.STRING, 10).nullable(), column("colour", DataType.STRING, 35).nullable()); Schema updatedSchema = changeColumn.reverse(testSchema); Table resultTable = updatedSchema.getTable("Apple"); assertNotNull(resultTable); assertEquals("Post upgrade column count", 9, resultTable.columns().size()); Column columnOne = resultTable.columns().get(2); assertEquals("Post upgrade existing column name 1", "colour", columnOne.getName()); assertEquals("Width should not have changed", 10, columnOne.getWidth()); assertEquals("Scale should not have changed", 0, columnOne.getScale()); assertEquals("Type should not have changed", DataType.STRING, columnOne.getType()); assertTrue("Nullable should not have changed", columnOne.isNullable()); }
@Override public Schema reverse(Schema schema) { return applyChange(schema, toColumn, fromColumn); }
ChangeColumn implements SchemaChange { @Override public Schema reverse(Schema schema) { return applyChange(schema, toColumn, fromColumn); } }
ChangeColumn implements SchemaChange { @Override public Schema reverse(Schema schema) { return applyChange(schema, toColumn, fromColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); }
ChangeColumn implements SchemaChange { @Override public Schema reverse(Schema schema) { return applyChange(schema, toColumn, fromColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }
ChangeColumn implements SchemaChange { @Override public Schema reverse(Schema schema) { return applyChange(schema, toColumn, fromColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }
@Test public void testReverseChangeColumnType() { Table alreadyChangedTable = table("Apple").columns( idColumn(), versionColumn(), column("colour", DataType.STRING, 10).nullable(), column("variety", DataType.STRING, 15).nullable(), column("ispoisoned", DataType.BOOLEAN).nullable(), column("datecreated", DataType.DATE).nullable(), column("numberavailable", DataType.BIG_INTEGER), column("totalvalue", DataType.DECIMAL, 9, 2), column("nullcheck", DataType.DECIMAL, 9, 0).nullable() ).indexes( index("Apple_1").columns("colour") ); Schema testSchema = schema(alreadyChangedTable); ChangeColumn changeColumn = new ChangeColumn("Apple", column("numberavailable", DataType.DECIMAL, 5), column("numberavailable", DataType.BIG_INTEGER)); Schema updatedSchema = changeColumn.reverse(testSchema); Table resultTable = updatedSchema.getTable("Apple"); assertNotNull(resultTable); assertTrue(new SchemaHomology(new ThrowingDifferenceWriter(), "expected", "result").tablesMatch(appleTable, resultTable)); }
@Override public Schema reverse(Schema schema) { return applyChange(schema, toColumn, fromColumn); }
ChangeColumn implements SchemaChange { @Override public Schema reverse(Schema schema) { return applyChange(schema, toColumn, fromColumn); } }
ChangeColumn implements SchemaChange { @Override public Schema reverse(Schema schema) { return applyChange(schema, toColumn, fromColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); }
ChangeColumn implements SchemaChange { @Override public Schema reverse(Schema schema) { return applyChange(schema, toColumn, fromColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }
ChangeColumn implements SchemaChange { @Override public Schema reverse(Schema schema) { return applyChange(schema, toColumn, fromColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Schema schema, ConnectionResources database); @Override Schema reverse(Schema schema); String getTableName(); Column getFromColumn(); Column getToColumn(); }