src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
Asyncs { public static Async<Void> parallel(Async<?>... asyncs) { return parallel(Arrays.asList(asyncs)); } private Asyncs(); static boolean isFinished(Async<?> async); static Async<ValueT> constant(final ValueT val); static Async<ValueT> failure(final Throwable t); static Async<Void> toVoid(Async<ResultT> a); static Async<SecondT> seq(Async<FirstT> first, final Async<SecondT> second); static Async<Void> parallel(Async<?>... asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs, boolean alwaysSucceed); @GwtIncompatible static Async<Void> threadSafeParallel(Collection<? extends Async<?>> asyncs); @GwtIncompatible static Async<List<ItemT>> parallelResult(Collection<Async<ItemT>> asyncs); static Async<List<ItemT>> composite(List<Async<ItemT>> asyncs); static void onAnyResult(Async<?> async, final Runnable r); static Async<ResultT> untilSuccess(final Supplier<Async<ResultT>> s); static Registration delegate(Async<? extends ValueT> from, final AsyncResolver<? super ValueT> to); static Async<Pair<FirstT, SecondT>> pair(Async<FirstT> first, Async<SecondT> second); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async, final long timeout, final TimeUnit timeUnit); }
@Test public void emptyParallel() { assertThat(Asyncs.parallel(), voidSuccess()); }
Asyncs { @GwtIncompatible public static <ItemT> Async<List<ItemT>> parallelResult(Collection<Async<ItemT>> asyncs) { final List<ItemT> result = Collections.synchronizedList(new ArrayList<ItemT>()); for (Async<ItemT> async : asyncs) { async.onSuccess( new Consumer<ItemT>() { @Override public void accept(ItemT item) { result.add(item); } } ); } return seq( parallel(asyncs, true, new ThreadSafeParallelData(asyncs.size())), Asyncs.constant(result) ); } private Asyncs(); static boolean isFinished(Async<?> async); static Async<ValueT> constant(final ValueT val); static Async<ValueT> failure(final Throwable t); static Async<Void> toVoid(Async<ResultT> a); static Async<SecondT> seq(Async<FirstT> first, final Async<SecondT> second); static Async<Void> parallel(Async<?>... asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs, boolean alwaysSucceed); @GwtIncompatible static Async<Void> threadSafeParallel(Collection<? extends Async<?>> asyncs); @GwtIncompatible static Async<List<ItemT>> parallelResult(Collection<Async<ItemT>> asyncs); static Async<List<ItemT>> composite(List<Async<ItemT>> asyncs); static void onAnyResult(Async<?> async, final Runnable r); static Async<ResultT> untilSuccess(final Supplier<Async<ResultT>> s); static Registration delegate(Async<? extends ValueT> from, final AsyncResolver<? super ValueT> to); static Async<Pair<FirstT, SecondT>> pair(Async<FirstT> first, Async<SecondT> second); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async, final long timeout, final TimeUnit timeUnit); }
@Test public void parallelResult() { assertThat( Asyncs.parallelResult(Arrays.asList( Asyncs.constant(1), Asyncs.<Integer>failure(new Throwable()), Asyncs.constant(2) )), result(equalTo(Arrays.asList(1, 2))) ); }
Rectangle { public boolean intersects(Rectangle rect) { Vector t1 = origin; Vector t2 = origin.add(dimension); Vector r1 = rect.origin; Vector r2 = rect.origin.add(rect.dimension); return r2.x >= t1.x && t2.x >= r1.x && r2.y >= t1.y && t2.y >= r1.y; } Rectangle(Vector origin, Vector dimension); Rectangle(int x, int y, int width, int height); Rectangle add(Vector v); Rectangle sub(Vector v); boolean contains(Rectangle r); boolean contains(Vector v); Rectangle union(Rectangle rect); boolean intersects(Rectangle rect); Rectangle intersect(Rectangle r); boolean innerIntersects(Rectangle rect); Rectangle changeDimension(Vector dim); double distance(Vector to); Range<Integer> xRange(); Range<Integer> yRange(); @Override int hashCode(); @Override boolean equals(Object obj); DoubleRectangle toDoubleRectangle(); Vector center(); Segment[] getBoundSegments(); Vector[] getBoundPoints(); @Override String toString(); final Vector origin; final Vector dimension; }
@Test public void intersects() { assertFalse(new Rectangle(0, 0, 1, 1).intersects(new Rectangle(2, 2, 1, 1))); assertTrue(new Rectangle(0, 0, 2, 2).intersects(new Rectangle(1, 1, 2, 2))); }
Asyncs { public static <ResultT> Async<ResultT> untilSuccess(final Supplier<Async<ResultT>> s) { final SimpleAsync<ResultT> result = new SimpleAsync<>(); Async<ResultT> async; final Consumer<ResultT> successConsumer = new Consumer<ResultT>() { @Override public void accept(ResultT item) { result.success(item); } }; try { async = s.get(); } catch (Exception e) { untilSuccess(s).onSuccess(successConsumer); return result; } async.onResult(successConsumer, new Consumer<Throwable>() { @Override public void accept(Throwable failure) { untilSuccess(s).onSuccess(successConsumer); } }); return result; } private Asyncs(); static boolean isFinished(Async<?> async); static Async<ValueT> constant(final ValueT val); static Async<ValueT> failure(final Throwable t); static Async<Void> toVoid(Async<ResultT> a); static Async<SecondT> seq(Async<FirstT> first, final Async<SecondT> second); static Async<Void> parallel(Async<?>... asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs, boolean alwaysSucceed); @GwtIncompatible static Async<Void> threadSafeParallel(Collection<? extends Async<?>> asyncs); @GwtIncompatible static Async<List<ItemT>> parallelResult(Collection<Async<ItemT>> asyncs); static Async<List<ItemT>> composite(List<Async<ItemT>> asyncs); static void onAnyResult(Async<?> async, final Runnable r); static Async<ResultT> untilSuccess(final Supplier<Async<ResultT>> s); static Registration delegate(Async<? extends ValueT> from, final AsyncResolver<? super ValueT> to); static Async<Pair<FirstT, SecondT>> pair(Async<FirstT> first, Async<SecondT> second); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async, final long timeout, final TimeUnit timeUnit); }
@Test public void untilSuccess() { assertThat( Asyncs.untilSuccess(new Supplier<Async<Integer>>() { @Override public Async<Integer> get() { return Asyncs.constant(1); } }), result(equalTo(1))); }
Persisters { public static Persister<Integer> intPersister() { return INT_PERSISTER; } private Persisters(); static Persister<String> stringPersister(); static Persister<Integer> intPersister(); static Persister<Integer> intPersister(final int defaultValue); static Persister<E> enumPersister(final Class<E> cls, final E defaultValue); static Persister<Long> longPersister(); static Persister<Boolean> booleanPersister(); static Persister<Boolean> booleanPersister(final boolean defaultValue); static Persister<Double> doublePersister(); static Persister<Double> doublePersister(final double defaultValue); static Persister<ListT> listPersister(final Persister<T> itemPersister, final Supplier<ListT> empty); }
@Test public void nullInt() { testNull(Persisters.intPersister(10)); }
Persisters { public static Persister<Long> longPersister() { return LONG_PERSISTER; } private Persisters(); static Persister<String> stringPersister(); static Persister<Integer> intPersister(); static Persister<Integer> intPersister(final int defaultValue); static Persister<E> enumPersister(final Class<E> cls, final E defaultValue); static Persister<Long> longPersister(); static Persister<Boolean> booleanPersister(); static Persister<Boolean> booleanPersister(final boolean defaultValue); static Persister<Double> doublePersister(); static Persister<Double> doublePersister(final double defaultValue); static Persister<ListT> listPersister(final Persister<T> itemPersister, final Supplier<ListT> empty); }
@Test public void nullLong() { testNull(Persisters.longPersister()); }
Persisters { public static Persister<Boolean> booleanPersister() { return BOOLEAN_PERSISTER; } private Persisters(); static Persister<String> stringPersister(); static Persister<Integer> intPersister(); static Persister<Integer> intPersister(final int defaultValue); static Persister<E> enumPersister(final Class<E> cls, final E defaultValue); static Persister<Long> longPersister(); static Persister<Boolean> booleanPersister(); static Persister<Boolean> booleanPersister(final boolean defaultValue); static Persister<Double> doublePersister(); static Persister<Double> doublePersister(final double defaultValue); static Persister<ListT> listPersister(final Persister<T> itemPersister, final Supplier<ListT> empty); }
@Test public void nullBoolean() { testNull(Persisters.booleanPersister(true)); }
Persisters { public static Persister<Double> doublePersister() { return DOUBLE_PERSISTER; } private Persisters(); static Persister<String> stringPersister(); static Persister<Integer> intPersister(); static Persister<Integer> intPersister(final int defaultValue); static Persister<E> enumPersister(final Class<E> cls, final E defaultValue); static Persister<Long> longPersister(); static Persister<Boolean> booleanPersister(); static Persister<Boolean> booleanPersister(final boolean defaultValue); static Persister<Double> doublePersister(); static Persister<Double> doublePersister(final double defaultValue); static Persister<ListT> listPersister(final Persister<T> itemPersister, final Supplier<ListT> empty); }
@Test public void nullDouble() { testNull(Persisters.doublePersister(1.5)); }
Persisters { public static Persister<String> stringPersister() { return STRING_PERSISTER; } private Persisters(); static Persister<String> stringPersister(); static Persister<Integer> intPersister(); static Persister<Integer> intPersister(final int defaultValue); static Persister<E> enumPersister(final Class<E> cls, final E defaultValue); static Persister<Long> longPersister(); static Persister<Boolean> booleanPersister(); static Persister<Boolean> booleanPersister(final boolean defaultValue); static Persister<Double> doublePersister(); static Persister<Double> doublePersister(final double defaultValue); static Persister<ListT> listPersister(final Persister<T> itemPersister, final Supplier<ListT> empty); }
@Test public void nullString() { Persister<String> persister = Persisters.stringPersister(); assertNull(persister.deserialize(persister.serialize(null))); }
Interval { public boolean contains(int point) { return myLowerBound <= point && point <= myUpperBound; } Interval(int lowerBound, int upperBound); int getLowerBound(); int getUpperBound(); int getLength(); boolean contains(int point); boolean contains(Interval other); boolean intersects(Interval other); Interval union(Interval other); Interval add(int delta); Interval sub(int delta); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void contains() { checkContains(i_1_4); checkContains(2, 3); checkContains(1, 2); checkContains(3, 4); checkNotContains(0, 4); checkNotContains(1, 5); checkNotContains(0, 5); checkNotContains(4, 10); }
Interval { public boolean intersects(Interval other) { return contains(other.getLowerBound()) || other.contains(getLowerBound()); } Interval(int lowerBound, int upperBound); int getLowerBound(); int getUpperBound(); int getLength(); boolean contains(int point); boolean contains(Interval other); boolean intersects(Interval other); Interval union(Interval other); Interval add(int delta); Interval sub(int delta); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void intersects() { checkIntersects(i_1_4); checkIntersects(2, 3); checkIntersects(1, 2); checkIntersects(3, 4); checkIntersects(0, 4); checkIntersects(0, 1); checkIntersects(2, 5); checkIntersects(4, 5); checkIntersects(0, 5); checkNotIntersects(-1, 0); checkNotIntersects(5, 6); }
Interval { public Interval union(Interval other) { return new Interval(Math.min(myLowerBound, other.myLowerBound), Math.max(myUpperBound, other.myUpperBound)); } Interval(int lowerBound, int upperBound); int getLowerBound(); int getUpperBound(); int getLength(); boolean contains(int point); boolean contains(Interval other); boolean intersects(Interval other); Interval union(Interval other); Interval add(int delta); Interval sub(int delta); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void union() { checkUnion(i(1, 2), i(3, 4)); checkUnion(i(1, 3), i(2, 4)); checkUnion(i(3, 4), i(1, 2)); checkUnion(i(2, 4), i(1, 3)); checkUnion(i_1_4, i(2, 3)); checkUnion(i(2, 3), i_1_4); }
Interval { public Interval add(int delta) { return new Interval(myLowerBound + delta, myUpperBound + delta); } Interval(int lowerBound, int upperBound); int getLowerBound(); int getUpperBound(); int getLength(); boolean contains(int point); boolean contains(Interval other); boolean intersects(Interval other); Interval union(Interval other); Interval add(int delta); Interval sub(int delta); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void add() { checkAdd(i(0, 3), 1); checkAdd(i_1_4, 0); checkAdd(i(2, 5), -1); }
Rectangle { public Rectangle intersect(Rectangle r) { if (!intersects(r)) { throw new IllegalStateException("rectangle [" + this + "] doesn't intersect [" + r + "]"); } Vector too = origin.add(dimension); Vector roo = r.origin.add(r.dimension); Vector ioo = too.min(roo); Vector io = origin.max(r.origin); return new Rectangle(io, ioo.sub(io)); } Rectangle(Vector origin, Vector dimension); Rectangle(int x, int y, int width, int height); Rectangle add(Vector v); Rectangle sub(Vector v); boolean contains(Rectangle r); boolean contains(Vector v); Rectangle union(Rectangle rect); boolean intersects(Rectangle rect); Rectangle intersect(Rectangle r); boolean innerIntersects(Rectangle rect); Rectangle changeDimension(Vector dim); double distance(Vector to); Range<Integer> xRange(); Range<Integer> yRange(); @Override int hashCode(); @Override boolean equals(Object obj); DoubleRectangle toDoubleRectangle(); Vector center(); Segment[] getBoundSegments(); Vector[] getBoundPoints(); @Override String toString(); final Vector origin; final Vector dimension; }
@Test public void intersection() { assertEquals(new Rectangle(1, 1, 1, 1), new Rectangle(0, 0, 2, 2).intersect(new Rectangle(1, 1, 2, 2))); assertEquals(new Rectangle(1, 1, 2, 2), new Rectangle(0, 0, 3, 3).intersect(new Rectangle(1, 1, 2, 2))); }
Interval { public Interval sub(int delta) { return new Interval(myLowerBound - delta, myUpperBound - delta); } Interval(int lowerBound, int upperBound); int getLowerBound(); int getUpperBound(); int getLength(); boolean contains(int point); boolean contains(Interval other); boolean intersects(Interval other); Interval union(Interval other); Interval add(int delta); Interval sub(int delta); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void sub() { checkSub(i(0, 3), -1); checkSub(i_1_4, 0); checkSub(i(2, 5), 1); }
ThrowableHandlers { static void handleError(Throwable t) { if (isClient(t)) { return; } Error error = getError(t); if (error != null) { throw error; } } private ThrowableHandlers(); static Registration addHandler(Consumer<? super Throwable> handler); static void asInProduction(Runnable r); static void handle(Throwable t); static boolean checkForLeaks(PrintStream stream); static final boolean DEBUG; }
@Test public void handleClientException() { ThrowableHandlers.handleError(createGwtException()); } @Test public void handleClientError() { ThrowableHandlers.handleError(createGwtError()); } @Test public void handleClientInnerError() { ThrowableHandlers.handleError(new RuntimeException(createGwtError())); } @Test public void handleServerException() { ThrowableHandlers.handleError(new RuntimeException()); } @Test(expected = NoClassDefFoundError.class) public void handleServerError() { ThrowableHandlers.handleError(new NoClassDefFoundError()); } @Test(expected = NoClassDefFoundError.class) public void handleServerInnerError() { ThrowableHandlers.handleError(new RuntimeException(new NoClassDefFoundError())); }
RunningEdtManager implements EdtManager, EventDispatchThread { @Override public final void schedule(Runnable r) { checkCanSchedule(); doSchedule(r); } RunningEdtManager(); RunningEdtManager(String name); @Override EventDispatchThread getEdt(); @Override final void finish(); @Override final void kill(); @Override long getCurrentTimeMillis(); @Override final void schedule(Runnable r); @Override final Registration schedule(int delay, Runnable r); @Override final Registration scheduleRepeating(int period, Runnable r); @Override final boolean isStopped(); final void flush(); final void flush(final int tasksNum); String getName(); int size(); boolean isEmpty(); @Override String toString(); }
@Test public void exceptionInTask() { ThrowableHandlers.asInProduction(new Runnable() { @Override public void run() { manager.schedule(new Runnable() { @Override public void run() { throw new RuntimeException(); } }); } }); final Value<Boolean> taskCompleted = new Value<>(false); manager.schedule(new Runnable() { @Override public void run() { taskCompleted.set(true); } }); assertTrue(taskCompleted.get()); }
EdtManagerPool implements EdtManagerFactory { boolean checkManager(EdtManager manager) { synchronized (myLock) { EdtManagerAdapter adapter = (EdtManagerAdapter) manager; return adapter.myManager == myManagers[adapter.myIndex]; } } EdtManagerPool(String name, int poolSize, EdtManagerFactory factory); @Override EdtManager createEdtManager(String name); }
@Test public void checkManager() { init(); EdtManager temp1 = createManager(); EdtManager checking = createManager(); temp1.finish(); EdtManager temp2 = createManager(); assertTrue(pool.checkManager(checking)); }
ExecutorEdtManager implements EdtManager, EventDispatchThread { @Override public void finish() { ensureCanShutdown(); myEdt.getExecutor().shutdown(); waitTermination(); } ExecutorEdtManager(); ExecutorEdtManager(String name); @Override EventDispatchThread getEdt(); @Override void finish(); @Override void kill(); @Override boolean isStopped(); @Override long getCurrentTimeMillis(); @Override void schedule(Runnable runnable); @Override Registration schedule(int delay, Runnable r); @Override Registration scheduleRepeating(int period, Runnable r); @Override String toString(); }
@Test public void finishFromItself() { shutdownFromItself(new Consumer<EdtManager>() { @Override public void accept(EdtManager edtManager) { edtManager.finish(); } }); }
Rectangle { public Rectangle union(Rectangle rect) { Vector newOrigin = origin.min(rect.origin); Vector corner = origin.add(dimension); Vector rectCorner = rect.origin.add(rect.dimension); Vector newCorner = corner.max(rectCorner); Vector newDimension = newCorner.sub(newOrigin); return new Rectangle(newOrigin, newDimension); } Rectangle(Vector origin, Vector dimension); Rectangle(int x, int y, int width, int height); Rectangle add(Vector v); Rectangle sub(Vector v); boolean contains(Rectangle r); boolean contains(Vector v); Rectangle union(Rectangle rect); boolean intersects(Rectangle rect); Rectangle intersect(Rectangle r); boolean innerIntersects(Rectangle rect); Rectangle changeDimension(Vector dim); double distance(Vector to); Range<Integer> xRange(); Range<Integer> yRange(); @Override int hashCode(); @Override boolean equals(Object obj); DoubleRectangle toDoubleRectangle(); Vector center(); Segment[] getBoundSegments(); Vector[] getBoundPoints(); @Override String toString(); final Vector origin; final Vector dimension; }
@Test public void union() { assertEquals(new Rectangle(0, 0, 3, 3), new Rectangle(0, 0, 1, 1).union(new Rectangle(2, 2, 1, 1))); }
ExecutorEdtManager implements EdtManager, EventDispatchThread { @Override public void kill() { ensureCanShutdown(); myEdt.getExecutor().shutdownNow(); waitTermination(); } ExecutorEdtManager(); ExecutorEdtManager(String name); @Override EventDispatchThread getEdt(); @Override void finish(); @Override void kill(); @Override boolean isStopped(); @Override long getCurrentTimeMillis(); @Override void schedule(Runnable runnable); @Override Registration schedule(int delay, Runnable r); @Override Registration scheduleRepeating(int period, Runnable r); @Override String toString(); }
@Test public void killFromItself() { shutdownFromItself(new Consumer<EdtManager>() { @Override public void accept(EdtManager edtManager) { edtManager.kill(); } }); }
ListItemProperty extends BaseReadableProperty<ValueT> implements Property<ValueT>, Disposable { @Override public ValueT get() { if (isValid()) { return myList.get(getIndex().get()); } else { return null; } } ListItemProperty(ObservableList<ValueT> list, int index); @Override Registration addHandler(EventHandler<? super PropertyChangeEvent<ValueT>> handler); @Override ValueT get(); @Override void set(ValueT value); boolean isValid(); @Override void dispose(); ReadableProperty<Integer> getIndex(); }
@Test public void getsTheRightItem() { ObservableList<Integer> list = createList(5); ListItemProperty<Integer> p2 = new ListItemProperty<>(list, 2); assertEquals(2, p2.get().intValue()); ListItemProperty<Integer> p4 = new ListItemProperty<>(list, 4); assertEquals(4, p4.get().intValue()); }
ListItemProperty extends BaseReadableProperty<ValueT> implements Property<ValueT>, Disposable { @Override public void set(ValueT value) { if (isValid()) { myList.set(getIndex().get(), value); } else { throw new IllegalStateException("Property points to an invalid item, can’t set"); } } ListItemProperty(ObservableList<ValueT> list, int index); @Override Registration addHandler(EventHandler<? super PropertyChangeEvent<ValueT>> handler); @Override ValueT get(); @Override void set(ValueT value); boolean isValid(); @Override void dispose(); ReadableProperty<Integer> getIndex(); }
@Test public void setsTheRightItem() { ObservableList<Integer> list = createList(5); ListItemProperty<Integer> p2 = new ListItemProperty<>(list, 2); p2.set(12); assertEquals("[0, 1, 12, 3, 4]", "" + list); ListItemProperty<Integer> p4 = new ListItemProperty<>(list, 4); p4.set(14); assertEquals("[0, 1, 12, 3, 14]", "" + list); } @Test public void firesOnListSet() { list.add(2, 22); list.set(3, 12); assertThat(p1Handler, noEvents()); assertThat(p2Handler, singleEvent( allOf(oldValueIs(2), newValueIs(12)))); assertThat(p3Handler, noEvents()); } @Test public void firesOnPropertySet() { ObservableList<Integer> list = createList(5); ListItemProperty<Integer> p2 = new ListItemProperty<>(list, 2); MatchingHandler<PropertyChangeEvent<Integer>> p2handler = setTestHandler(p2); p2.set(12); assertThat(p2handler, singleEvent( allOf(oldValueIs(2), newValueIs(12)))); } @Test public void indexFiresNotOnListSet() { list.set(2, 22); assertThat(p1indexHandler, noEvents()); assertThat(p2indexHandler, noEvents()); assertThat(p3indexHandler, noEvents()); }
ListItemProperty extends BaseReadableProperty<ValueT> implements Property<ValueT>, Disposable { @Override public void dispose() { if (myDisposed) { throw new IllegalStateException("Double dispose"); } if (isValid()) { myReg.dispose(); } myDisposed = true; } ListItemProperty(ObservableList<ValueT> list, int index); @Override Registration addHandler(EventHandler<? super PropertyChangeEvent<ValueT>> handler); @Override ValueT get(); @Override void set(ValueT value); boolean isValid(); @Override void dispose(); ReadableProperty<Integer> getIndex(); }
@Test public void disposeImmediately() { p1.dispose(); exception.expect(IllegalStateException.class); p1.dispose(); } @Test public void indexFiresNotOnDispose() { p1.dispose(); assertThat(p1indexHandler, noEvents()); } @Test public void indexFiresNotOnDisposeInvalid() { list.remove(1); assertThat(p1indexHandler, allEvents(hasSize(1))); p1.dispose(); assertThat(p1indexHandler, allEvents(hasSize(1))); }
UpdatableProperty extends BaseDerivedProperty<ValueT> { public void update() { somethingChanged(); } protected UpdatableProperty(); @Override String getPropExpr(); void update(); }
@Test public void updateFiresEvent() { EventHandler<? super PropertyChangeEvent<String>> handler = Mockito.mock(EventHandler.class); property.addHandler(handler); value = "z"; property.update(); Mockito.verify(handler).onEvent(new PropertyChangeEvent<>(null, "z")); } @Test public void updateWithoutChangeDoesntFireEvent() { EventHandler<? super PropertyChangeEvent<String>> handler = Mockito.mock(EventHandler.class); property.addHandler(handler); property.update(); Mockito.verifyNoMoreInteractions(handler); }
Rectangle { @Override public int hashCode() { return origin.hashCode() * 31 + dimension.hashCode(); } Rectangle(Vector origin, Vector dimension); Rectangle(int x, int y, int width, int height); Rectangle add(Vector v); Rectangle sub(Vector v); boolean contains(Rectangle r); boolean contains(Vector v); Rectangle union(Rectangle rect); boolean intersects(Rectangle rect); Rectangle intersect(Rectangle r); boolean innerIntersects(Rectangle rect); Rectangle changeDimension(Vector dim); double distance(Vector to); Range<Integer> xRange(); Range<Integer> yRange(); @Override int hashCode(); @Override boolean equals(Object obj); DoubleRectangle toDoubleRectangle(); Vector center(); Segment[] getBoundSegments(); Vector[] getBoundPoints(); @Override String toString(); final Vector origin; final Vector dimension; }
@Test public void hashCodeWorks() { assertEquals(new Rectangle(0, 0, 3, 3).hashCode(), new Rectangle(0, 0, 3, 3).hashCode()); }
PropertyPersisters { public static <T> Persister<Property<T>> valuePropertyPersister(final Persister<T> itemPersister) { return new Persister<Property<T>>() { @Override public Property<T> deserialize(String value) { if (value == null) { return null; } if (!value.isEmpty() && value.charAt(0) == 'v') { return new ValueProperty<>(itemPersister.deserialize(value.substring(1))); } return new ValueProperty<>(); } @Override public String serialize(Property<T> value) { if (value == null) { return null; } if (value.get() == null) { return "n"; } else { return "v" + itemPersister.serialize(value.get()); } } @Override public String toString() { return "valuePropertyPersister[using = " + itemPersister + "]"; } }; } private PropertyPersisters(); static Persister<Property<T>> valuePropertyPersister(final Persister<T> itemPersister); }
@Test public void nullStringValueProperty() { testNull(PropertyPersisters.valuePropertyPersister(stringPersister())); } @Test public void valuePropertyEmptyString() { assertNull(PropertyPersisters.valuePropertyPersister(stringPersister()).deserialize("").get()); }
PropertyBinding { public static <ValueT> Registration bindTwoWay(final Property<ValueT> source, final Property<ValueT> target) { final Property<Boolean> syncing = new ValueProperty<>(false); target.set(source.get()); class UpdatingEventHandler implements EventHandler<PropertyChangeEvent<ValueT>> { private boolean myForward; UpdatingEventHandler(boolean forward) { myForward = forward; } @Override public void onEvent(PropertyChangeEvent<ValueT> event) { if (syncing.get()) return; syncing.set(true); try { if (myForward) { target.set(source.get()); } else { source.set(target.get()); } } finally { syncing.set(false); } } } return new CompositeRegistration( source.addHandler(new UpdatingEventHandler(true)), target.addHandler(new UpdatingEventHandler(false)) ); } private PropertyBinding(); static Registration bindOneWay( ReadableProperty<? extends ValueT> source, final WritableProperty<? super ValueT> target); static Registration bindTwoWay(final Property<ValueT> source, final Property<ValueT> target); }
@Test public void bidirectionalSync() { source.set("239"); Registration reg = PropertyBinding.bindTwoWay(source, target); assertEquals("239", target.get()); target.set("z"); assertEquals("z", source.get()); reg.remove(); source.set("zzz"); assertEquals("z", target.get()); }
ListMap { @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{"); for (int i = 0; i < myData.length; i += 2) { @SuppressWarnings("unchecked") K k = (K) myData[i]; @SuppressWarnings("unchecked") V v = (V) myData[i + 1]; if (i != 0) { builder.append(","); } builder.append(k).append("=").append(v); } builder.append("}"); return builder.toString(); } ListMap(); boolean containsKey(K key); V remove(K key); Set<K> keySet(); boolean isEmpty(); Collection<V> values(); Set<Entry> entrySet(); int size(); V put(K key, V value); V get(K key); @Override String toString(); }
@Test public void empty() { assertEquals("{}", list.toString()); }
ListMap { public V put(K key, V value) { int index = findByKey(key); if (index >= 0) { @SuppressWarnings("unchecked") V oldValue = (V) myData[index + 1]; myData[index + 1] = value; return oldValue; } Object[] newArray = new Object[myData.length + 2]; System.arraycopy(myData, 0, newArray, 0, myData.length); newArray[myData.length] = key; newArray[myData.length + 1] = value; myData = newArray; return null; } ListMap(); boolean containsKey(K key); V remove(K key); Set<K> keySet(); boolean isEmpty(); Collection<V> values(); Set<Entry> entrySet(); int size(); V put(K key, V value); V get(K key); @Override String toString(); }
@Test public void put() { list.put("a", "b"); assertEquals("{a=b}", list.toString()); }
ListMap { public boolean isEmpty() { return size() == 0; } ListMap(); boolean containsKey(K key); V remove(K key); Set<K> keySet(); boolean isEmpty(); Collection<V> values(); Set<Entry> entrySet(); int size(); V put(K key, V value); V get(K key); @Override String toString(); }
@Test public void isEmpty() { assertTrue(list.isEmpty()); }
ListMap { public boolean containsKey(K key) { return findByKey(key) >= 0; } ListMap(); boolean containsKey(K key); V remove(K key); Set<K> keySet(); boolean isEmpty(); Collection<V> values(); Set<Entry> entrySet(); int size(); V put(K key, V value); V get(K key); @Override String toString(); }
@Test public void containsKey() { list.put("a", "b"); assertTrue(list.containsKey("a")); }
ObservableCollections { public static <ItemT> ReadableProperty<Integer> count( final ObservableCollection<ItemT> collection, final Predicate<? super ItemT> predicate) { return new BaseDerivedProperty<Integer>(simpleCount(predicate, collection)) { private Registration myCollectionRegistration; private int myCount; @Override protected void doAddListeners() { myCollectionRegistration = collection.addListener(new CollectionAdapter<ItemT>() { @Override public void onItemAdded(CollectionItemEvent<? extends ItemT> event) { if (predicate.test(event.getNewItem())) { myCount++; } somethingChanged(); } @Override public void onItemRemoved(CollectionItemEvent<? extends ItemT> event) { if (predicate.test(event.getOldItem())) { myCount--; } somethingChanged(); } }); myCount = simpleCount(predicate, collection); } @Override protected void doRemoveListeners() { myCollectionRegistration.remove(); myCollectionRegistration = null; } @Override protected Integer doGet() { if (myCollectionRegistration == null) { return simpleCount(predicate, collection); } else { return myCount; } } }; } private ObservableCollections(); static ObservableList<ItemT> toObservable(List<ItemT> l); static ObservableSet<ItemT> toObservable(Set<ItemT> s); static WritableProperty<ItemT> asWritableProp(final ObservableCollection<ItemT> coll); static Property<List<ItemT>> asProperty(final ObservableList<ItemT> list); static ObservableCollection<ItemT> empty(); static ObservableList<ItemT> emptyList(); static ReadableProperty<Integer> count( final ObservableCollection<ItemT> collection, final Predicate<? super ItemT> predicate); static ReadableProperty<Boolean> all( final ObservableCollection<ItemT> collection, Predicate<? super ItemT> predicate); static ReadableProperty<Boolean> any( ObservableCollection<ItemT> collection, Predicate<? super ItemT> predicate); static ObservableCollection<ItemT> selectCollection( ReadableProperty<ValueT> p, Function<ValueT, ObservableCollection<? extends ItemT>> s); static ObservableList<ItemT> selectList( ReadableProperty<ValueT> p, Function<ValueT, ObservableList<? extends ItemT>> s); }
@Test public void count() { ObservableList<String> collection = new ObservableArrayList<>(); ReadableProperty<Integer> count = ObservableCollections.count(collection, STARTS_WITH_A); runChanges(collection, count); } @Test public void countListener() { ObservableList<String> collection = new ObservableArrayList<>(); ReadableProperty<Integer> count = ObservableCollections.count(collection, STARTS_WITH_A); final Value<Integer> lastUpdate = new Value<>(0); count.addHandler(new EventHandler<PropertyChangeEvent<Integer>>() { @Override public void onEvent(PropertyChangeEvent<Integer> event) { lastUpdate.set(event.getNewValue()); } }); runChanges(collection, lastUpdate); }
Vector { @Override public boolean equals(Object obj) { if (!(obj instanceof Vector)) return false; Vector otherVector = (Vector) obj; return x == otherVector.x && y == otherVector.y; } Vector(int x, int y); Vector add(Vector v); Vector sub(Vector v); Vector negate(); Vector max(Vector v); Vector min(Vector v); Vector mul(int i); Vector div(int i); int dotProduct(Vector v); double length(); DoubleVector toDoubleVector(); Vector abs(); boolean isParallel(Vector to); Vector orthogonal(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); int getX(); int getY(); int get(Axis axis); static final Vector ZERO; final int x; final int y; }
@Test public void equals() { assertThat(new Vector(1, 2), is(new Vector(1, 2))); assertThat(new Vector(1, 2), is(not(new Vector(2, 1)))); }
ObservableCollections { public static <ItemT> ReadableProperty<Boolean> all( final ObservableCollection<ItemT> collection, Predicate<? super ItemT> predicate) { return Properties.map(count(collection, predicate), new Function<Integer, Boolean>() { @Override public Boolean apply(Integer value) { return value == collection.size(); } }); } private ObservableCollections(); static ObservableList<ItemT> toObservable(List<ItemT> l); static ObservableSet<ItemT> toObservable(Set<ItemT> s); static WritableProperty<ItemT> asWritableProp(final ObservableCollection<ItemT> coll); static Property<List<ItemT>> asProperty(final ObservableList<ItemT> list); static ObservableCollection<ItemT> empty(); static ObservableList<ItemT> emptyList(); static ReadableProperty<Integer> count( final ObservableCollection<ItemT> collection, final Predicate<? super ItemT> predicate); static ReadableProperty<Boolean> all( final ObservableCollection<ItemT> collection, Predicate<? super ItemT> predicate); static ReadableProperty<Boolean> any( ObservableCollection<ItemT> collection, Predicate<? super ItemT> predicate); static ObservableCollection<ItemT> selectCollection( ReadableProperty<ValueT> p, Function<ValueT, ObservableCollection<? extends ItemT>> s); static ObservableList<ItemT> selectList( ReadableProperty<ValueT> p, Function<ValueT, ObservableList<? extends ItemT>> s); }
@Test public void allTest() { ObservableCollection<String> collection = new ObservableArrayList<>(); ReadableProperty<Boolean> all = ObservableCollections.all(collection, STARTS_WITH_A); assertTrue(all.get()); collection.add("a"); assertTrue(all.get()); collection.add("b"); assertFalse(all.get()); collection.clear(); assertTrue(all.get()); }
ObservableCollections { public static <ItemT> ReadableProperty<Boolean> any( ObservableCollection<ItemT> collection, Predicate<? super ItemT> predicate) { return Properties.map(count(collection, predicate), new Function<Integer, Boolean>() { @Override public Boolean apply(Integer value) { return value > 0; } }); } private ObservableCollections(); static ObservableList<ItemT> toObservable(List<ItemT> l); static ObservableSet<ItemT> toObservable(Set<ItemT> s); static WritableProperty<ItemT> asWritableProp(final ObservableCollection<ItemT> coll); static Property<List<ItemT>> asProperty(final ObservableList<ItemT> list); static ObservableCollection<ItemT> empty(); static ObservableList<ItemT> emptyList(); static ReadableProperty<Integer> count( final ObservableCollection<ItemT> collection, final Predicate<? super ItemT> predicate); static ReadableProperty<Boolean> all( final ObservableCollection<ItemT> collection, Predicate<? super ItemT> predicate); static ReadableProperty<Boolean> any( ObservableCollection<ItemT> collection, Predicate<? super ItemT> predicate); static ObservableCollection<ItemT> selectCollection( ReadableProperty<ValueT> p, Function<ValueT, ObservableCollection<? extends ItemT>> s); static ObservableList<ItemT> selectList( ReadableProperty<ValueT> p, Function<ValueT, ObservableList<? extends ItemT>> s); }
@Test public void anyTest() { ObservableCollection<String> collection = new ObservableArrayList<>(); ReadableProperty<Boolean> any = ObservableCollections.any(collection, STARTS_WITH_A); assertFalse(any.get()); collection.add("b"); assertFalse(any.get()); collection.add("a"); assertTrue(any.get()); collection.clear(); assertFalse(any.get()); }
ObservableSetWrapper implements ObservableSet<TargetItemT> { @Override public boolean add(TargetItemT wrapper) { return mySource.add(myTtoS.apply(wrapper)); } ObservableSetWrapper(ObservableSet<SourceItemT> source, Function<SourceItemT, TargetItemT> toTarget, Function<TargetItemT, SourceItemT> toSource); @Override Registration addListener(CollectionListener<? super TargetItemT> l); @Override Registration addHandler(final EventHandler<? super CollectionItemEvent<? extends TargetItemT>> handler); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<TargetItemT> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(TargetItemT wrapper); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends TargetItemT> c); @Override boolean retainAll(Collection<?> c); @Override boolean removeAll(Collection<?> c); @Override void clear(); }
@Test public void setMapAddSource() { source.add(15.0); assertThat(target, containsInAnyOrder(11, 16, 21, 31)); listener.assertEvents(1, 0); assertThat(listener.getAddEvents().get(0), is(addEvent(equalTo(16), equalTo(-1)))); } @Test public void listMapAddTarget() { target.add(15); assertThat(target, containsInAnyOrder(11, 15, 21, 31)); assertThat(source, containsInAnyOrder(10.0, 14.0, 20.0, 30.0)); listener.assertEvents(1, 0); assertThat(listener.getAddEvents().get(0), is(addEvent(equalTo(15), equalTo(-1)))); }
ObservableSetWrapper implements ObservableSet<TargetItemT> { @Override public boolean remove(Object o) { @SuppressWarnings("unchecked") TargetItemT targetItem = (TargetItemT) o; return mySource.remove(myTtoS.apply(targetItem)); } ObservableSetWrapper(ObservableSet<SourceItemT> source, Function<SourceItemT, TargetItemT> toTarget, Function<TargetItemT, SourceItemT> toSource); @Override Registration addListener(CollectionListener<? super TargetItemT> l); @Override Registration addHandler(final EventHandler<? super CollectionItemEvent<? extends TargetItemT>> handler); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<TargetItemT> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(TargetItemT wrapper); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends TargetItemT> c); @Override boolean retainAll(Collection<?> c); @Override boolean removeAll(Collection<?> c); @Override void clear(); }
@Test public void setMapRemoveSource() { source.remove(30.0); assertThat(target, containsInAnyOrder(11, 21)); listener.assertEvents(0, 1); assertThat(listener.getRemoveEvents().get(0), is(removeEvent(equalTo(31), equalTo(-1)))); } @Test public void setMapRemoveTarget() { target.remove(31); assertThat(target, containsInAnyOrder(11, 21)); assertThat(source, containsInAnyOrder(10.0, 20.0)); listener.assertEvents(0, 1); assertThat(listener.getRemoveEvents().get(0), is(removeEvent(equalTo(31), equalTo(-1)))); }
TreePath implements Comparable<TreePath<CompositeT>> { @Override public int compareTo(TreePath<CompositeT> o) { int maxIndex = Math.min(myPath.size(), o.myPath.size()); for (int i = 0; i < maxIndex; i++) { int delta = myPath.get(i) - o.myPath.get(i); if (delta != 0) return delta; } return myPath.size() - o.myPath.size(); } TreePath(CompositeT composite); TreePath(CompositeT from, CompositeT to); private TreePath(List<Integer> path); static void sort(List<? extends CompositeT> composites); static TreePath<CompositeT> deserialize(String text); CompositeT get(CompositeT root); boolean isValid(CompositeT root); boolean isEmpty(); int getLastIndex(); TreePath<CompositeT> getParent(); TreePath<CompositeT> getChild(int index); String serialize(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(TreePath<CompositeT> o); @Override String toString(); }
@Test public void pathComparison() { assertTrue(new TreePath<>(root).compareTo(new TreePath<>(child1)) < 0); assertTrue(new TreePath<>(child1).compareTo(new TreePath<>(child2)) < 0); assertEquals(0, new TreePath<>(child1).compareTo(new TreePath<>(child1))); }
TreePath implements Comparable<TreePath<CompositeT>> { public static <CompositeT extends Composite<CompositeT>> void sort(List<? extends CompositeT> composites) { final Map<CompositeT, TreePath<CompositeT>> paths = new HashMap<>(); for (CompositeT composite : composites) { paths.put(composite, new TreePath<>(composite)); } Collections.sort(composites, new Comparator<CompositeT>() { @Override public int compare(CompositeT composite1, CompositeT composite2) { return paths.get(composite1).compareTo(paths.get(composite2)); } }); } TreePath(CompositeT composite); TreePath(CompositeT from, CompositeT to); private TreePath(List<Integer> path); static void sort(List<? extends CompositeT> composites); static TreePath<CompositeT> deserialize(String text); CompositeT get(CompositeT root); boolean isValid(CompositeT root); boolean isEmpty(); int getLastIndex(); TreePath<CompositeT> getParent(); TreePath<CompositeT> getChild(int index); String serialize(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(TreePath<CompositeT> o); @Override String toString(); }
@Test public void sortByPath() { List<TestComposite> composites = new ArrayList<>(Arrays.asList(child2, child1, root)); TreePath.sort(composites); assertEquals(Arrays.asList(root, child1, child2), composites); }
TreePath implements Comparable<TreePath<CompositeT>> { public boolean isValid(CompositeT root) { CompositeT current = root; for (Integer i : myPath) { List<CompositeT> children = current.children(); if (i >= children.size()) { return false; } current = children.get(i); } return true; } TreePath(CompositeT composite); TreePath(CompositeT from, CompositeT to); private TreePath(List<Integer> path); static void sort(List<? extends CompositeT> composites); static TreePath<CompositeT> deserialize(String text); CompositeT get(CompositeT root); boolean isValid(CompositeT root); boolean isEmpty(); int getLastIndex(); TreePath<CompositeT> getParent(); TreePath<CompositeT> getChild(int index); String serialize(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(TreePath<CompositeT> o); @Override String toString(); }
@Test public void pathValidity() { TreePath<TestComposite> path = new TreePath<>(child1); assertTrue(path.isValid(root)); assertFalse(path.isValid(child1)); }
Vector { public Vector add(Vector v) { return new Vector(x + v.x, y + v.y); } Vector(int x, int y); Vector add(Vector v); Vector sub(Vector v); Vector negate(); Vector max(Vector v); Vector min(Vector v); Vector mul(int i); Vector div(int i); int dotProduct(Vector v); double length(); DoubleVector toDoubleVector(); Vector abs(); boolean isParallel(Vector to); Vector orthogonal(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); int getX(); int getY(); int get(Axis axis); static final Vector ZERO; final int x; final int y; }
@Test public void add() { assertThat(new Vector(1, 2).add(new Vector(1, 2)), is(new Vector(2, 4))); }
AlphaNumericComparator implements Comparator { public int compare(Object o1, Object o2) { String s1 = o1.toString(); String s2 = o2.toString(); int n1 = s1.length(), n2 = s2.length(); int i1 = 0, i2 = 0; while (i1 < n1 && i2 < n2) { int p1 = i1; int p2 = i2; char c1 = s1.charAt(i1++); char c2 = s2.charAt(i2++); if(c1 != c2) { if (Character.isDigit(c1) && Character.isDigit(c2)) { int value1 = 0, value2 = 0; while (i1 < n1 && Character.isDigit(c1 = s1.charAt(i1))) { i1++; } value1 = Integer.parseInt(s1.substring(p1, i1)); while (i2 < n2 && Character.isDigit(c2 = s2.charAt(i2))) { i2++; } value2 = Integer.parseInt(s2.substring(p2, i2)); if (value1 != value2) { return value1 - value2; } } return c1 - c2; } } return n1 - n2; } AlphaNumericComparator(); int compare(Object o1, Object o2); }
@Test public void testBasic() { Comparator c = new AlphaNumericComparator(); assertTrue(c.compare("a", "b") < 0); assertTrue(c.compare("shard1", "shard1") == 0); assertTrue(c.compare("shard10", "shard10") == 0); assertTrue(c.compare("shard1", "shard2") < 0); assertTrue(c.compare("shard9", "shard10") < 0); assertTrue(c.compare("shard09", "shard10") < 0); assertTrue(c.compare("shard019", "shard10") > 0); assertTrue(c.compare("shard10", "shard11") < 0); assertTrue(c.compare("shard10z", "shard10z") == 0); assertTrue(c.compare("shard10z", "shard11z") < 0); assertTrue(c.compare("shard10a", "shard10z") < 0); assertTrue(c.compare("shard10z", "shard10a") > 0); assertTrue(c.compare("shard1z", "shard1z") == 0); assertTrue(c.compare("shard2", "shard1") > 0); }
User extends BaseExpression { public Result apply(PathData item) throws IOException { if(requiredUser.equals(getFileStatus(item).getOwner())) { return Result.PASS; } return Result.FAIL; } User(); @Override void addArguments(Deque<String> args); @Override void initialise(FindOptions options); Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void applyBlank() throws IOException { when(fileStatus.getOwner()).thenReturn(""); assertEquals(Result.FAIL, user.apply(item)); } @Test public void applyNull() throws IOException { when(fileStatus.getOwner()).thenReturn(null); assertEquals(Result.FAIL, user.apply(item)); } @Test public void applyPass() throws IOException{ when(fileStatus.getOwner()).thenReturn("user"); assertEquals(Result.PASS, user.apply(item)); } @Test public void applyFail() throws IOException { when(fileStatus.getOwner()).thenReturn("notuser"); assertEquals(Result.FAIL, user.apply(item)); }
Size extends NumberExpression { @Override public Result apply(PathData item) throws IOException { return applyNumber(getFileStatus(item).getLen()); } Size(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void applyEqualsBlock() throws IOException { Size size = new Size(); addArgument(size, "5"); size.initialise(new FindOptions()); assertEquals(Result.PASS, size.apply(fiveBlocks)); assertEquals(Result.FAIL, size.apply(sixBlocks)); assertEquals(Result.FAIL, size.apply(fourBlocks)); assertEquals(Result.PASS, size.apply(fiveBlocksPlus)); assertEquals(Result.FAIL, size.apply(fiveBlocksMinus)); } @Test public void applyGreaterThanBlock() throws IOException { Size size = new Size(); addArgument(size, "+5"); size.initialise(new FindOptions()); assertEquals(Result.FAIL, size.apply(fiveBlocks)); assertEquals(Result.PASS, size.apply(sixBlocks)); assertEquals(Result.FAIL, size.apply(fourBlocks)); assertEquals(Result.FAIL, size.apply(fiveBlocksPlus)); assertEquals(Result.FAIL, size.apply(fiveBlocksMinus)); } @Test public void applyLessThanBlock() throws IOException { Size size = new Size(); addArgument(size, "-5"); size.initialise(new FindOptions()); assertEquals(Result.FAIL, size.apply(fiveBlocks)); assertEquals(Result.FAIL, size.apply(sixBlocks)); assertEquals(Result.PASS, size.apply(fourBlocks)); assertEquals(Result.FAIL, size.apply(fiveBlocksPlus)); assertEquals(Result.PASS, size.apply(fiveBlocksMinus)); } @Test public void applyEqualsBytes() throws IOException { Size size = new Size(); addArgument(size, (5 * 512) + "c"); size.initialise(new FindOptions()); assertEquals(Result.PASS, size.apply(fiveBlocks)); assertEquals(Result.FAIL, size.apply(sixBlocks)); assertEquals(Result.FAIL, size.apply(fourBlocks)); assertEquals(Result.FAIL, size.apply(fiveBlocksPlus)); assertEquals(Result.FAIL, size.apply(fiveBlocksMinus)); } @Test public void applyGreaterThanBytes() throws IOException { Size size = new Size(); addArgument(size, "+" + (5 * 512) + "c"); size.initialise(new FindOptions()); assertEquals(Result.FAIL, size.apply(fiveBlocks)); assertEquals(Result.PASS, size.apply(sixBlocks)); assertEquals(Result.FAIL, size.apply(fourBlocks)); assertEquals(Result.PASS, size.apply(fiveBlocksPlus)); assertEquals(Result.FAIL, size.apply(fiveBlocksMinus)); } @Test public void applyLessThanBytes() throws IOException { Size size = new Size(); addArgument(size, "-" + (5 * 512) + "c"); size.initialise(new FindOptions()); assertEquals(Result.FAIL, size.apply(fiveBlocks)); assertEquals(Result.FAIL, size.apply(sixBlocks)); assertEquals(Result.PASS, size.apply(fourBlocks)); assertEquals(Result.FAIL, size.apply(fiveBlocksPlus)); assertEquals(Result.PASS, size.apply(fiveBlocksMinus)); }
And extends BaseExpression { @Override public void addChildren(Deque<Expression> expressions) { addChildren(expressions, 2); } And(); @Override Result apply(PathData item); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); static void registerExpression(ExpressionFactory factory); }
@Test public void testInit() throws IOException { And and = new And(); Expression first = mock(Expression.class); Expression second = mock(Expression.class); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(children); FindOptions options = mock(FindOptions.class); and.initialise(options); verify(first).initialise(options); verify(second).initialise(options); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); }
FilterExpression implements Expression, Configurable { @Override public void initialise(FindOptions options) throws IOException { expression.initialise(options); } protected FilterExpression(Expression expression); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isAction(); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); @Override void addArguments(Deque<String> args); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override String toString(); }
@Test public void initialise() throws IOException { FindOptions options = mock(FindOptions.class); test.initialise(options); verify(expr).initialise(options); verifyNoMoreInteractions(expr); }
Depth extends BaseExpression { @Override public void initialise(FindOptions options) { options.setDepth(true); } Depth(); @Override Result apply(PathData item); @Override void initialise(FindOptions options); static void registerExpression(ExpressionFactory factory); }
@Test public void initialise() throws IOException{ FindOptions options = new FindOptions(); Depth depth = new Depth(); assertFalse(options.isDepth()); depth.initialise(options); assertTrue(options.isDepth()); }
FilterExpression implements Expression, Configurable { @Override public Result apply(PathData item) throws IOException { return expression.apply(item); } protected FilterExpression(Expression expression); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isAction(); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); @Override void addArguments(Deque<String> args); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override String toString(); }
@Test public void apply() throws IOException { PathData item = mock(PathData.class); when(expr.apply(item)).thenReturn(Result.PASS).thenReturn(Result.FAIL); assertEquals(Result.PASS, test.apply(item)); assertEquals(Result.FAIL, test.apply(item)); verify(expr, times(2)).apply(item); verifyNoMoreInteractions(expr); }
FilterExpression implements Expression, Configurable { @Override public void finish() throws IOException { expression.finish(); } protected FilterExpression(Expression expression); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isAction(); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); @Override void addArguments(Deque<String> args); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override String toString(); }
@Test public void finish() throws IOException { test.finish(); verify(expr).finish(); verifyNoMoreInteractions(expr); }
FilterExpression implements Expression, Configurable { @Override public String[] getUsage() { return expression.getUsage(); } protected FilterExpression(Expression expression); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isAction(); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); @Override void addArguments(Deque<String> args); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override String toString(); }
@Test public void getUsage() { String[] usage = new String[]{"Usage 1", "Usage 2", "Usage 3"}; when(expr.getUsage()).thenReturn(usage); assertArrayEquals(usage, test.getUsage()); verify(expr).getUsage(); verifyNoMoreInteractions(expr); }
FilterExpression implements Expression, Configurable { @Override public String[] getHelp() { return expression.getHelp(); } protected FilterExpression(Expression expression); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isAction(); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); @Override void addArguments(Deque<String> args); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override String toString(); }
@Test public void getHelp() { String[] help = new String[]{"Help 1", "Help 2", "Help 3"}; when(expr.getHelp()).thenReturn(help); assertArrayEquals(help, test.getHelp()); verify(expr).getHelp(); verifyNoMoreInteractions(expr); }
FilterExpression implements Expression, Configurable { @Override public boolean isAction() { return expression.isAction(); } protected FilterExpression(Expression expression); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isAction(); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); @Override void addArguments(Deque<String> args); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override String toString(); }
@Test public void isAction() { when(expr.isAction()).thenReturn(true).thenReturn(false); assertTrue(test.isAction()); assertFalse(test.isAction()); verify(expr, times(2)).isAction(); verifyNoMoreInteractions(expr); }
FilterExpression implements Expression, Configurable { @Override public boolean isOperator() { return expression.isOperator(); } protected FilterExpression(Expression expression); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isAction(); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); @Override void addArguments(Deque<String> args); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override String toString(); }
@Test public void isOperator() { when(expr.isAction()).thenReturn(true).thenReturn(false); assertTrue(test.isAction()); assertFalse(test.isAction()); verify(expr, times(2)).isAction(); verifyNoMoreInteractions(expr); }
FilterExpression implements Expression, Configurable { @Override public int getPrecedence() { return expression.getPrecedence(); } protected FilterExpression(Expression expression); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isAction(); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); @Override void addArguments(Deque<String> args); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override String toString(); }
@Test public void getPrecedence() { int precedence = 12345; when(expr.getPrecedence()).thenReturn(precedence); assertEquals(precedence, test.getPrecedence()); verify(expr).getPrecedence(); verifyNoMoreInteractions(expr); }
FilterExpression implements Expression, Configurable { @Override public void addChildren(Deque<Expression> expressions) { expression.addChildren(expressions); } protected FilterExpression(Expression expression); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isAction(); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); @Override void addArguments(Deque<String> args); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override String toString(); }
@Test public void addChildren() { @SuppressWarnings("unchecked") Deque<Expression> expressions = mock(Deque.class); test.addChildren(expressions); verify(expr).addChildren(expressions); verifyNoMoreInteractions(expr); }
FilterExpression implements Expression, Configurable { @Override public void addArguments(Deque<String> args) { expression.addArguments(args); } protected FilterExpression(Expression expression); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isAction(); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); @Override void addArguments(Deque<String> args); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override String toString(); }
@Test public void addArguments() { @SuppressWarnings("unchecked") Deque<String> args = mock(Deque.class); test.addArguments(args); verify(expr).addArguments(args); verifyNoMoreInteractions(expr); }
Not extends BaseExpression { @Override public void addChildren(Deque<Expression> expressions) { addChildren(expressions, 1); } Not(); @Override Result apply(PathData item); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); static void registerExpression(ExpressionFactory factory); }
@Test public void testInit() throws IOException { Not not = new Not(); Expression child = mock(Expression.class); Deque<Expression> children = new LinkedList<Expression>(); children.add(child); not.addChildren(children); FindOptions options = mock(FindOptions.class); not.initialise(options); verify(child).initialise(options); verifyNoMoreInteractions(child); }
Depth extends BaseExpression { @Override public Result apply(PathData item) { return Result.PASS; } Depth(); @Override Result apply(PathData item); @Override void initialise(FindOptions options); static void registerExpression(ExpressionFactory factory); }
@Test public void apply() throws IOException{ Depth depth = new Depth(); depth.initialise(new FindOptions()); assertEquals(Result.PASS, depth.apply(new PathData("anything", new Configuration()))); }
Or extends BaseExpression { @Override public void addChildren(Deque<Expression> expressions) { addChildren(expressions, 2); } Or(); @Override Result apply(PathData item); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); static void registerExpression(ExpressionFactory factory); }
@Test public void testInit() throws IOException { Or or = new Or(); Expression first = mock(Expression.class); Expression second = mock(Expression.class); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); or.addChildren(children); FindOptions options = mock(FindOptions.class); or.initialise(options); verify(first).initialise(options); verify(second).initialise(options); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); }
Atime extends NumberExpression { @Override public Result apply(PathData item) throws IOException { return applyNumber(getOptions().getStartTime() - getFileStatus(item).getAccessTime()); } Atime(); Atime(long units); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void testExact() throws IOException { Atime atime = new Atime(); addArgument(atime, "5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); atime.initialise(options); assertEquals(Result.FAIL, atime.apply(fourDays)); assertEquals(Result.FAIL, atime.apply(fiveDaysMinus)); assertEquals(Result.PASS, atime.apply(fiveDays)); assertEquals(Result.PASS, atime.apply(fiveDaysPlus)); assertEquals(Result.FAIL, atime.apply(sixDays)); } @Test public void testGreater() throws IOException { Atime atime = new Atime(); addArgument(atime, "+5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); atime.initialise(options); assertEquals(Result.FAIL, atime.apply(fourDays)); assertEquals(Result.FAIL, atime.apply(fiveDaysMinus)); assertEquals(Result.FAIL, atime.apply(fiveDays)); assertEquals(Result.FAIL, atime.apply(fiveDaysPlus)); assertEquals(Result.PASS, atime.apply(sixDays)); } @Test public void testLess() throws IOException { Atime atime = new Atime(); addArgument(atime, "-5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); atime.initialise(options); assertEquals(Result.PASS, atime.apply(fourDays)); assertEquals(Result.PASS, atime.apply(fiveDaysMinus)); assertEquals(Result.FAIL, atime.apply(fiveDays)); assertEquals(Result.FAIL, atime.apply(fiveDaysPlus)); assertEquals(Result.FAIL, atime.apply(sixDays)); }
Exec extends BaseExpression { @Override public void addArguments(Deque<String> args) { while(!args.isEmpty()) { String arg = args.pop(); if("+".equals(arg) && !getArguments().isEmpty() && "{}".equals(getArguments().get(getArguments().size() - 1))) { setBatch(true); break; } else if(";".equals(arg)) { break; } else { addArgument(arg); } } } Exec(); Exec(boolean prompt); @Override void addArguments(Deque<String> args); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override boolean isAction(); static void registerExpression(ExpressionFactory factory); }
@Test public void addArguments() throws IOException { Exec exec = new Exec(); exec.addArguments(getArgs("one two three ; four")); assertEquals("Exec(one,two,three;)", exec.toString()); assertFalse(exec.isBatch()); }
Empty extends BaseExpression { @Override public Result apply(PathData item) throws IOException { FileStatus fileStatus = getFileStatus(item); if(fileStatus.isDirectory()) { if(getFileSystem(item).listStatus(getPath(item)).length == 0) { return Result.PASS; } return Result.FAIL; } if(fileStatus.getLen() == 0l) { return Result.PASS; } return Result.FAIL; } Empty(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void applyEmptyFile() throws IOException { FileStatus fileStatus = mock(FileStatus.class); when(fileStatus.isDirectory()).thenReturn(false); when(fileStatus.getLen()).thenReturn(0l); fs.setFileStatus("emptyFile", fileStatus); PathData item = new PathData("emptyFile", fs.getConf()); Empty empty = new Empty(); empty.initialise(new FindOptions()); assertEquals(Result.PASS, empty.apply(item)); } @Test public void applyNotEmptyFile() throws IOException { FileStatus fileStatus = mock(FileStatus.class); when(fileStatus.isDirectory()).thenReturn(false); when(fileStatus.getLen()).thenReturn(1l); fs.setFileStatus("notEmptyFile", fileStatus); PathData item = new PathData("notEmptyFile", fs.getConf()); Empty empty = new Empty(); empty.initialise(new FindOptions()); assertEquals(Result.FAIL, empty.apply(item)); } @Test public void applyEmptyDirectory() throws IOException { FileStatus fileStatus = mock(FileStatus.class); when(fileStatus.isDirectory()).thenReturn(false); fs.setFileStatus("emptyDirectory", fileStatus); fs.setListStatus("emptyDirectory", new FileStatus[0]); PathData item = new PathData("emptyDirectory", fs.getConf()); Empty empty = new Empty(); empty.initialise(new FindOptions()); assertEquals(Result.PASS, empty.apply(item)); } @Test public void applyNotEmptyDirectory() throws IOException { FileStatus fileStatus = mock(FileStatus.class); when(fileStatus.isDirectory()).thenReturn(false); fs.setFileStatus("notEmptyDirectory", fileStatus); fs.setListStatus("notEmptyDirectory", new FileStatus[] {mock(FileStatus.class)}); PathData item = new PathData("notEmptyDirectory", fs.getConf()); Empty empty = new Empty(); empty.initialise(new FindOptions()); assertEquals(Result.PASS, empty.apply(item)); }
Print extends BaseExpression { public Print(boolean appendNull) { super(); setUsage(USAGE); setHelp(HELP); setAppendNull(appendNull); } Print(boolean appendNull); Print(); @Override Result apply(PathData item); @Override boolean isAction(); static void registerExpression(ExpressionFactory factory); }
@Test public void testPrint() throws IOException{ Print print = new Print(); PrintStream out = mock(PrintStream.class); FindOptions options = new FindOptions(); options.setOut(out); print.initialise(options); String filename = "/one/two/test"; PathData item = new PathData(filename, conf); assertEquals(Result.PASS, print.apply(item)); verify(out).println(filename); verifyNoMoreInteractions(out); }
Prune extends BaseExpression { @Override public Result apply(PathData item) throws IOException { if(getOptions().isDepth()) { return Result.PASS; } return Result.STOP; } Prune(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void apply() throws IOException { Prune prune = new Prune(); PathData item = mock(PathData.class); Result result = prune.apply(item); assertTrue(result.isPass()); assertFalse(result.isDescend()); } @Test public void applyDepth() throws IOException { Prune prune = new Prune(); FindOptions options = new FindOptions(); options.setDepth(true); prune.initialise(options); PathData item = mock(PathData.class); assertEquals(Result.PASS, prune.apply(item)); }
Nogroup extends BaseExpression { @Override public Result apply(PathData item) throws IOException { String group = getFileStatus(item).getGroup(); if((group == null) || (group.equals(""))) { return Result.PASS; } return Result.FAIL; } Nogroup(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void applyPass() throws IOException{ when(fileStatus.getGroup()).thenReturn("user"); assertEquals(Result.FAIL, nogroup.apply(item)); } @Test public void applyFail() throws IOException { when(fileStatus.getGroup()).thenReturn("notuser"); assertEquals(Result.FAIL, nogroup.apply(item)); } @Test public void applyBlank() throws IOException { when(fileStatus.getGroup()).thenReturn(""); assertEquals(Result.PASS, nogroup.apply(item)); } @Test public void applyNull() throws IOException { when(fileStatus.getGroup()).thenReturn(null); assertEquals(Result.PASS, nogroup.apply(item)); }
Nouser extends BaseExpression { @Override public Result apply(PathData item) throws IOException { String user = getFileStatus(item).getOwner(); if((user == null) || (user.equals(""))) { return Result.PASS; } return Result.FAIL; } Nouser(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void applyPass() throws IOException{ when(fileStatus.getOwner()).thenReturn("user"); assertEquals(Result.FAIL, nouser.apply(item)); } @Test public void applyFail() throws IOException { when(fileStatus.getOwner()).thenReturn("notuser"); assertEquals(Result.FAIL, nouser.apply(item)); } @Test public void applyBlank() throws IOException { when(fileStatus.getOwner()).thenReturn(""); assertEquals(Result.PASS, nouser.apply(item)); } @Test public void applyNull() throws IOException { when(fileStatus.getOwner()).thenReturn(null); assertEquals(Result.PASS, nouser.apply(item)); }
Blocksize extends NumberExpression { @Override public Result apply(PathData item) throws IOException { return applyNumber(getFileStatus(item).getBlockSize()); } Blocksize(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void applyEquals() throws IOException { Blocksize blocksize = new Blocksize(); addArgument(blocksize, "3"); blocksize.initialise(new FindOptions()); assertEquals(Result.FAIL, blocksize.apply(one)); assertEquals(Result.FAIL, blocksize.apply(two)); assertEquals(Result.PASS, blocksize.apply(three)); assertEquals(Result.FAIL, blocksize.apply(four)); assertEquals(Result.FAIL, blocksize.apply(five)); } @Test public void applyGreaterThan() throws IOException { Blocksize blocksize = new Blocksize(); addArgument(blocksize, "+3"); blocksize.initialise(new FindOptions()); assertEquals(Result.FAIL, blocksize.apply(one)); assertEquals(Result.FAIL, blocksize.apply(two)); assertEquals(Result.FAIL, blocksize.apply(three)); assertEquals(Result.PASS, blocksize.apply(four)); assertEquals(Result.PASS, blocksize.apply(five)); } @Test public void applyLessThan() throws IOException { Blocksize blocksize = new Blocksize(); addArgument(blocksize, "-3"); blocksize.initialise(new FindOptions()); assertEquals(Result.PASS, blocksize.apply(one)); assertEquals(Result.PASS, blocksize.apply(two)); assertEquals(Result.FAIL, blocksize.apply(three)); assertEquals(Result.FAIL, blocksize.apply(four)); assertEquals(Result.FAIL, blocksize.apply(five)); }
Result { public Result combine(Result other) { return new Result(this.isPass() && other.isPass(), this.isDescend() && other.isDescend()); } private Result(boolean success, boolean recurse); boolean isDescend(); boolean isPass(); Result combine(Result other); Result negate(); String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final Result PASS; static final Result FAIL; static final Result STOP; }
@Test public void equalsPass() { Result one = Result.PASS; Result two = Result.PASS.combine(Result.PASS); assertEquals(one, two); } @Test public void equalsFail() { Result one = Result.FAIL; Result two = Result.FAIL.combine(Result.FAIL); assertEquals(one, two); } @Test public void equalsStop() { Result one = Result.STOP; Result two = Result.STOP.combine(Result.STOP); assertEquals(one, two); }
Result { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Result other = (Result) obj; if (descend != other.descend) return false; if (success != other.success) return false; return true; } private Result(boolean success, boolean recurse); boolean isDescend(); boolean isPass(); Result combine(Result other); Result negate(); String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final Result PASS; static final Result FAIL; static final Result STOP; }
@Test public void notEquals() { assertFalse(Result.PASS.equals(Result.FAIL)); assertFalse(Result.PASS.equals(Result.STOP)); assertFalse(Result.FAIL.equals(Result.PASS)); assertFalse(Result.FAIL.equals(Result.STOP)); assertFalse(Result.STOP.equals(Result.PASS)); assertFalse(Result.STOP.equals(Result.FAIL)); }
Newer extends BaseExpression { @Override public Result apply(PathData item) throws IOException { if(getFileStatus(item).getModificationTime() > filetime) { return Result.PASS; } return Result.FAIL; } Newer(); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void addArguments(Deque<String> args); static void registerExpression(ExpressionFactory factory); }
@Test public void applyPass() throws IOException{ FileStatus fileStatus = mock(FileStatus.class); when(fileStatus.getModificationTime()).thenReturn(NOW - (4l*86400000)); fs.setFileStatus("newer.file", fileStatus); PathData item = new PathData("/directory/path/newer.file", fs.getConf()); assertEquals(Result.PASS, newer.apply(item)); } @Test public void applyFail() throws IOException{ FileStatus fileStatus = mock(FileStatus.class); when(fileStatus.getModificationTime()).thenReturn(NOW - (6l*86400000)); fs.setFileStatus("older.file", fileStatus); PathData item = new PathData("/directory/path/older.file", fs.getConf()); assertEquals(Result.FAIL, newer.apply(item)); }
Group extends BaseExpression { @Override public Result apply(PathData item) throws IOException { String group = getFileStatus(item).getGroup(); if(requiredGroup.equals(group)) { return Result.PASS; } return Result.FAIL; } Group(); @Override void addArguments(Deque<String> args); @Override void initialise(FindOptions options); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void applyPass() throws IOException{ when(fileStatus.getGroup()).thenReturn("group"); assertEquals(Result.PASS, group.apply(item)); } @Test public void applyFail() throws IOException { when(fileStatus.getGroup()).thenReturn("notgroup"); assertEquals(Result.FAIL, group.apply(item)); } @Test public void applyBlank() throws IOException { when(fileStatus.getGroup()).thenReturn(""); assertEquals(Result.FAIL, group.apply(item)); } @Test public void applyNull() throws IOException { when(fileStatus.getGroup()).thenReturn(null); assertEquals(Result.FAIL, group.apply(item)); }
Mtime extends NumberExpression { @Override public Result apply(PathData item) throws IOException { return applyNumber(getOptions().getStartTime() - getFileStatus(item).getModificationTime()); } Mtime(); Mtime(long units); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void testExact() throws IOException { Mtime mtime = new Mtime(); addArgument(mtime, "5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); mtime.initialise(options); assertEquals(Result.FAIL, mtime.apply(fourDays)); assertEquals(Result.FAIL, mtime.apply(fiveDaysMinus)); assertEquals(Result.PASS, mtime.apply(fiveDays)); assertEquals(Result.PASS, mtime.apply(fiveDaysPlus)); assertEquals(Result.FAIL, mtime.apply(sixDays)); } @Test public void testGreater() throws IOException { Mtime mtime = new Mtime(); addArgument(mtime, "+5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); mtime.initialise(options); assertEquals(Result.FAIL, mtime.apply(fourDays)); assertEquals(Result.FAIL, mtime.apply(fiveDaysMinus)); assertEquals(Result.FAIL, mtime.apply(fiveDays)); assertEquals(Result.FAIL, mtime.apply(fiveDaysPlus)); assertEquals(Result.PASS, mtime.apply(sixDays)); } @Test public void testLess() throws IOException { Mtime mtime = new Mtime(); addArgument(mtime, "-5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); mtime.initialise(options); assertEquals(Result.PASS, mtime.apply(fourDays)); assertEquals(Result.PASS, mtime.apply(fiveDaysMinus)); assertEquals(Result.FAIL, mtime.apply(fiveDays)); assertEquals(Result.FAIL, mtime.apply(fiveDaysPlus)); assertEquals(Result.FAIL, mtime.apply(sixDays)); }
Type extends BaseExpression { @Override public void initialise(FindOptions option) throws IOException { String arg = getArgument(1); if(FILE_TYPES.containsKey(arg)) { this.fileType = FILE_TYPES.get(arg); } else { throw new IOException("Invalid file type: " + arg); } } Type(); @Override void addArguments(Deque<String> args); @Override void initialise(FindOptions option); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); static final Map<String,FileType> FILE_TYPES; }
@Test public void testInvalidType() throws IOException { Type type = new Type(); addArgument(type, "a"); try { type.initialise(new FindOptions()); fail("Invalid file type not caught"); } catch (IOException e) {} }
Name extends BaseExpression { @Override public Result apply(PathData item) { String name = getPath(item).getName(); if(!caseSensitive) { name = name.toLowerCase(); } if(globPattern.matches(name)) { return Result.PASS; } else { return Result.FAIL; } } Name(); Name(boolean caseSensitive); @Override void addArguments(Deque<String> args); @Override void initialise(FindOptions options); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void applyPass() throws IOException{ PathData item = new PathData("/directory/path/name", conf); assertEquals(Result.PASS, name.apply(item)); } @Test public void applyFail() throws IOException{ PathData item = new PathData("/directory/path/notname", conf); assertEquals(Result.FAIL, name.apply(item)); } @Test public void applyMixedCase() throws IOException{ PathData item = new PathData("/directory/path/NaMe", conf); assertEquals(Result.FAIL, name.apply(item)); }
Replicas extends NumberExpression { @Override public Result apply(PathData item) throws IOException { return applyNumber(getFileStatus(item).getReplication()); } Replicas(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }
@Test public void applyEquals() throws IOException { Replicas rep = new Replicas(); addArgument(rep, "3"); rep.initialise(new FindOptions()); assertEquals(Result.FAIL, rep.apply(one)); assertEquals(Result.FAIL, rep.apply(two)); assertEquals(Result.PASS, rep.apply(three)); assertEquals(Result.FAIL, rep.apply(four)); assertEquals(Result.FAIL, rep.apply(five)); } @Test public void applyGreaterThan() throws IOException { Replicas rep = new Replicas(); addArgument(rep, "+3"); rep.initialise(new FindOptions()); assertEquals(Result.FAIL, rep.apply(one)); assertEquals(Result.FAIL, rep.apply(two)); assertEquals(Result.FAIL, rep.apply(three)); assertEquals(Result.PASS, rep.apply(four)); assertEquals(Result.PASS, rep.apply(five)); } @Test public void applyLessThan() throws IOException { Replicas rep = new Replicas(); addArgument(rep, "-3"); rep.initialise(new FindOptions()); assertEquals(Result.PASS, rep.apply(one)); assertEquals(Result.PASS, rep.apply(two)); assertEquals(Result.FAIL, rep.apply(three)); assertEquals(Result.FAIL, rep.apply(four)); assertEquals(Result.FAIL, rep.apply(five)); }
ClassExpression extends FilterExpression { @Override public void addArguments(Deque<String> args) { String classname = args.pop(); expression = ExpressionFactory.getExpressionFactory().createExpression(classname, getConf()); super.addArguments(args); } ClassExpression(); static void registerExpression(ExpressionFactory factory); @Override void addArguments(Deque<String> args); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isOperator(); }
@Test public void addArguments() throws IOException { test.addArguments(getArgs(TestExpression.class.getName() + " arg1 arg2 arg3")); verify(expr).addArguments(getArgs("arg1 arg2 arg3")); } @Test public void addChildren() throws IOException { @SuppressWarnings("unchecked") LinkedList<Expression> children = mock(LinkedList.class); test.addArguments(getArgs(TestExpression.class.getName())); test.addChildren(children); verify(expr).addArguments(new LinkedList<String>()); verify(expr).addChildren(children); verifyNoMoreInteractions(expr); verifyNoMoreInteractions(children); } @Test public void initialise() throws IOException { FindOptions options = new FindOptions(); test.addArguments(getArgs(TestExpression.class.getName())); test.initialise(options); verify(expr).addArguments(new LinkedList<String>()); verify(expr).initialise(options); verifyNoMoreInteractions(expr); } @Test public void applyPass() throws IOException { PathData item = mock(PathData.class); when(expr.apply(item)).thenReturn(Result.PASS); test.addArguments(getArgs(TestExpression.class.getName())); assertEquals(Result.PASS, test.apply(item)); verify(expr).addArguments(new LinkedList<String>()); verify(expr).apply(item); verifyNoMoreInteractions(expr); } @Test public void applyFail() throws IOException { PathData item = mock(PathData.class); when(expr.apply(item)).thenReturn(Result.FAIL); test.addArguments(getArgs(TestExpression.class.getName())); assertEquals(Result.FAIL, test.apply(item)); verify(expr).addArguments(new LinkedList<String>()); verify(expr).apply(item); verifyNoMoreInteractions(expr); } @Test public void applyStop() throws IOException { PathData item = mock(PathData.class); when(expr.apply(item)).thenReturn(Result.STOP); test.addArguments(getArgs(TestExpression.class.getName())); assertEquals(Result.STOP, test.apply(item)); verify(expr).addArguments(new LinkedList<String>()); verify(expr).apply(item); verifyNoMoreInteractions(expr); } @Test public void finish() throws IOException { test.addArguments(getArgs(TestExpression.class.getName())); test.finish(); verify(expr).addArguments(new LinkedList<String>()); verify(expr).finish(); verifyNoMoreInteractions(expr); } @Test public void isAction() throws IOException { when(expr.isAction()).thenReturn(true).thenReturn(false); test.addArguments(getArgs(TestExpression.class.getName())); assertTrue(test.isAction()); assertFalse(test.isAction()); verify(expr).addArguments(new LinkedList<String>()); verify(expr, times(2)).isAction(); verifyNoMoreInteractions(expr); } @Test public void getPrecedence() throws IOException { when(expr.getPrecedence()).thenReturn(12345).thenReturn(67890); test.addArguments(getArgs(TestExpression.class.getName())); assertEquals(12345, test.getPrecedence()); assertEquals(67890, test.getPrecedence()); verify(expr).addArguments(new LinkedList<String>()); verify(expr, times(2)).getPrecedence(); verifyNoMoreInteractions(expr); }
ClassExpression extends FilterExpression { @Override public boolean isOperator() { if(expression == null) { return false; } return expression.isOperator(); } ClassExpression(); static void registerExpression(ExpressionFactory factory); @Override void addArguments(Deque<String> args); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isOperator(); }
@Test public void isOperator() throws IOException { when(expr.isOperator()).thenReturn(true).thenReturn(false); test.addArguments(getArgs(TestExpression.class.getName())); assertTrue(test.isOperator()); assertFalse(test.isOperator()); verify(expr).addArguments(new LinkedList<String>()); verify(expr, times(2)).isOperator(); verifyNoMoreInteractions(expr); }
JGitAPIExceptions { public static RuntimeException exceptionWithFriendlyMessageFor(Exception e) { Throwable cause = getRootCause(e); String message = cause.getMessage(); if (message == null) { message = cause.getClass().getSimpleName(); } if (cause instanceof JSchException) { message = "SSH: " + message; } return new RuntimeException(message, cause); } static RuntimeException exceptionWithFriendlyMessageFor(Exception e); }
@Test public void testExceptionWithFriendlyMessageFor() throws Exception { RuntimeException re = exceptionWithFriendlyMessageFor(new NullPointerException()); assertThat(re.getMessage(), equalTo("NullPointerException")); }
FilePathMatcher implements Predicate<FilePath> { public int[] match(CharSequence filePath) { Matcher matcher = pattern.matcher(filePath); if (matcher.find()) { for (int i = 0; i < matchingLetters.length; ++i) { matchingLetters[i] = matcher.start(i + 1); } return matchingLetters; } else { return null; } } FilePathMatcher(String constraint); @Override boolean apply(FilePath filePath); int[] match(CharSequence filePath); double score(FilePath fp); }
@Test public void shouldMatchEndOfCandidateString() { assertThat(match("xml", "pom.xml"), is(true)); } @Test public void shouldNotMatchDifferingEndOfCandidateString() { assertThat(match("xml", "pom.xmo"), is(false)); } @Test public void shouldMatch() { assertThat(match("attrib", "Documentation/.gitattributes"), is(true)); assertThat(match("att", "Documentation/.gitattributes"), is(true)); assertThat(match("docgit", "Documentation/.gitattributes"), is(true)); assertThat(match("agitt", "agitb"), is(false)); }
RDTTag extends RepoDomainType<TagSummary> { public List<TagSummary> getAll() { final RevWalk revWalk = new RevWalk(repository); List<TagSummary> tagSummaries = newArrayList(transform(repository.getTags().values(), new TagSummaryFactory(revWalk))); sort(tagSummaries, SORT_BY_TIME_AND_NAME); return tagSummaries; } @Inject RDTTag(Repository repository); @Override String name(); List<TagSummary> getAll(); @Override String idFor(TagSummary tagSummary); @Override CharSequence conciseSummaryTitle(); @Override CharSequence shortDescriptionOf(TagSummary tagSummary); }
@Test public void shouldHandleTheDatelessAnnotatedTagsThatGitUsedToHave() throws Exception { Repository repository = helper().unpackRepo("git-repo-has-dateless-tag.depth2.zip"); RDTTag rdtTag = new RDTTag(repository); List<TagSummary> listOfTagsInRepo = rdtTag.getAll(); assertThat(listOfTagsInRepo.size(), is(1)); TagSummary tagSummary = listOfTagsInRepo.get(0); assertThat(tagSummary.getTime(), equalTo(1121037394L)); } @Test public void shouldHaveTaggedObjectFieldCorrectlySetForAnAnnotatedTag() throws Exception { RDTTag rdtTag = new RDTTag(helper().unpackRepo("small-repo.with-tags.zip")); List<TagSummary> tags = rdtTag.getAll(); TagSummary tag = find(tags, tagNamed("annotated-tag-of-2nd-commit")); assertThat(tag.getTaggedObject(), instanceOf(RevCommit.class)); }
GitHubWebLaunchActivity extends WebLaunchActivity { Intent cloneLauncherForWebBrowseIntent(Uri uri) { Matcher matcher = projectPathPattern.matcher(uri.getPath()); matcher.find(); return cloneLauncherIntentFor("git: } }
@Test public void shouldSupplyCloneSourceForRegularGithubProjectPage() { Intent cloneIntent = activity.cloneLauncherForWebBrowseIntent(parse("https: assertThat(sourceUriFrom(cloneIntent), is("git: } @Test public void shouldSupplyOnlyUserepoOwnerAndNameForCloneUrl() { Intent cloneIntent = activity.cloneLauncherForWebBrowseIntent(parse("https: ".com/eddieringle/hubroid/issues/66")); assertThat(sourceUriFrom(cloneIntent), is("git: }
EmailCommandHandler { public void create(EmailCreateCommand command) throws Exception { EmailAggregate emailAggregate = getByUUID(command.getUuid()); emailAggregate = emailAggregate.create(command); List<AppEvent> pendingEvents = emailAggregate.getUncommittedChanges(); eventSourcingService.save(emailAggregate); pendingEvents.forEach(eventPublisher::publish); pendingEvents.forEach(eventPublisher::stream); } EmailCommandHandler( EventSourcingService eventSourcingService, EventPublisher eventPublisher ); void create(EmailCreateCommand command); void send(EmailSendCommand command); void delivery(EmailDeliveryCommand command); void delete(EmailDeleteCommand command); EmailAggregate getByUUID(String uuid); }
@Test public void create() throws Exception { String uuid = UUID.randomUUID().toString(); EmailCreateCommand command = new EmailCreateCommand( uuid, new Email("Alexsandro", "[email protected]", EmailState.CREATED) ); commandHandler.create(command); verify(eventPublisher, Mockito.times(1)).publish(Mockito.anyObject()); verify(eventPublisher, Mockito.times(1)).stream(Mockito.anyObject()); }
EmailCommandHandler { public void send(EmailSendCommand command) throws Exception { EmailAggregate emailAggregate = getByUUID(command.getUuid()); emailAggregate = emailAggregate.send(command); List<AppEvent> pendingEvents = emailAggregate.getUncommittedChanges(); pendingEvents.forEach(eventPublisher::stream); eventSourcingService.save(emailAggregate); } EmailCommandHandler( EventSourcingService eventSourcingService, EventPublisher eventPublisher ); void create(EmailCreateCommand command); void send(EmailSendCommand command); void delivery(EmailDeliveryCommand command); void delete(EmailDeleteCommand command); EmailAggregate getByUUID(String uuid); }
@Test public void send() throws Exception { String uuid = UUID.randomUUID().toString(); EmailSendCommand command = new EmailSendCommand(uuid, Instant.now()); commandHandler.send(command); verify(eventSourcingService, Mockito.times(1)).save(Mockito.any(Aggregate.class)); verify(eventPublisher, Mockito.times(1)).stream(Mockito.anyObject()); }
EmailCommandHandler { public EmailAggregate getByUUID(String uuid) { return EmailAggregate.from(uuid, eventSourcingService.getRelatedEvents(uuid)); } EmailCommandHandler( EventSourcingService eventSourcingService, EventPublisher eventPublisher ); void create(EmailCreateCommand command); void send(EmailSendCommand command); void delivery(EmailDeliveryCommand command); void delete(EmailDeleteCommand command); EmailAggregate getByUUID(String uuid); }
@Test public void getByUUID() { String uuid = "123"; Mockito.when(eventSourcingService.getAggregate(Mockito.anyString())) .thenReturn(new EventStream()); EmailAggregate byUUID = commandHandler.getByUUID(uuid); Assert.assertTrue(byUUID.getState().getEmail() == null); }
EmailAggregate extends AbstractAggregate implements Aggregate { public EmailAggregate create(EmailCreateCommand command) throws Exception { if (state.getState() != null) { throw new Exception("Is not possible to edit a deleted email"); } return applyChange(new EmailCreatedEvent(uuid, command.getEmail())); } EmailAggregate(String uuid, List<AppEvent> changes); EmailAggregate(String uuid, List<AppEvent> changes, Email state); EmailAggregate create(EmailCreateCommand command); EmailAggregate send(EmailSendCommand command); EmailAggregate delivery(EmailDeliveryCommand command); EmailAggregate delete(EmailDeleteCommand command); static EmailAggregate from(String uuid, List<AppEvent> history); @Override EmailAggregate markChangesAsCommitted(); Email getState(); }
@Test public void testCreate() throws Exception { final Email email = new Email("alex", "[email protected]", EmailState.CREATED); String uuid = UUID.randomUUID().toString(); EmailAggregate result = getAggregateWithStateCreated(email,uuid); assertEquals(email.getEmail(), result.getState().getEmail()); assertEquals(email.getName(), result.getState().getName()); AppEvent event = result.getUncommittedChanges().get(0); assertEquals(uuid, result.getUuid()); assertEquals(uuid, event.uuid()); assertEquals(EmailState.CREATED, result.getState().getState()); }
EmailAggregate extends AbstractAggregate implements Aggregate { public EmailAggregate send(EmailSendCommand command) throws Exception { if (state.getState() == EmailState.DELETED) { throw new Exception("Is not possible to edit a deleted email"); } return applyChange(new EmailSentEvent( command.getUuid(), getState().setState(EmailState.SENT))); } EmailAggregate(String uuid, List<AppEvent> changes); EmailAggregate(String uuid, List<AppEvent> changes, Email state); EmailAggregate create(EmailCreateCommand command); EmailAggregate send(EmailSendCommand command); EmailAggregate delivery(EmailDeliveryCommand command); EmailAggregate delete(EmailDeleteCommand command); static EmailAggregate from(String uuid, List<AppEvent> history); @Override EmailAggregate markChangesAsCommitted(); Email getState(); }
@Test public void testSend() throws Exception { final Email email = new Email("alex", "[email protected]", EmailState.CREATED); String uuid = UUID.randomUUID().toString(); EmailAggregate aggregateWithStateCreated = getAggregateWithStateCreated(email, uuid); EmailSendCommand command = new EmailSendCommand(uuid, Instant.MIN); EmailAggregate result = aggregateWithStateCreated.send(command); assertEquals(EmailState.SENT, result.getState().getState()); }
EmailAggregate extends AbstractAggregate implements Aggregate { @Override public EmailAggregate markChangesAsCommitted() { return new EmailAggregate(uuid, new CopyOnWriteArrayList(), state); } EmailAggregate(String uuid, List<AppEvent> changes); EmailAggregate(String uuid, List<AppEvent> changes, Email state); EmailAggregate create(EmailCreateCommand command); EmailAggregate send(EmailSendCommand command); EmailAggregate delivery(EmailDeliveryCommand command); EmailAggregate delete(EmailDeleteCommand command); static EmailAggregate from(String uuid, List<AppEvent> history); @Override EmailAggregate markChangesAsCommitted(); Email getState(); }
@Test public void testMarkChangesAsCommitted() throws Exception { final Email email = new Email("alex", "[email protected]", EmailState.CREATED); String uuid = UUID.randomUUID().toString(); EmailAggregate instance = getAggregateWithStateCreated(email,uuid); EmailAggregate result = instance.markChangesAsCommitted(); assertFalse(instance.getUncommittedChanges().isEmpty()); assertTrue(result.getUncommittedChanges().isEmpty()); }
EmailAggregate extends AbstractAggregate implements Aggregate { public EmailAggregate delete(EmailDeleteCommand command) throws Exception { if (state.getState() == EmailState.DELETED) { throw new Exception("Is not possible to delete a deleted email"); } return applyChange(new EmailDeletedEvent(uuid, getState().setState(EmailState.DELETED) )); } EmailAggregate(String uuid, List<AppEvent> changes); EmailAggregate(String uuid, List<AppEvent> changes, Email state); EmailAggregate create(EmailCreateCommand command); EmailAggregate send(EmailSendCommand command); EmailAggregate delivery(EmailDeliveryCommand command); EmailAggregate delete(EmailDeleteCommand command); static EmailAggregate from(String uuid, List<AppEvent> history); @Override EmailAggregate markChangesAsCommitted(); Email getState(); }
@Test public void testDelete() throws Exception { final Email email = new Email("alex", "[email protected]", EmailState.CREATED); String uuid = UUID.randomUUID().toString(); EmailAggregate aggregateWithStateCreated = getAggregateWithStateCreated(email, uuid); EmailDeleteCommand command = new EmailDeleteCommand(uuid); EmailAggregate result = aggregateWithStateCreated.delete(command); assertEquals(EmailState.DELETED, result.getState().getState()); }
SnorocketReasoner implements IReasoner, Serializable { @Override public IReasoner classify() { if(!isClassified) { no.classify(); isClassified = true; } else { no.classifyIncremental(); } return this; } SnorocketReasoner(); static SnorocketReasoner load(InputStream in); @Override void prune(); @Override Ontology getClassifiedOntology(); @Override Ontology getClassifiedOntology(Ontology ont); Collection<Axiom> getInferredAxioms(); @Override void save(OutputStream out); @Override boolean isClassified(); @Override void loadAxioms(Set<Axiom> axioms); @Override void loadAxioms(Iterator<Axiom> axioms); @Override void loadAxioms(Ontology ont); @Override IReasoner classify(); void setNumThreads(int numThreads); static final int BUFFER_SIZE; }
@Test public void testBottom() { IFactory factory = new CoreFactory(); NamedConcept a = new NamedConcept("A"); NamedConcept b = new NamedConcept("B"); ConceptInclusion a1 = new ConceptInclusion(a, NamedConcept.BOTTOM_CONCEPT); ConceptInclusion a2 = new ConceptInclusion(b, NamedConcept.TOP_CONCEPT); Set<Axiom> axioms = new HashSet<Axiom>(); axioms.add(a1); axioms.add(a2); NormalisedOntology o = new NormalisedOntology(factory, axioms); o.classify(); o.buildTaxonomy(); Node bNode = o.getEquivalents(b.getId()); Set<Node> bParents = bNode.getParents(); assertTrue(bParents.size() == 1); assertTrue(bParents.contains(o.getTopNode())); Node bottomNode = o.getBottomNode(); assertTrue(bottomNode.getEquivalentConcepts().size() == 2); bottomNode.getEquivalentConcepts().contains(a.getId()); Set<Node> bottomParents = bottomNode.getParents(); assertTrue(bottomParents.size() == 1); assertTrue(bottomParents.contains(o.getEquivalents(b.getId()))); } @Test public void testBottom2() { IFactory factory = new CoreFactory(); NamedConcept a = new NamedConcept("A"); NamedConcept b = new NamedConcept("B"); ConceptInclusion a1 = new ConceptInclusion(a, b); ConceptInclusion a2 = new ConceptInclusion(a, NamedConcept.BOTTOM_CONCEPT); Set<Axiom> axioms = new HashSet<Axiom>(); axioms.add(a1); axioms.add(a2); NormalisedOntology o = new NormalisedOntology(factory, axioms); o.classify(); o.buildTaxonomy(); Node bNode = o.getEquivalents(b.getId()); Set<Node> bParents = bNode.getParents(); assertTrue(bParents.size() == 1); assertTrue(bParents.contains(o.getTopNode())); Node bottomNode = o.getBottomNode(); assertTrue(bottomNode.getEquivalentConcepts().size() == 2); bottomNode.getEquivalentConcepts().contains(a.getId()); Set<Node> bottomParents = bottomNode.getParents(); assertTrue(bottomParents.size() == 1); assertTrue(bottomParents.contains(o.getEquivalents(b.getId()))); }
NormalisedOntology implements Serializable { public Set<Inclusion> normalise(final Set<? extends Axiom> inclusions) { Set<Inclusion> newIs = transformAxiom(inclusions); Set<Inclusion> oldIs = new HashSet<Inclusion>(newIs.size()); final Set<Inclusion> done = new HashSet<Inclusion>(newIs.size()); do { final Set<Inclusion> tmp = oldIs; oldIs = newIs; newIs = tmp; newIs.clear(); for (Inclusion i : oldIs) { Inclusion[] s = i.normalise1(factory); if (null != s) { for (int j = 0; j < s.length; j++) { if (null != s[j]) { newIs.add(s[j]); } } } else { done.add(i); } } } while (!newIs.isEmpty()); newIs.addAll(done); done.clear(); do { final Set<Inclusion> tmp = oldIs; oldIs = newIs; newIs = tmp; newIs.clear(); for (Inclusion i : oldIs) { Inclusion[] s = i.normalise2(factory); if (null != s) { for (int j = 0; j < s.length; j++) { if (null != s[j]) { newIs.add(s[j]); } } } else { done.add(i); } } } while (!newIs.isEmpty()); if(log.isTraceEnabled()) { log.trace("Normalised axioms:"); for(Inclusion inc : done) { StringBuilder sb = new StringBuilder(); if(inc instanceof GCI) { GCI gci = (GCI)inc; sb.append(printInternalObject(gci.lhs())); sb.append(" [ "); sb.append(printInternalObject(gci.rhs())); } else if(inc instanceof RI) { RI ri = (RI)inc; int[] lhs = ri.getLhs(); sb.append(factory.lookupRoleId(lhs[0])); for(int i = 1; i < lhs.length; i++) { sb.append(" * "); sb.append(factory.lookupRoleId(lhs[i])); } sb.append(" [ "); sb.append(factory.lookupRoleId(ri.getRhs())); } log.trace(sb.toString()); } } return done; } NormalisedOntology(final IFactory factory, final Set<? extends Axiom> inclusions); NormalisedOntology(final IFactory factory); protected NormalisedOntology( final IFactory factory, final IConceptMap<MonotonicCollection<IConjunctionQueueEntry>> nf1q, final IConceptMap<MonotonicCollection<NF2>> nf2q, final IConceptMap<ConcurrentMap<Integer, Collection<IConjunctionQueueEntry>>> nf3q, final IMonotonicCollection<NF4> nf4q, final IMonotonicCollection<NF5> nf5q, final IConceptMap<MonotonicCollection<NF7>> nf7q, final FeatureMap<MonotonicCollection<NF8>> nf8q); IConceptMap<MonotonicCollection<IConjunctionQueueEntry>> getOntologyNF1(); IConceptMap<MonotonicCollection<NF2>> getOntologyNF2(); IConceptMap<ConcurrentMap<Integer, Collection<IConjunctionQueueEntry>>> getOntologyNF3(); IMonotonicCollection<NF4> getOntologyNF4(); IMonotonicCollection<NF5> getOntologyNF5(); IConceptSet getReflexiveRoles(); IConceptMap<MonotonicCollection<NF7>> getOntologyNF7(); FeatureMap<MonotonicCollection<NF8>> getOntologyNF8(); IConceptSet getFunctionalFeatures(); Queue<Context> getTodo(); IConceptMap<Context> getContextIndex(); Map<Integer, RoleSet> getRoleClosureCache(); Set<Context> getAffectedContexts(); void loadAxioms(final Set<? extends Axiom> inclusions); void prapareForInferred(); Collection<NF1b> getNF1bs(); Set<Inclusion> normalise(final Set<? extends Axiom> inclusions); void loadIncremental(Set<Axiom> incAxioms); void classifyIncremental(); void classify(); IConceptMap<IConceptSet> getSubsumptions(); IConceptMap<IConceptSet> getNewSubsumptions(); IConceptMap<IConceptSet> getAffectedSubsumptions(); R getRelationships(); void printStats(); IFactory getFactory(); Set<Axiom> getStatedAxioms(); Concept transform(Object o); void setNumThreads(int numThreads); void getFullTaxonomy(IConceptMap<IConceptSet> equiv, IConceptMap<IConceptSet> direc); void buildTaxonomy(); Map<String, Node> getTaxonomy(); Set<Node> getAffectedNodes(); boolean isTaxonomyComputed(); Node getBottomNode(); Node getTopNode(); Node getEquivalents(String cid); }
@Test public void testNormalise() { IFactory factory = new CoreFactory(); NamedRole container = new NamedRole("container"); NamedRole contains = new NamedRole("contains"); NamedFeature mgPerTablet = new NamedFeature("mgPerTablet"); NamedConcept panadol = new NamedConcept("Panadol"); NamedConcept panadol_250mg = new NamedConcept("Panadol_250mg"); NamedConcept panadol_500mg = new NamedConcept("Panadol_500mg"); NamedConcept panadol_pack_250mg = new NamedConcept("Panadol_pack_250mg"); NamedConcept paracetamol = new NamedConcept("Paracetamol"); NamedConcept bottle = new NamedConcept("Bottle"); ConceptInclusion a1 = new ConceptInclusion(panadol, new Existential(contains, paracetamol)); ConceptInclusion a2 = new ConceptInclusion(panadol_250mg, new Conjunction(new Concept[] { panadol, new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(250)) })); ConceptInclusion a3 = new ConceptInclusion(new Conjunction( new Concept[] { panadol, new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(250)) }), panadol_250mg); ConceptInclusion a4 = new ConceptInclusion(panadol_500mg, new Conjunction(new Concept[] { panadol, new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(500)) })); ConceptInclusion a5 = new ConceptInclusion(new Conjunction( new Concept[] { panadol, new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(500)) }), panadol_500mg); ConceptInclusion a6 = new ConceptInclusion(panadol_pack_250mg, new Conjunction(new Concept[] { panadol, new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(250)), new Existential(container, bottle) })); Set<Axiom> axioms = new HashSet<Axiom>(); axioms.add(a1); axioms.add(a2); axioms.add(a3); axioms.add(a4); axioms.add(a5); axioms.add(a6); NormalisedOntology no = new NormalisedOntology(factory); Set<Inclusion> norms = no.normalise(axioms); for (Inclusion norm : norms) { System.out.println(norm.getNormalForm().toString()); } assertEquals(12, norms.size()); }
Tables { public static String getSQL(Object[] sqlData, Version currentVersion) { try { for (int c = 0; c < sqlData.length; c += 2) { Version curSqlVersion = (Version) sqlData[c]; String curSql = (String) sqlData[c + 1]; if (currentVersion.isMinimum(curSqlVersion)) return curSql; } } catch (Exception e) { throw new IllegalStateException("Misconfigured system table type "); } throw new UnsupportedServerVersion(currentVersion); } static String getSQL(Object[] sqlData, Version currentVersion); static List<R> convertRows(Context context, T table, ResultBatch results); }
@Test public void testGetSQL() { assertEquals(Tables.getSQL(SQL, Version.parse("9.0.0")), SQL[3]); assertNotEquals(Tables.getSQL(SQL, Version.parse("9.0.0")), SQL[1]); assertEquals(Tables.getSQL(SQL, Version.parse("9.4.5")), SQL[1]); } @Test public void testIllegalStateException() { try { String sql = Tables.getSQL(SQLBad, Version.parse("9.0.0")); fail("Didn't hit IllegalStateException, usually from bad sqlData"); } catch (IllegalStateException e) { } } @Test public void testUnsupportedServerVersion() { thrown.expect(UnsupportedServerVersion.class); assertEquals(Tables.getSQL(SQL, Version.parse("8.3.0")), SQL[1]); }
PGTypeTable implements Table<PGTypeTable.Row> { @Override public String getSQL(Version currentVersion) { return Tables.getSQL(SQL, currentVersion); } private PGTypeTable(); @Override String getSQL(Version currentVersion); @Override Row createRow(Context context, ResultBatch resultBatch, int rowIdx); static final PGTypeTable INSTANCE; static final Object[] SQL; }
@Test public void testGetSQLVersionEqual() { assertEquals(INSTANCE.getSQL(Version.parse("9.2.0")), SQL[1]); assertNotEquals(INSTANCE.getSQL(Version.parse("9.1.0")), INSTANCE.getSQL(Version.parse("9.2.0"))); } @Test public void testGetSQLVersionGreater() { assertEquals(INSTANCE.getSQL(Version.parse("9.4.5")), SQL[1]); } @Test public void testGetSQLVersionLess() { assertEquals(INSTANCE.getSQL(Version.parse("9.1.9")), SQL[3]); } @Test public void testGetSQLVersionInvalid() { thrown.expect(UnsupportedServerVersion.class); assertEquals(INSTANCE.getSQL(Version.parse("8.0.0")), SQL[1]); }
PGTypeTable implements Table<PGTypeTable.Row> { @Override public Row createRow(Context context, ResultBatch resultBatch, int rowIdx) throws IOException { Row row = new Row(); row.load(context, resultBatch, rowIdx); return row; } private PGTypeTable(); @Override String getSQL(Version currentVersion); @Override Row createRow(Context context, ResultBatch resultBatch, int rowIdx); static final PGTypeTable INSTANCE; static final Object[] SQL; }
@Test public void testHashCode() { PGTypeTable.Row pgAttrOne = createRow(12345); PGTypeTable.Row pgAttrOneAgain = createRow(12345); PGTypeTable.Row pgAttrTwo = createRow(54321); assertEquals(pgAttrOne.hashCode(), pgAttrOne.hashCode()); assertEquals(pgAttrOne.hashCode(), pgAttrOneAgain.hashCode()); assertNotEquals(pgAttrOne.hashCode(), pgAttrTwo.hashCode()); } @Test public void testEquals() { PGTypeTable.Row pgAttrOne = createRow(12345); PGTypeTable.Row pgAttrOneAgain = createRow(12345); PGTypeTable.Row pgAttrTwo = createRow(54321); assertEquals(pgAttrOne, pgAttrOne); assertNotEquals(null, pgAttrOne); assertNotEquals("testStringNotSameClass", pgAttrOne); assertNotEquals(pgAttrOne, pgAttrTwo); assertEquals(pgAttrOne, pgAttrOneAgain); }
SearchHistoryEntity implements SearchHistory { @Override @NonNull public String getPlaceId() { return placeId; } SearchHistoryEntity(@NonNull String placeId, CarmenFeature carmenFeature); @Override @NonNull String getPlaceId(); @Override CarmenFeature getCarmenFeature(); }
@Test public void getPlaceId_doesReturnTheSetPlaceId() throws Exception { CarmenFeature feature = CarmenFeature.builder() .properties(new JsonObject()) .build(); SearchHistoryEntity entity = new SearchHistoryEntity("placeId", feature); assertThat(entity.getPlaceId(), equalTo("placeId")); }
LineManager extends AnnotationManager<LineLayer, Line, LineOptions, OnLineDragListener, OnLineClickListener, OnLineLongClickListener> { @UiThread public List<Line> create(@NonNull String json) { return create(FeatureCollection.fromJson(json)); } @UiThread LineManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style); @UiThread LineManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId); @UiThread LineManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions); @VisibleForTesting LineManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @NonNull CoreElementProvider<LineLayer> coreElementProvider, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions, DraggableAnnotationController draggableAnnotationController); @UiThread List<Line> create(@NonNull String json); @UiThread List<Line> create(@NonNull FeatureCollection featureCollection); String getLineCap(); void setLineCap(@Property.LINE_CAP String value); Float getLineMiterLimit(); void setLineMiterLimit( Float value); Float getLineRoundLimit(); void setLineRoundLimit( Float value); Float[] getLineTranslate(); void setLineTranslate( Float[] value); String getLineTranslateAnchor(); void setLineTranslateAnchor(@Property.LINE_TRANSLATE_ANCHOR String value); Float[] getLineDasharray(); void setLineDasharray( Float[] value); @Override void setFilter(@NonNull Expression expression); @Nullable Expression getFilter(); }
@Test public void testGeometryLine() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs); Line line = lineManager.create(options); assertEquals(options.getLatLngs(), latLngs); assertEquals(line.getLatLngs(), latLngs); assertEquals(options.getGeometry(), LineString.fromLngLats(new ArrayList<Point>() {{ add(Point.fromLngLat(0, 0)); add(Point.fromLngLat(1, 1)); }})); assertEquals(line.getGeometry(), LineString.fromLngLats(new ArrayList<Point>() {{ add(Point.fromLngLat(0, 0)); add(Point.fromLngLat(1, 1)); }})); } @Test public void testFeatureIdLine() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); Line lineZero = lineManager.create(new LineOptions().withLatLngs(latLngs)); Line lineOne = lineManager.create(new LineOptions().withLatLngs(latLngs)); assertEquals(lineZero.getFeature().get(Line.ID_KEY).getAsLong(), 0); assertEquals(lineOne.getFeature().get(Line.ID_KEY).getAsLong(), 1); } @Test public void testLineDraggableFlag() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); Line lineZero = lineManager.create(new LineOptions().withLatLngs(latLngs)); assertFalse(lineZero.isDraggable()); lineZero.setDraggable(true); assertTrue(lineZero.isDraggable()); lineZero.setDraggable(false); assertFalse(lineZero.isDraggable()); } @Test public void testLineJoinLayerProperty() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(lineLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(lineJoin(get("line-join"))))); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs).withLineJoin(LINE_JOIN_BEVEL); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineJoin(get("line-join"))))); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineJoin(get("line-join"))))); } @Test public void testLineOpacityLayerProperty() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(lineLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(lineOpacity(get("line-opacity"))))); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs).withLineOpacity(2.0f); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineOpacity(get("line-opacity"))))); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineOpacity(get("line-opacity"))))); } @Test public void testLineColorLayerProperty() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(lineLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(lineColor(get("line-color"))))); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs).withLineColor("rgba(0, 0, 0, 1)"); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineColor(get("line-color"))))); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineColor(get("line-color"))))); } @Test public void testLineWidthLayerProperty() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(lineLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(lineWidth(get("line-width"))))); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs).withLineWidth(2.0f); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineWidth(get("line-width"))))); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineWidth(get("line-width"))))); } @Test public void testLineGapWidthLayerProperty() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(lineLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(lineGapWidth(get("line-gap-width"))))); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs).withLineGapWidth(2.0f); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineGapWidth(get("line-gap-width"))))); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineGapWidth(get("line-gap-width"))))); } @Test public void testLineOffsetLayerProperty() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(lineLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(lineOffset(get("line-offset"))))); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs).withLineOffset(2.0f); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineOffset(get("line-offset"))))); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineOffset(get("line-offset"))))); } @Test public void testLineBlurLayerProperty() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(lineLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(lineBlur(get("line-blur"))))); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs).withLineBlur(2.0f); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineBlur(get("line-blur"))))); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(lineBlur(get("line-blur"))))); } @Test public void testLinePatternLayerProperty() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(lineLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(linePattern(get("line-pattern"))))); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs).withLinePattern("pedestrian-polygon"); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(linePattern(get("line-pattern"))))); lineManager.create(options); verify(lineLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(linePattern(get("line-pattern"))))); } @Test public void testCustomData() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs); options.withData(new JsonPrimitive("hello")); Line line = lineManager.create(options); assertEquals(new JsonPrimitive("hello"), line.getData()); } @Test public void testClearAll() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs); lineManager.create(options); assertEquals(1, lineManager.getAnnotations().size()); lineManager.deleteAll(); assertEquals(0, lineManager.getAnnotations().size()); } @Test public void testIgnoreClearedAnnotations() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); LineOptions options = new LineOptions().withLatLngs(latLngs); Line line = lineManager.create(options); assertEquals(1, lineManager.annotations.size()); lineManager.getAnnotations().clear(); lineManager.updateSource(); assertTrue(lineManager.getAnnotations().isEmpty()); lineManager.update(line); assertTrue(lineManager.getAnnotations().isEmpty()); } @Test public void testAddLine() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); Line line = lineManager.create(new LineOptions().withLatLngs(latLngs)); assertEquals(lineManager.getAnnotations().get(0), line); } @Test public void addLineFromFeatureCollection() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<Point> points = new ArrayList<>(); points.add(Point.fromLngLat(0, 0)); points.add(Point.fromLngLat(1, 1)); Geometry geometry = LineString.fromLngLats(points); Feature feature = Feature.fromGeometry(geometry); feature.addStringProperty("line-join", LINE_JOIN_BEVEL); feature.addNumberProperty("line-opacity", 2.0f); feature.addStringProperty("line-color", "rgba(0, 0, 0, 1)"); feature.addNumberProperty("line-width", 2.0f); feature.addNumberProperty("line-gap-width", 2.0f); feature.addNumberProperty("line-offset", 2.0f); feature.addNumberProperty("line-blur", 2.0f); feature.addStringProperty("line-pattern", "pedestrian-polygon"); feature.addBooleanProperty("is-draggable", true); List<Line> lines = lineManager.create(FeatureCollection.fromFeature(feature)); Line line = lines.get(0); assertEquals(line.geometry, geometry); assertEquals(line.getLineJoin(), LINE_JOIN_BEVEL); assertEquals(line.getLineOpacity(), 2.0f); assertEquals(line.getLineColor(), "rgba(0, 0, 0, 1)"); assertEquals(line.getLineWidth(), 2.0f); assertEquals(line.getLineGapWidth(), 2.0f); assertEquals(line.getLineOffset(), 2.0f); assertEquals(line.getLineBlur(), 2.0f); assertEquals(line.getLinePattern(), "pedestrian-polygon"); assertTrue(line.isDraggable()); } @Test public void addLines() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<List<LatLng>> latLngList = new ArrayList<>(); latLngList.add(new ArrayList<LatLng>() {{ add(new LatLng(2, 2)); add(new LatLng(2, 3)); }}); latLngList.add(new ArrayList<LatLng>() {{ add(new LatLng(1, 1)); add(new LatLng(2, 3)); }}); List<LineOptions> options = new ArrayList<>(); for (List<LatLng> latLngs : latLngList) { options.add(new LineOptions().withLatLngs(latLngs)); } List<Line> lines = lineManager.create(options); assertTrue("Returned value size should match", lines.size() == 2); assertTrue("Annotations size should match", lineManager.getAnnotations().size() == 2); } @Test public void testDeleteLine() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>latLngs = new ArrayList<>(); latLngs.add(new LatLng()); latLngs.add(new LatLng(1,1)); Line line = lineManager.create(new LineOptions().withLatLngs(latLngs)); lineManager.delete(line); assertTrue(lineManager.getAnnotations().size() == 0); }
FillManager extends AnnotationManager<FillLayer, Fill, FillOptions, OnFillDragListener, OnFillClickListener, OnFillLongClickListener> { @Override public void setFilter(@NonNull Expression expression) { layerFilter = expression; layer.setFilter(layerFilter); } @UiThread FillManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style); @UiThread FillManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId); @UiThread FillManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions); @VisibleForTesting FillManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @NonNull CoreElementProvider<FillLayer> coreElementProvider, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions, DraggableAnnotationController draggableAnnotationController); @UiThread List<Fill> create(@NonNull String json); @UiThread List<Fill> create(@NonNull FeatureCollection featureCollection); Boolean getFillAntialias(); void setFillAntialias( Boolean value); Float[] getFillTranslate(); void setFillTranslate( Float[] value); String getFillTranslateAnchor(); void setFillTranslateAnchor(@Property.FILL_TRANSLATE_ANCHOR String value); @Override void setFilter(@NonNull Expression expression); @Nullable Expression getFilter(); }
@Test public void testInitializationOnStyleReload() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(style).addSource(geoJsonSource); verify(style).addLayer(fillLayer); assertTrue(fillManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : fillManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(fillLayer).setProperties(fillManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(draggableAnnotationController).onSourceUpdated(); verify(geoJsonSource).setGeoJson(any(FeatureCollection.class)); Expression filter = Expression.literal(false); fillManager.setFilter(filter); ArgumentCaptor<MapView.OnDidFinishLoadingStyleListener> loadingArgumentCaptor = ArgumentCaptor.forClass(MapView.OnDidFinishLoadingStyleListener.class); verify(mapView).addOnDidFinishLoadingStyleListener(loadingArgumentCaptor.capture()); loadingArgumentCaptor.getValue().onDidFinishLoadingStyle(); ArgumentCaptor<Style.OnStyleLoaded> styleLoadedArgumentCaptor = ArgumentCaptor.forClass(Style.OnStyleLoaded.class); verify(mapboxMap).getStyle(styleLoadedArgumentCaptor.capture()); Style newStyle = mock(Style.class); when(newStyle.isFullyLoaded()).thenReturn(true); GeoJsonSource newSource = mock(GeoJsonSource.class); when(coreElementProvider.getSource(null)).thenReturn(newSource); FillLayer newLayer = mock(FillLayer.class); when(coreElementProvider.getLayer()).thenReturn(newLayer); styleLoadedArgumentCaptor.getValue().onStyleLoaded(newStyle); verify(newStyle).addSource(newSource); verify(newStyle).addLayer(newLayer); assertTrue(fillManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : fillManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(newLayer).setProperties(fillManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(fillLayer).setFilter(filter); verify(draggableAnnotationController, times(2)).onSourceUpdated(); verify(newSource).setGeoJson(any(FeatureCollection.class)); } @Test public void testGeoJsonOptionsInitialization() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, geoJsonOptions, draggableAnnotationController); verify(style).addSource(optionedGeoJsonSource); verify(style).addLayer(fillLayer); assertTrue(fillManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : fillManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(fillLayer).setProperties(fillManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(fillLayer, times(0)).setFilter(any(Expression.class)); verify(draggableAnnotationController).onSourceUpdated(); verify(optionedGeoJsonSource).setGeoJson(any(FeatureCollection.class)); } @Test public void testInitialization() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(style).addSource(geoJsonSource); verify(style).addLayer(fillLayer); assertTrue(fillManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : fillManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(fillLayer).setProperties(fillManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(fillLayer, times(0)).setFilter(any(Expression.class)); verify(draggableAnnotationController).onSourceUpdated(); verify(geoJsonSource).setGeoJson(any(FeatureCollection.class)); }
LocalizationPlugin { public void setMapLanguage(@Languages String language) { setMapLanguage(new MapLocale(language)); } LocalizationPlugin(@NonNull MapView mapView, @NonNull final MapboxMap mapboxMap, @NonNull Style style); void matchMapLanguageWithDeviceDefault(); void matchMapLanguageWithDeviceDefault(boolean acceptFallback); void setMapLanguage(@Languages String language); void setMapLanguage(@NonNull Locale locale); void setMapLanguage(@NonNull Locale locale, boolean acceptFallback); void setMapLanguage(@NonNull MapLocale mapLocale); void setCameraToLocaleCountry(int padding); void setCameraToLocaleCountry(Locale locale, int padding); void setCameraToLocaleCountry(MapLocale mapLocale, int padding); }
@Test @Ignore public void setMapLanguage_localePassedInNotValid() throws Exception { when(style.isFullyLoaded()).thenReturn(true); thrown.expect(NullPointerException.class); thrown.expectMessage(containsString("has no matching MapLocale object. You need to create")); LocalizationPlugin localizationPlugin = new LocalizationPlugin(mock(MapView.class), mock(MapboxMap.class), style); localizationPlugin.setMapLanguage(new Locale("foo", "bar"), false); }
MapLocale { @Nullable public static MapLocale getMapLocale(@NonNull Locale locale) { return getMapLocale(locale, false); } MapLocale(@NonNull String mapLanguage); MapLocale(@NonNull LatLngBounds countryBounds); MapLocale(@NonNull @Languages String mapLanguage, @Nullable LatLngBounds countryBounds); @NonNull String getMapLanguage(); @Nullable LatLngBounds getCountryBounds(); static void addMapLocale(@NonNull Locale locale, @NonNull MapLocale mapLocale); @Nullable static MapLocale getMapLocale(@NonNull Locale locale); @Nullable static MapLocale getMapLocale(@NonNull Locale locale, boolean acceptFallback); static final String LOCAL_NAME; static final String ENGLISH; static final String FRENCH; static final String ARABIC; static final String SPANISH; static final String GERMAN; static final String PORTUGUESE; static final String RUSSIAN; static final String CHINESE; static final String SIMPLIFIED_CHINESE; static final String JAPANESE; static final String KOREAN; static final MapLocale FRANCE; static final MapLocale GERMANY; static final MapLocale JAPAN; static final MapLocale KOREA; static final MapLocale CHINA; static final MapLocale TAIWAN; static final MapLocale CHINESE_HANS; static final MapLocale CHINESE_HANT; static final MapLocale UK; static final MapLocale US; static final MapLocale CANADA; static final MapLocale CANADA_FRENCH; static final MapLocale RUSSIA; static final MapLocale SPAIN; static final MapLocale PORTUGAL; static final MapLocale BRAZIL; }
@Test public void regionalVariantsNoFallbackWhenNotRequested() throws Exception { Locale localeHN = new Locale("es_HN", "Honduras"); MapLocale mapLocale = MapLocale.getMapLocale(localeHN, false); assertNull(mapLocale); }
FillManager extends AnnotationManager<FillLayer, Fill, FillOptions, OnFillDragListener, OnFillClickListener, OnFillLongClickListener> { @UiThread public List<Fill> create(@NonNull String json) { return create(FeatureCollection.fromJson(json)); } @UiThread FillManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style); @UiThread FillManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId); @UiThread FillManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions); @VisibleForTesting FillManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @NonNull CoreElementProvider<FillLayer> coreElementProvider, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions, DraggableAnnotationController draggableAnnotationController); @UiThread List<Fill> create(@NonNull String json); @UiThread List<Fill> create(@NonNull FeatureCollection featureCollection); Boolean getFillAntialias(); void setFillAntialias( Boolean value); Float[] getFillTranslate(); void setFillTranslate( Float[] value); String getFillTranslateAnchor(); void setFillTranslateAnchor(@Property.FILL_TRANSLATE_ANCHOR String value); @Override void setFilter(@NonNull Expression expression); @Nullable Expression getFilter(); }
@Test public void testAddFill() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); innerLatLngs.add(new LatLng()); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); Fill fill = fillManager.create(new FillOptions().withLatLngs(latLngs)); assertEquals(fillManager.getAnnotations().get(0), fill); } @Test public void addFillFromFeatureCollection() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<Point> innerPoints = new ArrayList<>(); innerPoints.add(Point.fromLngLat(0, 0)); innerPoints.add(Point.fromLngLat(1, 1)); innerPoints.add(Point.fromLngLat(-1, -1)); innerPoints.add(Point.fromLngLat(0, 0)); List<List<Point>> points = new ArrayList<>(); points.add(innerPoints); Geometry geometry = Polygon.fromLngLats(points); Feature feature = Feature.fromGeometry(geometry); feature.addNumberProperty("fill-opacity", 2.0f); feature.addStringProperty("fill-color", "rgba(0, 0, 0, 1)"); feature.addStringProperty("fill-outline-color", "rgba(0, 0, 0, 1)"); feature.addStringProperty("fill-pattern", "pedestrian-polygon"); feature.addBooleanProperty("is-draggable", true); List<Fill> fills = fillManager.create(FeatureCollection.fromFeature(feature)); Fill fill = fills.get(0); assertEquals(fill.geometry, geometry); assertEquals(fill.getFillOpacity(), 2.0f); assertEquals(fill.getFillColor(), "rgba(0, 0, 0, 1)"); assertEquals(fill.getFillOutlineColor(), "rgba(0, 0, 0, 1)"); assertEquals(fill.getFillPattern(), "pedestrian-polygon"); assertTrue(fill.isDraggable()); } @Test public void addFills() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); final List<List<LatLng>> latLngListOne = new ArrayList<>(); latLngListOne.add(new ArrayList<LatLng>() {{ add(new LatLng(2, 2)); add(new LatLng(2, 3)); }}); latLngListOne.add(new ArrayList<LatLng>() {{ add(new LatLng(1, 1)); add(new LatLng(2, 3)); }}); final List<List<LatLng>> latLngListTwo = new ArrayList<>(); latLngListTwo.add(new ArrayList<LatLng>() {{ add(new LatLng(5, 7)); add(new LatLng(2, 3)); }}); latLngListTwo.add(new ArrayList<LatLng>() {{ add(new LatLng(1, 1)); add(new LatLng(3, 9)); }}); List<List<List<LatLng>>> latLngList = new ArrayList<List<List<LatLng>>>(){{ add(latLngListOne); add(latLngListTwo); }}; List<FillOptions> options = new ArrayList<>(); for (List<List<LatLng>> lists : latLngList) { options.add(new FillOptions().withLatLngs(lists)); } List<Fill> fills = fillManager.create(options); assertTrue("Returned value size should match", fills.size() == 2); assertTrue("Annotations size should match", fillManager.getAnnotations().size() == 2); } @Test public void testDeleteFill() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); Fill fill = fillManager.create(new FillOptions().withLatLngs(latLngs)); fillManager.delete(fill); assertTrue(fillManager.getAnnotations().size() == 0); } @Test public void testGeometryFill() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); FillOptions options = new FillOptions().withLatLngs(latLngs); Fill fill = fillManager.create(options); assertEquals(options.getLatLngs(), latLngs); assertEquals(fill.getLatLngs(), latLngs); assertEquals(options.getGeometry(), Polygon.fromLngLats(new ArrayList<List<Point>>() {{ add(new ArrayList<Point>() {{ add(Point.fromLngLat(0, 0)); add(Point.fromLngLat(1, 1)); add(Point.fromLngLat(-1, -1)); }}); }})); assertEquals(fill.getGeometry(), Polygon.fromLngLats(new ArrayList<List<Point>>() {{ add(new ArrayList<Point>() {{ add(Point.fromLngLat(0, 0)); add(Point.fromLngLat(1, 1)); add(Point.fromLngLat(-1, -1)); }}); }})); } @Test public void testFeatureIdFill() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); Fill fillZero = fillManager.create(new FillOptions().withLatLngs(latLngs)); Fill fillOne = fillManager.create(new FillOptions().withLatLngs(latLngs)); assertEquals(fillZero.getFeature().get(Fill.ID_KEY).getAsLong(), 0); assertEquals(fillOne.getFeature().get(Fill.ID_KEY).getAsLong(), 1); } @Test public void testFillDraggableFlag() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); Fill fillZero = fillManager.create(new FillOptions().withLatLngs(latLngs)); assertFalse(fillZero.isDraggable()); fillZero.setDraggable(true); assertTrue(fillZero.isDraggable()); fillZero.setDraggable(false); assertFalse(fillZero.isDraggable()); } @Test public void testFillOpacityLayerProperty() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(fillLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(fillOpacity(get("fill-opacity"))))); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); FillOptions options = new FillOptions().withLatLngs(latLngs).withFillOpacity(2.0f); fillManager.create(options); verify(fillLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(fillOpacity(get("fill-opacity"))))); fillManager.create(options); verify(fillLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(fillOpacity(get("fill-opacity"))))); } @Test public void testFillColorLayerProperty() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(fillLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(fillColor(get("fill-color"))))); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); FillOptions options = new FillOptions().withLatLngs(latLngs).withFillColor("rgba(0, 0, 0, 1)"); fillManager.create(options); verify(fillLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(fillColor(get("fill-color"))))); fillManager.create(options); verify(fillLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(fillColor(get("fill-color"))))); } @Test public void testFillOutlineColorLayerProperty() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(fillLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(fillOutlineColor(get("fill-outline-color"))))); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); FillOptions options = new FillOptions().withLatLngs(latLngs).withFillOutlineColor("rgba(0, 0, 0, 1)"); fillManager.create(options); verify(fillLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(fillOutlineColor(get("fill-outline-color"))))); fillManager.create(options); verify(fillLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(fillOutlineColor(get("fill-outline-color"))))); } @Test public void testFillPatternLayerProperty() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(fillLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(fillPattern(get("fill-pattern"))))); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); FillOptions options = new FillOptions().withLatLngs(latLngs).withFillPattern("pedestrian-polygon"); fillManager.create(options); verify(fillLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(fillPattern(get("fill-pattern"))))); fillManager.create(options); verify(fillLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(fillPattern(get("fill-pattern"))))); } @Test public void testCustomData() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); FillOptions options = new FillOptions().withLatLngs(latLngs); options.withData(new JsonPrimitive("hello")); Fill fill = fillManager.create(options); assertEquals(new JsonPrimitive("hello"), fill.getData()); } @Test public void testClearAll() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); FillOptions options = new FillOptions().withLatLngs(latLngs); fillManager.create(options); assertEquals(1, fillManager.getAnnotations().size()); fillManager.deleteAll(); assertEquals(0, fillManager.getAnnotations().size()); } @Test public void testIgnoreClearedAnnotations() { fillManager = new FillManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng>innerLatLngs = new ArrayList<>(); innerLatLngs.add(new LatLng()); innerLatLngs.add(new LatLng(1,1)); innerLatLngs.add(new LatLng(-1,-1)); List<List<LatLng>>latLngs = new ArrayList<>(); latLngs.add(innerLatLngs); FillOptions options = new FillOptions().withLatLngs(latLngs); Fill fill = fillManager.create(options); assertEquals(1, fillManager.annotations.size()); fillManager.getAnnotations().clear(); fillManager.updateSource(); assertTrue(fillManager.getAnnotations().isEmpty()); fillManager.update(fill); assertTrue(fillManager.getAnnotations().isEmpty()); }