method2testcases
stringlengths 118
6.63k
|
---|
### Question:
MostSimilarGuess { public PrecisionRecallAccumulator getPrecisionRecall(int n, double threshold) { PrecisionRecallAccumulator pr = new PrecisionRecallAccumulator(n, threshold); TIntDoubleMap actual = new TIntDoubleHashMap(); for (KnownSim ks : known.getMostSimilar()) { pr.observe(ks.similarity); actual.put(ks.wpId2, ks.similarity); } for (Observation o : observations) { if (o.rank > n) { break; } pr.observeRetrieved(actual.get(o.id)); } return pr; } MostSimilarGuess(KnownMostSim known, String str); MostSimilarGuess(KnownMostSim known, SRResultList guess); String toString(); List<Observation> getObservations(); int getLength(); KnownMostSim getKnown(); double getNDGC(); double getPenalizedNDGC(); PrecisionRecallAccumulator getPrecisionRecall(int n, double threshold); }### Answer:
@Test public void testPrecisionRecall() { PrecisionRecallAccumulator pr = guess.getPrecisionRecall(1, 0.7); assertEquals(pr.getN(), 1); assertEquals(1.0, pr.getPrecision(), 0.001); assertEquals(0.333333, pr.getRecall(), 0.001); pr = guess.getPrecisionRecall(2, 0.7); assertEquals(0.5, pr.getPrecision(), 0.001); assertEquals(0.333333, pr.getRecall(), 0.001); pr = guess.getPrecisionRecall(5, 0.7); assertEquals(0.6666, pr.getPrecision(), 0.001); assertEquals(0.6666, pr.getRecall(), 0.001); } |
### Question:
FileDownloader { public File download(URL url, File file) throws InterruptedException { LOG.info("beginning download of " + url + " to " + file); for (int i=1; i <= maxAttempts; i++) { try { AtomicBoolean stop = new AtomicBoolean(false); DownloadInfo info = new DownloadInfo(url); DownloadMonitor monitor = new DownloadMonitor(info); info.extract(stop, monitor); file.getParentFile().mkdirs(); WGet wget = new WGet(info, file); wget.download(stop, monitor); LOG.info("Download complete: " + file.getAbsolutePath()); while (!monitor.isFinished()) { Thread.sleep(sleepTime); } return file; } catch (DownloadIOCodeError e) { if (i < maxAttempts) { LOG.info("Failed to download " + url + ". Reconnecting in " + (i * backoffTime / 1000) + " seconds (HTTP " + e.getCode() + "-Error " + url + ")"); Thread.sleep(backoffTime * i); } else { LOG.warn("Failed to download " + file + " (HTTP " + e.getCode() + "-Error " + url + ")"); } } } return null; } FileDownloader(); File download(URL url, File file); void setSleepTime(int sleepTime); void setMaxAttempts(int maxAttempts); void setDisplayInfo(int displayInfo); void setBackoffTime(int backoffTime); static final Logger LOG; }### Answer:
@Test public void testDownloader() throws IOException, InterruptedException { URL url = new URL("http: File tmp1 = File.createTempFile("downloader-test", ".txt"); FileDownloader downloader = new FileDownloader(); downloader.download(url, tmp1); assertTrue(tmp1.isFile()); List<String> lines = FileUtils.readLines(tmp1); assert(lines.size() > 10); assertTrue(lines.get(0).startsWith("User-agent:")); File tmp2 = File.createTempFile("downloader-test", ".txt"); FileUtils.copyURLToFile(url, tmp2); assertTrue(tmp2.isFile()); assertTrue(FileUtils.readFileToString(tmp2).startsWith("User-agent:")); assertEquals(FileUtils.readFileToString(tmp1), FileUtils.readFileToString(tmp2)); }
@Test public void testDownloaderMove() throws IOException, InterruptedException { URL url = new URL("http: File tmp1 = File.createTempFile("downloader-test", ".txt"); File tmp3 = File.createTempFile("downloader-test", ".txt"); tmp1.delete(); tmp3.delete(); tmp3.deleteOnExit(); FileDownloader downloader = new FileDownloader(); downloader.download(url, tmp3); assertTrue(tmp3.isFile()); FileUtils.moveFile(tmp3, tmp1); } |
### Question:
JvmUtils { public synchronized static String getFullClassName(String shortName) { if (NAME_TO_CLASS != null) { return NAME_TO_CLASS.get(shortName); } NAME_TO_CLASS = new HashMap<String, String>(); for (File file : getClassPathAsList()) { if (file.length() > MAX_FILE_SIZE) { LOG.debug("skipping looking for providers in large file " + file); continue; } ClassFinder finder = new ClassFinder(); finder.add(file); ClassFilter filter = new AndClassFilter( new RegexClassFilter(WIKIBRAIN_CLASS_PATTERN.pattern()), new NotClassFilter(new RegexClassFilter(WIKIBRAIN_CLASS_BLACKLIST.pattern())) ); Collection<ClassInfo> foundClasses = new ArrayList<ClassInfo>(); finder.findClasses(foundClasses,filter); for (ClassInfo info : foundClasses) { String tokens[] = info.getClassName().split("[.]"); if (tokens.length == 0) { continue; } String n = tokens[tokens.length - 1]; if (!NAME_TO_CLASS.containsKey(n)) { NAME_TO_CLASS.put(n, info.getClassName()); } } } LOG.info("found " + NAME_TO_CLASS.size() + " classes when constructing short to full class name mapping"); return NAME_TO_CLASS.get(shortName); } static String getClassPath(); synchronized static List<File> getClassPathAsList(); static Process launch(Class klass, String args[]); static Process launch(Class klass, String args[], OutputStream out, OutputStream err, String heapSize); static void setWikiBrainClassPattern(Pattern pattern, Pattern blacklist); static Class classForShortName(String shortName); synchronized static String getFullClassName(String shortName); static final int MAX_FILE_SIZE; }### Answer:
@Test public void testFullClassName() { assertEquals("org.wikibrain.utils.JvmUtils", JvmUtils.getFullClassName("JvmUtils")); assertNull(JvmUtils.getFullClassName("Foozkjasdf")); } |
### Question:
JvmUtils { public static Class classForShortName(String shortName) { String fullName = getFullClassName(shortName); if (fullName == null) { return null; } try { return Class.forName(fullName); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } static String getClassPath(); synchronized static List<File> getClassPathAsList(); static Process launch(Class klass, String args[]); static Process launch(Class klass, String args[], OutputStream out, OutputStream err, String heapSize); static void setWikiBrainClassPattern(Pattern pattern, Pattern blacklist); static Class classForShortName(String shortName); synchronized static String getFullClassName(String shortName); static final int MAX_FILE_SIZE; }### Answer:
@Test public void testClassForShortName() { assertEquals(JvmUtils.class, JvmUtils.classForShortName("JvmUtils")); assertNull(JvmUtils.classForShortName("Foozkjasdf")); } |
### Question:
KafkaSinkFactory implements SinkFactory { @Override public String name() { return "kafka"; } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test public void testName() { assertThat(factory.name()).isEqualTo("kafka"); } |
### Question:
ReflectionHelper { public static void invokeTransformationMethod(Object mediator, Method method) { method = ReflectionHelper.makeAccessibleIfNot(method); List<Object> values = getParameterFromTransformationMethod(method); try { Class<?> returnType = method.getReturnType(); Outbound outbound = method.getAnnotation(Outbound.class); if (returnType.equals(Void.TYPE)) { method.invoke(mediator, values.toArray()); } else { if (outbound == null) { throw new IllegalStateException("The method " + method.getName() + " from " + mediator.getClass() + " needs to be annotated with @Outbound indicating the sink"); } else { Sink<Object> sink = getSinkOrFail(outbound.value()); Flowable<Object> flowable; if (Publisher.class.isAssignableFrom(returnType)) { flowable = Flowable.fromPublisher( (Publisher) method.invoke(mediator, values.toArray())); } else { throw new IllegalStateException("The method " + method.getName() + " from " + mediator.getClass() + " does not return a valid type"); } Type type = method.getGenericReturnType(); if (type instanceof ParameterizedType) { Type enclosed = ((ParameterizedType) type).getActualTypeArguments()[0]; if (!enclosed.getTypeName().startsWith(Message.class.getName())) { flowable.flatMapCompletable(sink::dispatch) .doOnError(Throwable::printStackTrace) .subscribe(); } else { flowable .flatMapCompletable(d -> sink.dispatch((Message) d)) .doOnError(Throwable::printStackTrace) .subscribe(); } } else { flowable.flatMapCompletable(sink::dispatch) .doOnError(Throwable::printStackTrace) .subscribe(); } } } } catch (Exception e) { throw new IllegalStateException("Unable to invoke " + method.getName() + " from " + mediator.getClass() .getName(), e); } } private ReflectionHelper(); static void set(Object mediator, Field field, Object source); static void invokeFunction(Object mediator, Method method); static void invokeTransformationMethod(Object mediator, Method method); static Object getSourceToInject(Class<?> clazz, Type type, Source<Object> source); static void inject(Object mediator); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testTransformationWithNotAnnotatedParameter() throws NoSuchMethodException { InvalidBecauseOfBadParams test = new InvalidBecauseOfBadParams(); Method method = test.getClass().getMethod("trans", Source.class); ReflectionHelper.invokeTransformationMethod(test, method); } |
### Question:
ReflectionHelper { static Sink<Object> getSinkOrFail(String name) { Sink<Object> sink = FluidRegistry.sink(Objects.requireNonNull(name)); if (sink == null) { throw new IllegalArgumentException("Unable to find the sink " + name); } return sink; } private ReflectionHelper(); static void set(Object mediator, Field field, Object source); static void invokeFunction(Object mediator, Method method); static void invokeTransformationMethod(Object mediator, Method method); static Object getSourceToInject(Class<?> clazz, Type type, Source<Object> source); static void inject(Object mediator); }### Answer:
@Test public void testGettingAMissingSink() { FluidRegistry.register("my-sink", Sink.list()); Sink<Object> sink = ReflectionHelper.getSinkOrFail("my-sink"); assertThat(sink).isNotNull(); try { ReflectionHelper.getSinkOrFail("missing"); fail("The sink should be missing"); } catch (IllegalArgumentException e) { } } |
### Question:
ReflectionHelper { static Source<Object> getSourceOrFail(String name) { Source<Object> src = FluidRegistry.source(Objects.requireNonNull(name)); if (src == null) { throw new IllegalArgumentException("Unable to find the source " + name); } return src; } private ReflectionHelper(); static void set(Object mediator, Field field, Object source); static void invokeFunction(Object mediator, Method method); static void invokeTransformationMethod(Object mediator, Method method); static Object getSourceToInject(Class<?> clazz, Type type, Source<Object> source); static void inject(Object mediator); }### Answer:
@Test public void testGettingAMissingSource() { FluidRegistry.register("my-source", Source.empty()); Source<Object> source = ReflectionHelper.getSourceOrFail("my-source"); assertThat(source).isNotNull(); try { ReflectionHelper.getSourceOrFail("missing"); fail("The source should be missing"); } catch (IllegalArgumentException e) { } } |
### Question:
FluidRegistry { public static synchronized <T> void register(Source<T> source) { sources.put(Objects.requireNonNull(source.name(), NAME_NOT_PROVIDED_MESSAGE), source); } private FluidRegistry(); static synchronized void initialize(Vertx vertx, FluidConfig config); static void reset(); static synchronized void register(Source<T> source); static synchronized void register(Sink<T> sink); static synchronized void register(String name, Source<T> source); static synchronized void register(String name, Sink<T> sink); static synchronized void unregisterSource(String name); static synchronized void unregisterSink(String name); @SuppressWarnings("unchecked") static Source<T> source(String name); @SuppressWarnings("unchecked") static Sink<T> sink(String name); @SuppressWarnings({"unused", "unchecked"}) static Source<T> source(String name, Class<T> clazz); }### Answer:
@Test(expected = NullPointerException.class) public void testRegistrationOfSinkWithNullName() { Sink<String> discard = Sink.discard(); FluidRegistry.register(null, discard); }
@Test(expected = NullPointerException.class) public void testRegistrationOfSourceWithNullName() { Source<String> source = Source.empty(); FluidRegistry.register(null, source); } |
### Question:
FluidRegistry { public static synchronized void initialize(Vertx vertx, FluidConfig config) { sinks.putAll(SourceAndSinkBuilder.createSinksFromConfiguration(vertx, config)); sources.putAll(SourceAndSinkBuilder.createSourcesFromConfiguration(vertx, config)); } private FluidRegistry(); static synchronized void initialize(Vertx vertx, FluidConfig config); static void reset(); static synchronized void register(Source<T> source); static synchronized void register(Sink<T> sink); static synchronized void register(String name, Source<T> source); static synchronized void register(String name, Sink<T> sink); static synchronized void unregisterSource(String name); static synchronized void unregisterSink(String name); @SuppressWarnings("unchecked") static Source<T> source(String name); @SuppressWarnings("unchecked") static Sink<T> sink(String name); @SuppressWarnings({"unused", "unchecked"}) static Source<T> source(String name, Class<T> clazz); }### Answer:
@Test public void testInitialize() { Fluid fluid = Fluid.create(); assertThat(FluidRegistry.source("unknown")).isNull(); assertThat(FluidRegistry.sink("unknown")).isNull(); fluid.vertx().close(); } |
### Question:
SourceAndSinkBuilder { public static Map<String, Source> createSourcesFromConfiguration(Vertx vertx, FluidConfig config) { Map<String, Source> map = new HashMap<>(); Optional<Config> sources = config.getConfig("sources"); if (sources.isPresent()) { Iterator<String> names = sources.get().names(); while (names.hasNext()) { String name = names.next(); LOGGER.info("Creating source from configuration `" + name + "`"); Optional<Config> conf = sources.get().getConfig(name); Source<?> source = buildSource(vertx, name, conf.orElseThrow(() -> new IllegalStateException("Illegal configuration for source `" + name + "`"))); map.put(name, source); } } else { LOGGER.warn("No sources configured from the fluid configuration"); } return map; } static Map<String, Source> createSourcesFromConfiguration(Vertx vertx, FluidConfig config); static Map<String, Sink> createSinksFromConfiguration(Vertx vertx, FluidConfig config); }### Answer:
@SuppressWarnings("unchecked") @Test public void loadSourceTest() { Map<String, Source> sources = SourceAndSinkBuilder.createSourcesFromConfiguration(vertx, fluid.getConfig()); assertThat(sources).hasSize(2); Source<String> source1 = sources.get("source1"); assertThat(source1).isNotNull(); Source<Integer> source2 = sources.get("source2"); assertThat(source2).isNotNull(); ListSink<String> list = new ListSink<>(); source1.to(list); assertThat(list.values()).containsExactly("a", "b", "c"); assertThat(source1.name()).isEqualTo("source1"); ListSink<Integer> list2 = new ListSink<>(); source2.to(list2); assertThat(list2.values()).containsExactly(0, 1, 2, 3); assertThat(source2.name()).isEqualTo("source2"); } |
### Question:
SourceAndSinkBuilder { public static Map<String, Sink> createSinksFromConfiguration(Vertx vertx, FluidConfig config) { Map<String, Sink> map = new HashMap<>(); Optional<Config> sinks = config.getConfig("sinks"); if (sinks.isPresent()) { Iterator<String> names = sinks.get().names(); while (names.hasNext()) { String name = names.next(); LOGGER.info("Creating sink from configuration `" + name + "`"); Optional<Config> conf = sinks.get().getConfig(name); Sink<?> sink = buildSink(vertx, name, conf.orElseThrow(() -> new IllegalStateException("Illegal configuration for source `" + name + "`"))); map.put(name, sink); } } else { LOGGER.warn("No sinks configured from the fluid configuration"); } return map; } static Map<String, Source> createSourcesFromConfiguration(Vertx vertx, FluidConfig config); static Map<String, Sink> createSinksFromConfiguration(Vertx vertx, FluidConfig config); }### Answer:
@SuppressWarnings("unchecked") @Test public void loadSinkTest() { Map<String, Sink> sinks = SourceAndSinkBuilder.createSinksFromConfiguration(vertx, fluid.getConfig()); assertThat(sinks).hasSize(2); Sink<String> sink1 = sinks.get("sink1"); assertThat(sink1).isNotNull().isInstanceOf(ListSink.class); Sink<Integer> sink2 = sinks.get("sink2"); assertThat(sink2).isNotNull().isInstanceOf(ListSink.class); Source.from("1", "2", "3").to(sink1); Source.from(4, 5).to(sink2); assertThat(((ListSink) sink1).values()).containsExactly("1", "2", "3"); assertThat(((ListSink) sink2).values()).containsExactly(4, 5); } |
### Question:
CommonHeaders { public static String address(Message message) { return (String) message.get(ADDRESS); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldGetRequiredAddress() { assertThat(address(messageWithCommonHeaders)).isEqualTo("address"); } |
### Question:
CommonHeaders { @SuppressWarnings("unchecked") public static Optional<String> addressOpt(Message message) { return message.getOpt(ADDRESS); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldHandleEmptyAddress() { assertThat(addressOpt(messageWithoutCommonHeaders)).isEmpty(); } |
### Question:
KafkaSinkFactory implements SinkFactory { @Override public <T> Single<Sink<T>> create(Vertx vertx, String name, Config config) { return Single.just(new KafkaSink<>(vertx, name, config)); } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test(expected = ConfigException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); }
@Test public void testCreationWithMinimalConfiguration() throws IOException { Single<Sink<Object>> single = factory.create(vertx, null, new Config(new JsonObject() .put("bootstrap.servers", "localhost:9092") .put("key.serializer", JsonObjectSerializer.class.getName()) .put("value.serializer", JsonObjectSerializer.class.getName()))); Sink<Object> sink = single.blockingGet(); assertThat(sink).isInstanceOf(KafkaSink.class); } |
### Question:
CommonHeaders { public static String key(Message message) { return (String) message.get(KEY); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldGetRequiredKey() { assertThat(key(messageWithCommonHeaders)).isEqualTo("key"); } |
### Question:
CommonHeaders { @SuppressWarnings("unchecked") public static Optional<String> keyOpt(Message message) { return message.getOpt(KEY); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldHandleEmptyKey() { assertThat(keyOpt(messageWithoutCommonHeaders)).isEmpty(); } |
### Question:
CommonHeaders { @SuppressWarnings("unchecked") public static <T> T original(Message message) { return (T) message.get(ORIGINAL); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldGetRequiredOriginalData() { assertThat(CommonHeaders.<String>original(messageWithCommonHeaders)).isEqualTo("original"); } |
### Question:
CommonHeaders { @SuppressWarnings("unchecked") public static <T> Optional<T> originalOpt(Message message) { return message.getOpt(ORIGINAL); } private CommonHeaders(); @SuppressWarnings("unchecked") static T original(Message message); @SuppressWarnings("unchecked") static Optional<T> originalOpt(Message message); static String address(Message message); @SuppressWarnings("unchecked") static Optional<String> addressOpt(Message message); static String key(Message message); @SuppressWarnings("unchecked") static Optional<String> keyOpt(Message message); static ResponseCallback responseCallback(Message message); static Optional<ResponseCallback> responseCallbackOpt(Message message); static final String ORIGINAL; static final String ADDRESS; static final String KEY; static final String RESPONSE_CALLBACK; static final String GROUP_KEY; }### Answer:
@Test public void shouldHandleEmptyOriginal() { assertThat(originalOpt(messageWithoutCommonHeaders)).isEmpty(); } |
### Question:
DefaultSource implements Source<T> { @Override public Source<T> named(String name) { if (Strings.isBlank(name)) { throw new IllegalArgumentException("The name cannot be `null` or blank"); } return new DefaultSource<>(flow, name, attributes); } DefaultSource(Publisher<Message<T>> items, String name, Map<String, Object> attr); @Override Source<T> named(String name); @Override Source<T> unnamed(); @Override Source<T> withAttribute(String key, Object value); @Override Source<T> withoutAttribute(String key); @Override void subscribe(Subscriber<? super Message<T>> s); @Override Source<T> orElse(Source<T> alt); @Override String name(); @Override Optional<T> attr(String key); @Override Source<X> map(Function<Message<T>, Message<X>> mapper); @Override Source<X> mapPayload(Function<T, X> mapper); @Override Source<T> filter(Predicate<Message<T>> filter); @Override Source<T> filterPayload(Predicate<T> filter); @Override Source<T> filterNot(Predicate<Message<T>> filter); @Override Source<T> filterNotPayload(Predicate<T> filter); @Override Source<X> flatMap(Function<Message<T>, Publisher<Message<X>>> mapper); @Override Source<X> concatMap(Function<Message<T>, Publisher<Message<X>>> mapper); @Override Source<X> flatMap(Function<Message<T>, Publisher<Message<X>>> mapper, int maxConcurrency); @Override Source<X> flatMapPayload(Function<T, Publisher<X>> mapper); @Override Source<X> concatMapPayload(Function<T, Publisher<X>> mapper); @Override Source<X> flatMapPayload(Function<T, Publisher<X>> mapper, int maxConcurrency); @Override Source<X> scan(Message<X> zero, BiFunction<Message<X>, Message<T>, Message<X>> function); @Override Source<X> scanPayloads(X zero, BiFunction<X, T, X> function); @Override Publisher<GroupedDataStream<K, T>> groupBy(Function<Message<T>, K> keySupplier); @Override Source<T> log(String loggerName); @Override List<Source<T>> broadcast(int numberOfBranches); @Override Map<String, Source<T>> broadcast(String... names); @Override Pair<Source<T>, Source<T>> branch(Predicate<Message<T>> condition); @Override Pair<Source<T>, Source<T>> branchOnPayload(Predicate<T> condition); @Override Sink<T> to(Sink<T> sink); @Override Flowable<Message<T>> asFlowable(); @Override Source<Pair<T, O>> zipWith(Publisher<Message<O>> source); @Override Source<Tuple> zipWith(Source... sources); Source<Tuple> zipWith(Publisher<Message>... sources); @Override Source<T> mergeWith(Publisher<Message<T>> source); @Override Source<T> mergeWith(Publisher<Message<T>>... sources); @Override Source<X> compose(Function<Publisher<Message<T>>, Publisher<Message<X>>> mapper); @Override Source<X> composeFlowable(Function<Flowable<Message<T>>, Flowable<Message<X>>> mapper); @Override Source<X> composePayloadFlowable(Function<Flowable<T>, Flowable<X>> function); static final String FUNCTION_CANNOT_BE_NULL_MESSAGE; static final String FILTER_CANNOT_BE_NULL_MESSAGE; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testNullName() { Source.from("a", "b", "c").named(null); }
@Test(expected = IllegalArgumentException.class) public void testBlankName() { Source.from("a", "b", "c").named(" "); } |
### Question:
DefaultSource implements Source<T> { @Override public <X> Source<X> compose(Function<Publisher<Message<T>>, Publisher<Message<X>>> mapper) { return new DefaultSource<>(asFlowable().compose(mapper::apply), name, attributes); } DefaultSource(Publisher<Message<T>> items, String name, Map<String, Object> attr); @Override Source<T> named(String name); @Override Source<T> unnamed(); @Override Source<T> withAttribute(String key, Object value); @Override Source<T> withoutAttribute(String key); @Override void subscribe(Subscriber<? super Message<T>> s); @Override Source<T> orElse(Source<T> alt); @Override String name(); @Override Optional<T> attr(String key); @Override Source<X> map(Function<Message<T>, Message<X>> mapper); @Override Source<X> mapPayload(Function<T, X> mapper); @Override Source<T> filter(Predicate<Message<T>> filter); @Override Source<T> filterPayload(Predicate<T> filter); @Override Source<T> filterNot(Predicate<Message<T>> filter); @Override Source<T> filterNotPayload(Predicate<T> filter); @Override Source<X> flatMap(Function<Message<T>, Publisher<Message<X>>> mapper); @Override Source<X> concatMap(Function<Message<T>, Publisher<Message<X>>> mapper); @Override Source<X> flatMap(Function<Message<T>, Publisher<Message<X>>> mapper, int maxConcurrency); @Override Source<X> flatMapPayload(Function<T, Publisher<X>> mapper); @Override Source<X> concatMapPayload(Function<T, Publisher<X>> mapper); @Override Source<X> flatMapPayload(Function<T, Publisher<X>> mapper, int maxConcurrency); @Override Source<X> scan(Message<X> zero, BiFunction<Message<X>, Message<T>, Message<X>> function); @Override Source<X> scanPayloads(X zero, BiFunction<X, T, X> function); @Override Publisher<GroupedDataStream<K, T>> groupBy(Function<Message<T>, K> keySupplier); @Override Source<T> log(String loggerName); @Override List<Source<T>> broadcast(int numberOfBranches); @Override Map<String, Source<T>> broadcast(String... names); @Override Pair<Source<T>, Source<T>> branch(Predicate<Message<T>> condition); @Override Pair<Source<T>, Source<T>> branchOnPayload(Predicate<T> condition); @Override Sink<T> to(Sink<T> sink); @Override Flowable<Message<T>> asFlowable(); @Override Source<Pair<T, O>> zipWith(Publisher<Message<O>> source); @Override Source<Tuple> zipWith(Source... sources); Source<Tuple> zipWith(Publisher<Message>... sources); @Override Source<T> mergeWith(Publisher<Message<T>> source); @Override Source<T> mergeWith(Publisher<Message<T>>... sources); @Override Source<X> compose(Function<Publisher<Message<T>>, Publisher<Message<X>>> mapper); @Override Source<X> composeFlowable(Function<Flowable<Message<T>>, Flowable<Message<X>>> mapper); @Override Source<X> composePayloadFlowable(Function<Flowable<T>, Flowable<X>> function); static final String FUNCTION_CANNOT_BE_NULL_MESSAGE; static final String FILTER_CANNOT_BE_NULL_MESSAGE; }### Answer:
@Test public void testCompose() { ListSink<Integer> list = Sink.list(); Source.from(1, 2, 3, 4, 5) .composeFlowable(flow -> flow.map(Message::payload).map(i -> i + 1).map(Message::new)) .to(list); assertThat(list.values()).containsExactly(2, 3, 4, 5, 6); } |
### Question:
Tuple implements Iterable<Object> { Tuple(Object... items) { if (items == null) { this.items = Collections.emptyList(); } else { for (Object o : items) { if (o == null) { throw new IllegalArgumentException("A tuple cannot contain a `null` value"); } } this.items = Collections.unmodifiableList(Arrays.asList(items)); } } Tuple(Object... items); static Tuple tuple(Object... items); int size(); @SuppressWarnings("unchecked") T nth(int pos); @Override Iterator<Object> iterator(); boolean contains(Object value); final boolean containsAll(Collection<?> collection); final boolean containsAll(final Object... values); final int indexOf(Object value); final int lastIndexOf(Object value); final List<Object> asList(); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testTupleWithNull() { Tuple.tuple("a", "b", null, "c"); } |
### Question:
EventBusSourceFactory implements SourceFactory { @Override public String name() { return "eventbus"; } @Override String name(); @Override Single<Source<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test public void testName() { assertThat(factory.name()).isEqualTo("eventbus"); } |
### Question:
EventBusSourceFactory implements SourceFactory { @Override public <T> Single<Source<T>> create(Vertx vertx, String name, Config config) { String address = config.getString("address") .orElse(name); if (address == null) { throw new IllegalArgumentException("Either address or name must be set"); } return Single.just(new EventBusSource<>(vertx, name, address, config)); } @Override String name(); @Override Single<Source<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); }
@Test public void testCreationWithAddress() throws IOException { Single<Source<Object>> single = factory.create(vertx, null, new Config(new JsonObject().put("address", "an-address"))); Source<Object> sink = single.blockingGet(); assertThat(sink).isInstanceOf(EventBusSource.class); } |
### Question:
EventBusSinkFactory implements SinkFactory { @Override public String name() { return "eventbus"; } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config conf); }### Answer:
@Test public void testName() { assertThat(factory.name()).isEqualTo("eventbus"); } |
### Question:
EventBusSinkFactory implements SinkFactory { @Override public <T> Single<Sink<T>> create(Vertx vertx, String name, Config conf) { return Single.just(new EventBusSink<>(vertx, conf)); } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config conf); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); }
@Test public void testCreationWithAddress() throws IOException { Single<Sink<Object>> single = factory.create(vertx, null, new Config(new JsonObject().put("address", "an-address"))); Sink<Object> sink = single.blockingGet(); assertThat(sink).isInstanceOf(EventBusSink.class); } |
### Question:
KafkaSourceFactory implements SourceFactory { @Override public String name() { return "kafka"; } @Override String name(); @Override Single<Source<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test public void testName() { assertThat(factory.name()).isEqualTo("kafka"); } |
### Question:
CamelSink implements Sink<T> { public CamelContext camelContext() { return camelContext; } CamelSink(String name, Config config); @Override String name(); @Override Completable dispatch(Message<T> message); CamelContext camelContext(); }### Answer:
@Test public void shouldWrapIntegersIntoCamelBodies(TestContext context) throws Exception { Async async = context.async(); CamelSink<Integer> sink = new CamelSink<>( null, new Config( new JsonObject().put("endpoint", "direct:test") ) ); CamelContext camelContext = sink.camelContext(); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:test").process(event -> { if (event.getIn().getBody(Integer.class) == 10) { context.assertEquals(event.getIn().getBody(Integer.class), 10); async.complete(); } }); } }); Source.from(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).to(sink); } |
### Question:
CamelSinkFactory implements SinkFactory { @Override public String name() { return "camel"; } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test public void testName() { CamelSinkFactory factory = new CamelSinkFactory(); assertThat(factory.name()).isEqualTo("camel"); } |
### Question:
CamelSinkFactory implements SinkFactory { @Override public <T> Single<Sink<T>> create(Vertx vertx, String name, Config config) { return Single.just(new CamelSink<>(name, config)); } @Override String name(); @Override Single<Sink<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testCreationWithoutParameter() { CamelSinkFactory factory = new CamelSinkFactory(); factory.create(vertx, null , new Config(NullNode.getInstance())); }
@Test public void testCreationWithEndpoint() throws IOException { CamelSinkFactory factory = new CamelSinkFactory(); Single<Sink<Object>> single = factory.create(vertx, null , new Config(new JsonObject().put("endpoint", "my-endpoint"))); Sink<Object> sink = single.blockingGet(); assertThat(sink).isInstanceOf(CamelSink.class); } |
### Question:
InMemoryDocumentView implements DocumentView { @Override public synchronized Completable save(String collection, String key, Map<String, Object> document) { Objects.requireNonNull(collection, NULL_COLLECTION_MESSAGE); Objects.requireNonNull(key, NULL_KEY_MESSAGE); Objects.requireNonNull(collection, "The `document` must not be `null`"); return Completable.fromAction(() -> { Map<String, Map<String, Object>> collectionData = documents.computeIfAbsent(collection, k -> new LinkedHashMap<>()); collectionData.put(key, document); }); } @Override synchronized Completable save(String collection, String key, Map<String, Object> document); @Override synchronized Single<Map<String, Object>> findById(String collection, String key); @Override synchronized Single<Long> count(String collection); @Override synchronized Flowable<DocumentWithKey> findAll(String collection); @Override synchronized Completable remove(String collection, String key); static final String NULL_COLLECTION_MESSAGE; static final String NULL_KEY_MESSAGE; }### Answer:
@Test public void shouldCallSubscriberOnSave(TestContext context) { Async async = context.async(); view.save(collection, key, document).subscribe(async::complete); } |
### Question:
KafkaSourceFactory implements SourceFactory { @Override public <T> Single<Source<T>> create(Vertx vertx, String name, Config config) { return Single.just(new KafkaSource<>(vertx, name, config)); } @Override String name(); @Override Single<Source<T>> create(Vertx vertx, String name, Config config); }### Answer:
@Test(expected = ConfigException.class) public void testCreationWithoutParameter() { factory.create(vertx, null, new Config(NullNode.getInstance())); }
@Test public void testCreationWithMinimalConfiguration() throws IOException { Single<Source<Object>> single = factory.create(vertx, null, new Config(new JsonObject() .put("bootstrap.servers", "localhost:9092") .put("key.deserializer", JsonObjectDeserializer.class.getName()) .put("value.deserializer", JsonObjectDeserializer.class.getName()))); Source<Object> sink = single.blockingGet(); assertThat(sink).isInstanceOf(KafkaSource.class); } |
### Question:
ReflectionHelper { public static void set(Object mediator, Field field, Object source) { if (!field.isAccessible()) { field.setAccessible(true); } try { field.set(mediator, source); } catch (IllegalAccessException e) { throw new IllegalStateException("Unable to set field " + field.getName() + " from " + mediator.getClass().getName() + " to " + source, e); } } private ReflectionHelper(); static void set(Object mediator, Field field, Object source); static void invokeFunction(Object mediator, Method method); static void invokeTransformationMethod(Object mediator, Method method); static Object getSourceToInject(Class<?> clazz, Type type, Source<Object> source); static void inject(Object mediator); }### Answer:
@Test public void testValidSet() throws NoSuchFieldException { Test1 test = new Test1(); Field field = Test1.class.getDeclaredField("foo"); ReflectionHelper.set(test, field, "hello"); assertThat(test.foo).isEqualTo("hello"); }
@Test(expected = IllegalArgumentException.class) public void testInvalidSet() throws NoSuchFieldException { Test1 test = new Test1(); Field field = Test1.class.getDeclaredField("foo"); ReflectionHelper.set(test, field, 10); } |
### Question:
ReflectionHelper { public static void invokeFunction(Object mediator, Method method) { method = ReflectionHelper.makeAccessibleIfNot(method); List<Flowable<Object>> sources = getFlowableForParameters(method); Function function = method.getAnnotation(Function.class); Sink<Object> sink = null; if (function.outbound().length() != 0) { sink = getSinkOrFail(function.outbound()); } Method methodToBeInvoked = method; Sink<Object> theSink = sink; Flowable<Optional<Object>> result; if (sources.size() == 1) { result = sources.get(0) .map(item -> Optional.ofNullable(methodToBeInvoked.invoke(mediator, item))); } else { result = Flowable.zip(sources, args -> args) .map(args -> Optional.ofNullable(methodToBeInvoked.invoke(mediator, args))); } result .flatMapCompletable(maybeResult -> { if (! maybeResult.isPresent()) { return Completable.complete(); } else { return propagateResult(maybeResult.get(), theSink); } }) .doOnError(Throwable::printStackTrace) .subscribe(); } private ReflectionHelper(); static void set(Object mediator, Field field, Object source); static void invokeFunction(Object mediator, Method method); static void invokeTransformationMethod(Object mediator, Method method); static Object getSourceToInject(Class<?> clazz, Type type, Source<Object> source); static void inject(Object mediator); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFunctionWithNotAnnotatedParameter() throws NoSuchMethodException { InvalidBecauseOfBadParams test = new InvalidBecauseOfBadParams(); Method method = test.getClass().getMethod("function", String.class); ReflectionHelper.invokeFunction(test, method); }
@Test(expected = IllegalArgumentException.class) public void testFunctionWithoutParam() throws NoSuchMethodException { InvalidBecauseOfBadParams test = new InvalidBecauseOfBadParams(); Method method = test.getClass().getMethod("functionWithoutParam"); ReflectionHelper.invokeFunction(test, method); } |
### Question:
PostgreSQLHStoreType extends ImmutableType<Map> { @Override protected Map get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException { return (Map) rs.getObject(names[0]); } PostgreSQLHStoreType(); @Override int[] sqlTypes(); static final PostgreSQLHStoreType INSTANCE; }### Answer:
@Test public void test() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Book book = new Book(); book.setIsbn("978-9730228236"); book.getProperties().put("title", "High-Performance Java Persistence"); book.getProperties().put("author", "Vlad Mihalcea"); book.getProperties().put("publisher", "Amazon"); book.getProperties().put("price", "$44.95"); entityManager.persist(book); return null; } }); doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Book book = (Book) entityManager.unwrap(Session.class) .bySimpleNaturalId(Book.class) .load("978-9730228236"); assertEquals("High-Performance Java Persistence", book.getProperties().get("title")); assertEquals("Vlad Mihalcea", book.getProperties().get("author")); return null; } }); }
@Test public void test() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Book book = new Book(); book.setIsbn("978-9730228236"); book.getProperties().put("title", "High-Performance Java Persistence"); book.getProperties().put("author", "Vlad Mihalcea"); book.getProperties().put("publisher", "Amazon"); book.getProperties().put("price", "$44.95"); entityManager.persist(book); return null; } }); doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Book book = entityManager.unwrap(Session.class) .bySimpleNaturalId(Book.class) .load("978-9730228236"); assertEquals("High-Performance Java Persistence", book.getProperties().get("title")); assertEquals("Vlad Mihalcea", book.getProperties().get("author")); return null; } }); } |
### Question:
PostgreSQLGuavaRangeType extends ImmutableType<Range> implements DynamicParameterizedType { public static Range<Integer> integerRange(String range) { return ofString(range, new Function<String, Integer>() { @Override public Integer apply(String s) { return Integer.parseInt(s); } }, Integer.class); } PostgreSQLGuavaRangeType(); @Override int[] sqlTypes(); @SuppressWarnings("unchecked") static Range<T> ofString(String str, Function<String, T> converter, Class<T> cls); static Range<BigDecimal> bigDecimalRange(String range); static Range<Integer> integerRange(String range); static Range<Long> longRange(String range); String asString(Range range); @Override void setParameterValues(Properties parameters); Class<?> getElementType(); static final PostgreSQLGuavaRangeType INSTANCE; }### Answer:
@Test public void testUnboundedRangeStringIsRejected() { try { PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; instance.integerRange("(,)"); fail("An unbounded range string should throw an exception!"); } catch (Exception e) { Throwable rootCause = Throwables.getRootCause(e); assertTrue(rootCause instanceof IllegalArgumentException); assertTrue(rootCause.getMessage().contains("Cannot find bound type")); } } |
### Question:
JacksonUtil { public static <T> T clone(T value) { return ObjectMapperWrapper.INSTANCE.clone(value); } static T fromString(String string, Class<T> clazz); static T fromString(String string, Type type); static String toString(Object value); static JsonNode toJsonNode(String value); static T clone(T value); }### Answer:
@Test public void cloneDeserializeStepErrorTest() { MyEntity entity = new MyEntity(); entity.setValue("some value"); entity.setPojos(Arrays.asList( createMyPojo("first value", MyType.A, "1.1", createOtherPojo("USD")), createMyPojo("second value", MyType.B, "1.2", createOtherPojo("BRL")) )); MyEntity clone = JacksonUtil.clone(entity); assertEquals(clone, entity); List<MyPojo> clonePojos = JacksonUtil.clone(entity.getPojos()); assertEquals(clonePojos, entity.getPojos()); } |
### Question:
JsonTypeDescriptor extends AbstractTypeDescriptor<Object> implements DynamicParameterizedType { @Override public boolean areEqual(Object one, Object another) { if (one == another) { return true; } if (one == null || another == null) { return false; } if (one instanceof String && another instanceof String) { return one.equals(another); } if (one instanceof Collection && another instanceof Collection) { return Objects.equals(one, another); } if (one.getClass().equals(another.getClass()) && ReflectionUtils.getDeclaredMethodOrNull(one.getClass(), "equals", Object.class) != null) { return one.equals(another); } return objectMapperWrapper.toJsonNode(objectMapperWrapper.toString(one)).equals( objectMapperWrapper.toJsonNode(objectMapperWrapper.toString(another)) ); } JsonTypeDescriptor(); JsonTypeDescriptor(Type type); JsonTypeDescriptor(final ObjectMapperWrapper objectMapperWrapper); JsonTypeDescriptor(final ObjectMapperWrapper objectMapperWrapper, Type type); @Override void setParameterValues(Properties parameters); @Override boolean areEqual(Object one, Object another); @Override String toString(Object value); @Override Object fromString(String string); @SuppressWarnings({"unchecked"}) @Override X unwrap(Object value, Class<X> type, WrapperOptions options); @Override Object wrap(X value, WrapperOptions options); }### Answer:
@Test public void testSetsAreEqual() { JsonTypeDescriptor descriptor = new JsonTypeDescriptor(); Form theFirst = createForm(1, 2, 3); Form theSecond = createForm(3, 2, 1); assertTrue(descriptor.areEqual(theFirst, theSecond)); } |
### Question:
SQLExtractor { public static String from(Query query) { AbstractProducedQuery abstractProducedQuery = query.unwrap(AbstractProducedQuery.class); String[] sqls = abstractProducedQuery .getProducer() .getFactory() .getQueryPlanCache() .getHQLQueryPlan(abstractProducedQuery.getQueryString(), false, Collections.emptyMap()) .getSqlStrings(); return sqls.length > 0 ? sqls[0] : null; } private SQLExtractor(); static String from(Query query); }### Answer:
@Test public void testJPQL() { doInJPA(entityManager -> { Query jpql = entityManager .createQuery( "select " + " YEAR(p.createdOn) as year, " + " count(p) as postCount " + "from " + " Post p " + "group by " + " YEAR(p.createdOn)", Tuple.class); String sql = SQLExtractor.from(jpql); assertNotNull(sql); LOGGER.info( "The JPQL query: [\n{}\n]\ngenerates the following SQL query: [\n{}\n]", jpql.unwrap(org.hibernate.query.Query.class).getQueryString(), sql ); }); }
@Test public void testCriteriaAPI() { doInJPA(entityManager -> { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<PostComment> criteria = builder.createQuery(PostComment.class); Root<PostComment> postComment = criteria.from(PostComment.class); Join<PostComment, Post> post = postComment.join("post"); criteria.where( builder.like(post.get("title"), "%Java%") ); criteria.orderBy( builder.asc(postComment.get("id")) ); Query criteriaQuery = entityManager.createQuery(criteria); String sql = SQLExtractor.from(criteriaQuery); assertNotNull(sql); LOGGER.info( "The Criteria API query: [\n{}\n]\ngenerates the following SQL query: [\n{}\n]", criteriaQuery.unwrap(org.hibernate.query.Query.class).getQueryString(), sql ); }); } |
### Question:
Configuration { public Properties getProperties() { return properties; } private Configuration(); Properties getProperties(); ObjectMapperWrapper getObjectMapperWrapper(); Integer integerProperty(PropertyKey propertyKey); Long longProperty(PropertyKey propertyKey); Boolean booleanProperty(PropertyKey propertyKey); Class<T> classProperty(PropertyKey propertyKey); static final Configuration INSTANCE; static final String PROPERTIES_FILE_PATH; static final String PROPERTIES_FILE_NAME; }### Answer:
@Test public void testHibernateProperties() { assertNull(Configuration.INSTANCE.getProperties().getProperty("hibernate.types.nothing")); assertEquals("def", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.abc")); }
@Test public void testHibernateTypesOverrideProperties() { assertEquals("ghi", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.def")); } |
### Question:
PostgreSQLHStoreType extends ImmutableType<Map> { @Override protected Map get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { return (Map) rs.getObject(names[0]); } PostgreSQLHStoreType(); @Override int[] sqlTypes(); static final PostgreSQLHStoreType INSTANCE; }### Answer:
@Test public void test() { doInJPA(entityManager -> { Book book = new Book(); book.setIsbn("978-9730228236"); book.getProperties().put("title", "High-Performance Java Persistence"); book.getProperties().put("author", "Vlad Mihalcea"); book.getProperties().put("publisher", "Amazon"); book.getProperties().put("price", "$44.95"); entityManager.persist(book); }); doInJPA(entityManager -> { Book book = entityManager.unwrap(Session.class) .bySimpleNaturalId(Book.class) .load("978-9730228236"); assertEquals("High-Performance Java Persistence", book.getProperties().get("title")); assertEquals("Vlad Mihalcea", book.getProperties().get("author")); }); } |
### Question:
Range implements Serializable { public static Range<LocalDateTime> localDateTimeRange(String range) { return ofString(range, parseLocalDateTime().compose(unquote()), LocalDateTime.class); } private Range(T lower, T upper, int mask, Class<T> clazz); @SuppressWarnings("unchecked") static Range<T> closed(T lower, T upper); @SuppressWarnings("unchecked") static Range<T> open(T lower, T upper); @SuppressWarnings("unchecked") static Range<T> openClosed(T lower, T upper); @SuppressWarnings("unchecked") static Range<T> closedOpen(T lower, T upper); @SuppressWarnings("unchecked") static Range<T> openInfinite(T lower); @SuppressWarnings("unchecked") static Range<T> closedInfinite(T lower); @SuppressWarnings("unchecked") static Range<T> infiniteOpen(T upper); @SuppressWarnings("unchecked") static Range<T> infiniteClosed(T upper); @SuppressWarnings("unchecked") static Range<T> infinite(Class<T> cls); @SuppressWarnings("unchecked") static Range<T> ofString(String str, Function<String, T> converter, Class<T> clazz); static Range<BigDecimal> bigDecimalRange(String range); static Range<Integer> integerRange(String range); static Range<Long> longRange(String range); static Range<LocalDateTime> localDateTimeRange(String range); static Range<LocalDate> localDateRange(String range); static Range<ZonedDateTime> zonedDateTimeRange(String rangeStr); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean hasMask(int flag); boolean isLowerBoundClosed(); boolean isUpperBoundClosed(); boolean hasLowerBound(); boolean hasUpperBound(); T lower(); T upper(); @SuppressWarnings("unchecked") boolean contains(T point); boolean contains(Range<T> range); String asString(); static Range<R> emptyRange(Class<R> clazz); static final int LOWER_INCLUSIVE; static final int LOWER_EXCLUSIVE; static final int UPPER_INCLUSIVE; static final int UPPER_EXCLUSIVE; static final int LOWER_INFINITE; static final int UPPER_INFINITE; static final String EMPTY; static final String INFINITY; }### Answer:
@Test public void localDateTimeTest() { assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.1,)")); assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.12,)")); assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.123,)")); assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.1234,)")); assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.12345,)")); assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.123456,)")); assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.123456,infinity)")); } |
### Question:
PostgreSQLGuavaRangeType extends ImmutableType<Range> implements DynamicParameterizedType { public static Range<Integer> integerRange(String range) { return ofString(range, Integer::parseInt, Integer.class); } PostgreSQLGuavaRangeType(); @Override int[] sqlTypes(); @SuppressWarnings("unchecked") static Range<T> ofString(String str, Function<String, T> converter, Class<T> cls); static Range<BigDecimal> bigDecimalRange(String range); static Range<Integer> integerRange(String range); static Range<Long> longRange(String range); static Range<LocalDateTime> localDateTimeRange(String range); static Range<LocalDate> localDateRange(String range); static Range<ZonedDateTime> zonedDateTimeRange(String rangeStr); String asString(Range range); @Override void setParameterValues(Properties parameters); Class<?> getElementType(); static final PostgreSQLGuavaRangeType INSTANCE; }### Answer:
@Test public void testUnboundedRangeStringIsRejected() { try { PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; instance.integerRange("(,)"); fail("An unbounded range string should throw an exception!"); } catch (Exception e) { IllegalArgumentException rootCause = ExceptionUtil.rootCause(e); assertTrue(rootCause.getMessage().contains("Cannot find bound type")); } } |
### Question:
SQLExtractor { public static String from(Query query) { AbstractQueryImpl abstractQuery = query.unwrap(AbstractQueryImpl.class); SessionImplementor session = ReflectionUtils.getFieldValue(abstractQuery, "session"); String[] sqls = session.getFactory() .getQueryPlanCache() .getHQLQueryPlan(abstractQuery.getQueryString(), false, Collections.<String, Filter>emptyMap()) .getSqlStrings(); return sqls.length > 0 ? sqls[0] : null; } private SQLExtractor(); static String from(Query query); }### Answer:
@Test public void testJPQL() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Query query = entityManager .createQuery( "select " + " YEAR(p.createdOn) as year, " + " count(p) as postCount " + "from " + " Post p " + "group by " + " YEAR(p.createdOn)", Tuple.class); String sql = SQLExtractor.from(query); assertNotNull(sql); LOGGER.info("SQL query: {}", sql); return null; } }); }
@Test public void testCriteriaAPI() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<PostComment> criteria = builder.createQuery(PostComment.class); Root<PostComment> postComment = criteria.from(PostComment.class); Join<PostComment, Post> post = postComment.join("post"); Path<String> postTitle = post.get("title"); criteria.where( builder.like(postTitle, "%Java%") ); criteria.orderBy( builder.asc(postComment.get("id")) ); Query query = entityManager.createQuery(criteria); String sql = SQLExtractor.from(query); assertNotNull(sql); LOGGER.info("SQL query: {}", sql); return null; } }); } |
### Question:
PostgreSQLGuavaRangeType extends ImmutableType<Range> { public static Range<Integer> integerRange(String range) { return ofString(range, new Function<String, Integer>() { @Override public Integer apply(String s) { return Integer.parseInt(s); } }, Integer.class); } PostgreSQLGuavaRangeType(); @Override int[] sqlTypes(); @SuppressWarnings("unchecked") static Range<T> ofString(String str, Function<String, T> converter, Class<T> cls); static Range<BigDecimal> bigDecimalRange(String range); static Range<Integer> integerRange(String range); static Range<Long> longRange(String range); String asString(Range range); static final PostgreSQLGuavaRangeType INSTANCE; }### Answer:
@Test public void testUnboundedRangeStringIsRejected() { try { PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; instance.integerRange("(,)"); fail("An unbounded range string should throw an exception!"); } catch (Exception e) { Throwable rootCause = Throwables.getRootCause(e); assertTrue(rootCause instanceof IllegalArgumentException); assertTrue(rootCause.getMessage().contains("Cannot find bound type")); } } |
### Question:
AuthorizationsCollector implements IAuthorizator { protected Authorization parseAuthLine(String line) throws ParseException { String[] tokens = line.split("\\s+"); String keyword = tokens[0].toLowerCase(); switch (keyword) { case "topic": return createAuthorization(line, tokens); case "user": m_parsingUsersSpecificSection = true; m_currentUser = tokens[1]; m_parsingPatternSpecificSection = false; return null; case "pattern": m_parsingUsersSpecificSection = false; m_currentUser = ""; m_parsingPatternSpecificSection = true; return createAuthorization(line, tokens); default: throw new ParseException(String.format("invalid line definition found %s", line), 1); } } @Override boolean canWrite(Topic topic, String user, String client); @Override boolean canRead(Topic topic, String user, String client); boolean isEmpty(); }### Answer:
@Test public void testParseAuthLineValid() throws ParseException { Authorization authorization = authorizator.parseAuthLine("topic /weather/italy/anemometer"); assertEquals(RW_ANEMOMETER, authorization); }
@Test public void testParseAuthLineValid_read() throws ParseException { Authorization authorization = authorizator.parseAuthLine("topic read /weather/italy/anemometer"); assertEquals(R_ANEMOMETER, authorization); }
@Test public void testParseAuthLineValid_write() throws ParseException { Authorization authorization = authorizator.parseAuthLine("topic write /weather/italy/anemometer"); assertEquals(W_ANEMOMETER, authorization); }
@Test public void testParseAuthLineValid_readwrite() throws ParseException { Authorization authorization = authorizator.parseAuthLine("topic readwrite /weather/italy/anemometer"); assertEquals(RW_ANEMOMETER, authorization); }
@Test public void testParseAuthLineValid_topic_with_space() throws ParseException { Authorization expected = new Authorization(new Topic("/weather/eastern italy/anemometer")); Authorization authorization = authorizator.parseAuthLine("topic readwrite /weather/eastern italy/anemometer"); assertEquals(expected, authorization); }
@Test(expected = ParseException.class) public void testParseAuthLineValid_invalid() throws ParseException { authorizator.parseAuthLine("topic faker /weather/italy/anemometer"); } |
### Question:
ACLFileParser { public static AuthorizationsCollector parse(File file) throws ParseException { if (file == null) { LOG.warn("parsing NULL file, so fallback on default configuration!"); return AuthorizationsCollector.emptyImmutableCollector(); } if (!file.exists()) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath())); return AuthorizationsCollector.emptyImmutableCollector(); } try { FileReader reader = new FileReader(file); return parse(reader); } catch (FileNotFoundException fex) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex); return AuthorizationsCollector.emptyImmutableCollector(); } } private ACLFileParser(); static AuthorizationsCollector parse(File file); static AuthorizationsCollector parse(Reader reader); }### Answer:
@Test public void testParseEmpty() throws ParseException { Reader conf = new StringReader(" "); AuthorizationsCollector authorizations = ACLFileParser.parse(conf); assertTrue(authorizations.isEmpty()); }
@Test public void testParseValidComment() throws ParseException { Reader conf = new StringReader("#simple comment"); AuthorizationsCollector authorizations = ACLFileParser.parse(conf); assertTrue(authorizations.isEmpty()); }
@Test(expected = ParseException.class) public void testParseInvalidComment() throws ParseException { Reader conf = new StringReader(" #simple comment"); ACLFileParser.parse(conf); }
@Test public void testParseSingleLineACL() throws ParseException { Reader conf = new StringReader("topic /weather/italy/anemometer"); AuthorizationsCollector authorizations = ACLFileParser.parse(conf); assertTrue(authorizations.canRead(new Topic("/weather/italy/anemometer"), "", "")); assertTrue(authorizations.canWrite(new Topic("/weather/italy/anemometer"), "", "")); } |
### Question:
ConfigurationParser { void parse(File file) throws ParseException { if (file == null) { LOG.warn("parsing NULL file, so fallback on default configuration!"); return; } if (!file.exists()) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath())); return; } try { FileReader reader = new FileReader(file); parse(reader); } catch (FileNotFoundException fex) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex); return; } } }### Answer:
@Test(expected = ParseException.class) public void parseInvalidComment() throws ParseException { Reader conf = new StringReader(" #simple comment"); m_parser.parse(conf); } |
### Question:
BrokerInterceptor implements Interceptor { @Override public void notifyClientConnected(final MqttConnectMessage msg) { for (final InterceptHandler handler : this.handlers.get(InterceptConnectMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Sending MQTT CONNECT message to interceptor. CId={}, interceptorId={}", msg.payload().clientIdentifier(), handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onConnect(new InterceptConnectMessage(msg)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }### Answer:
@Test public void testNotifyClientConnected() throws Exception { interceptor.notifyClientConnected(MqttMessageBuilders.connect().build()); interval(); assertEquals(40, n.get()); } |
### Question:
BrokerInterceptor implements Interceptor { @Override public void notifyClientDisconnected(final String clientID, final String username) { for (final InterceptHandler handler : this.handlers.get(InterceptDisconnectMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Notifying MQTT client disconnection to interceptor. CId={}, username={}, interceptorId={}", clientID, username, handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onDisconnect(new InterceptDisconnectMessage(clientID, username)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }### Answer:
@Test public void testNotifyClientDisconnected() throws Exception { interceptor.notifyClientDisconnected("cli1234", "cli1234"); interval(); assertEquals(50, n.get()); } |
### Question:
BrokerInterceptor implements Interceptor { @Override public void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username) { int messageId = msg.getMessageId(); String topic = msg.getTopic(); for (final InterceptHandler handler : this.handlers.get(InterceptPublishMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Notifying MQTT PUBLISH message to interceptor. CId={}, messageId={}, topic={}, interceptorId={}", clientID, messageId, topic, handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onPublish(new InterceptPublishMessage(msg, clientID, username)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }### Answer:
@Test public void testNotifyTopicPublished() throws Exception { MqttPublishMessage msg = MqttMessageBuilders.publish().qos(MqttQoS.AT_MOST_ONCE).payload(Unpooled.copiedBuffer("Hello".getBytes())).build(); MoquetteMessage moquetteMessage = new MoquetteMessage(msg.fixedHeader(), msg.variableHeader(), msg.content()); interceptor.notifyTopicPublished(moquetteMessage, "cli1234", "cli1234"); interval(); assertEquals(60, n.get()); } |
### Question:
BrokerInterceptor implements Interceptor { @Override public void notifyTopicSubscribed(final Subscription sub, final String username) { for (final InterceptHandler handler : this.handlers.get(InterceptSubscribeMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Notifying MQTT SUBSCRIBE message to interceptor. CId={}, topicFilter={}, interceptorId={}", sub.getClientId(), sub.getTopicFilter(), handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onSubscribe(new InterceptSubscribeMessage(sub, username)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }### Answer:
@Test public void testNotifyTopicSubscribed() throws Exception { interceptor.notifyTopicSubscribed(new Subscription("cli1", new Topic("o2"), MqttQoS.AT_MOST_ONCE), "cli1234"); interval(); assertEquals(70, n.get()); } |
### Question:
BrokerInterceptor implements Interceptor { @Override public void notifyTopicUnsubscribed(final String topic, final String clientID, final String username) { for (final InterceptHandler handler : this.handlers.get(InterceptUnsubscribeMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Notifying MQTT UNSUBSCRIBE message to interceptor. CId={}, topic={}, interceptorId={}", clientID, topic, handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onUnsubscribe(new InterceptUnsubscribeMessage(topic, clientID, username)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }### Answer:
@Test public void testNotifyTopicUnsubscribed() throws Exception { interceptor.notifyTopicUnsubscribed("o2", "cli1234", "cli1234"); interval(); assertEquals(80, n.get()); } |
### Question:
MapDBPersistentStore implements IStore { @Override public void close() { if (this.m_db.isClosed()) { LOG.warn("MapDB store is already closed. Nothing will be done"); return; } LOG.info("Performing last commit to MapDB"); this.m_db.commit(); LOG.info("Closing MapDB store"); this.m_db.close(); LOG.info("Stopping MapDB commit tasks"); this.m_scheduler.shutdown(); try { m_scheduler.awaitTermination(10L, TimeUnit.SECONDS); } catch (InterruptedException e) { } if (!m_scheduler.isTerminated()) { LOG.warn("Forcing shutdown of MapDB commit tasks"); m_scheduler.shutdown(); } LOG.info("MapDB store has been closed successfully"); } MapDBPersistentStore(IConfig props); @Override IMessagesStore messagesStore(); @Override ISessionsStore sessionsStore(); @Override void initStore(); @Override void close(); }### Answer:
@Test public void testCloseShutdownCommitTask() throws InterruptedException { m_storageService.close(); assertTrue("Storage service scheduler can't be stopped in 3 seconds", m_storageService.m_scheduler.awaitTermination(3, TimeUnit.SECONDS)); assertTrue(m_storageService.m_scheduler.isTerminated()); } |
### Question:
ProtocolProcessor { public void processUnsubscribe(Channel channel, MqttUnsubscribeMessage msg) { List<String> topics = msg.payload().topics(); String clientID = NettyUtils.clientID(channel); LOG.info("Processing UNSUBSCRIBE message. CId={}, topics={}", clientID, topics); ClientSession clientSession = m_sessionsStore.sessionForClient(clientID); for (String t : topics) { Topic topic = new Topic(t); boolean validTopic = topic.isValid(); if (!validTopic) { channel.close(); LOG.error("Topic filter is not valid. CId={}, topics={}, badTopicFilter={}", clientID, topics, topic); return; } if(LOG.isDebugEnabled()){ LOG.debug("Removing subscription. CId={}, topic={}", clientID, topic); } subscriptions.removeSubscription(topic, clientID); clientSession.unsubscribeFrom(topic); String username = NettyUtils.userName(channel); m_interceptor.notifyTopicUnsubscribed(topic.toString(), clientID, username); } int messageID = msg.variableHeader().messageId(); MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.UNSUBACK, false, AT_LEAST_ONCE, false, 0); MqttUnsubAckMessage ackMessage = new MqttUnsubAckMessage(fixedHeader, from(messageID)); LOG.info("Sending UNSUBACK message. CId={}, topics={}, messageId={}", clientID, topics, messageID); channel.writeAndFlush(ackMessage); } ProtocolProcessor(); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, IAuthorizator authorizator,
BrokerInterceptor interceptor); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
IAuthorizator authorizator, BrokerInterceptor interceptor); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort); void processConnect(Channel channel, MqttConnectMessage msg); void processPubAck(Channel channel, MqttPubAckMessage msg); static IMessagesStore.StoredMessage asStoredMessage(MqttPublishMessage msg); void processPublish(Channel channel, MqttPublishMessage msg); void internalPublish(MqttPublishMessage msg, final String clientId); void processPubRel(Channel channel, MqttMessage msg); void processPubRec(Channel channel, MqttMessage msg); void processPubComp(Channel channel, MqttMessage msg); void processDisconnect(Channel channel); void processConnectionLost(String clientID, Channel channel); void processUnsubscribe(Channel channel, MqttUnsubscribeMessage msg); void processSubscribe(Channel channel, MqttSubscribeMessage msg); void notifyChannelWritable(Channel channel); void addInterceptHandler(InterceptHandler interceptHandler); void removeInterceptHandler(InterceptHandler interceptHandler); IMessagesStore getMessagesStore(); ISessionsStore getSessionsStore(); }### Answer:
@Test public void testUnsubscribeWithBadFormattedTopic() { MqttUnsubscribeMessage msg = MqttMessageBuilders.unsubscribe().addTopicFilter(BAD_FORMATTED_TOPIC).messageId(1) .build(); m_processor.processUnsubscribe(m_channel, msg); assertFalse("If client unsubscribe with bad topic than channel must be closed", m_channel.isOpen()); } |
### Question:
ProtocolProcessor { static MqttQoS lowerQosToTheSubscriptionDesired(Subscription sub, MqttQoS qos) { if (qos.value() > sub.getRequestedQos().value()) { qos = sub.getRequestedQos(); } return qos; } ProtocolProcessor(); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, IAuthorizator authorizator,
BrokerInterceptor interceptor); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
IAuthorizator authorizator, BrokerInterceptor interceptor); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort); void processConnect(Channel channel, MqttConnectMessage msg); void processPubAck(Channel channel, MqttPubAckMessage msg); static IMessagesStore.StoredMessage asStoredMessage(MqttPublishMessage msg); void processPublish(Channel channel, MqttPublishMessage msg); void internalPublish(MqttPublishMessage msg, final String clientId); void processPubRel(Channel channel, MqttMessage msg); void processPubRec(Channel channel, MqttMessage msg); void processPubComp(Channel channel, MqttMessage msg); void processDisconnect(Channel channel); void processConnectionLost(String clientID, Channel channel); void processUnsubscribe(Channel channel, MqttUnsubscribeMessage msg); void processSubscribe(Channel channel, MqttSubscribeMessage msg); void notifyChannelWritable(Channel channel); void addInterceptHandler(InterceptHandler interceptHandler); void removeInterceptHandler(InterceptHandler interceptHandler); IMessagesStore getMessagesStore(); ISessionsStore getSessionsStore(); }### Answer:
@Test public void testLowerTheQosToTheRequestedBySubscription() { Subscription subQos1 = new Subscription("Sub A", new Topic("a/b"), MqttQoS.AT_LEAST_ONCE); assertEquals(MqttQoS.AT_LEAST_ONCE, lowerQosToTheSubscriptionDesired(subQos1, MqttQoS.EXACTLY_ONCE)); Subscription subQos2 = new Subscription("Sub B", new Topic("a/+"), MqttQoS.EXACTLY_ONCE); assertEquals(MqttQoS.EXACTLY_ONCE, lowerQosToTheSubscriptionDesired(subQos2, MqttQoS.EXACTLY_ONCE)); } |
### Question:
DBAuthenticator implements IAuthenticator { @Override public synchronized boolean checkValid(String clientId, String username, byte[] password) { if (username == null || password == null) { LOG.info("username or password was null"); return false; } ResultSet r = null; try { this.preparedStatement.setString(1, username); r = this.preparedStatement.executeQuery(); if (r.next()) { final String foundPwq = r.getString(1); messageDigest.update(password); byte[] digest = messageDigest.digest(); String encodedPasswd = new String(Hex.encodeHex(digest)); return foundPwq.equals(encodedPasswd); } r.close(); } catch (SQLException e) { e.printStackTrace(); } return false; } DBAuthenticator(IConfig conf); DBAuthenticator(String driver, String jdbcUrl, String sqlQuery, String digestMethod); @Override synchronized boolean checkValid(String clientId, String username, byte[] password); }### Answer:
@Test public void Db_verifyValid() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertTrue(dbAuthenticator.checkValid(null, "dbuser", "password".getBytes())); }
@Test public void Db_verifyInvalidLogin() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertFalse(dbAuthenticator.checkValid(null, "dbuser2", "password".getBytes())); }
@Test public void Db_verifyInvalidPassword() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertFalse(dbAuthenticator.checkValid(null, "dbuser", "wrongPassword".getBytes())); } |
### Question:
ChainingPrincipalResolver implements PrincipalResolver { public boolean supports(final Credential credential) { return this.chain.get(0).supports(credential); } void setChain(final List<PrincipalResolver> chain); Principal resolve(final Credential credential); boolean supports(final Credential credential); }### Answer:
@Test public void testSupports() throws Exception { final Credential credential = mock(Credential.class); when(credential.getId()).thenReturn("a"); final PrincipalResolver resolver1 = mock(PrincipalResolver.class); when(resolver1.supports(eq(credential))).thenReturn(true); final PrincipalResolver resolver2 = mock(PrincipalResolver.class); when(resolver2.supports(eq(credential))).thenReturn(false); final ChainingPrincipalResolver resolver = new ChainingPrincipalResolver(); resolver.setChain(Arrays.asList(resolver1, resolver2)); assertTrue(resolver.supports(credential)); } |
### Question:
ChainingPrincipalResolver implements PrincipalResolver { public Principal resolve(final Credential credential) { Principal result = null; Credential input = credential; for (final PrincipalResolver resolver : this.chain) { if (result != null) { input = new IdentifiableCredential(result.getId()); } result = resolver.resolve(input); } return result; } void setChain(final List<PrincipalResolver> chain); Principal resolve(final Credential credential); boolean supports(final Credential credential); }### Answer:
@Test public void testResolve() throws Exception { final Credential credential = mock(Credential.class); when(credential.getId()).thenReturn("input"); final PrincipalResolver resolver1 = mock(PrincipalResolver.class); when(resolver1.supports(eq(credential))).thenReturn(true); when(resolver1.resolve((eq(credential)))).thenReturn(new SimplePrincipal("output")); final PrincipalResolver resolver2 = mock(PrincipalResolver.class); when(resolver2.supports(any(Credential.class))).thenReturn(false); when(resolver2.resolve(argThat(new ArgumentMatcher<Credential>() { @Override public boolean matches(final Object o) { return ((Credential) o).getId().equals("output"); } }))).thenReturn( new SimplePrincipal("final", Collections.<String, Object>singletonMap("mail", "[email protected]"))); final ChainingPrincipalResolver resolver = new ChainingPrincipalResolver(); resolver.setChain(Arrays.asList(resolver1, resolver2)); final Principal principal = resolver.resolve(credential); assertEquals("final", principal.getId()); assertEquals("[email protected]", principal.getAttributes().get("mail")); } |
### Question:
LegacyAuthenticationHandlerAdapter implements AuthenticationHandler { @Override public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException, PreventedException { try { if (this.legacyHandler.authenticate(credentialsAdapter.convert(credential))) { final CredentialMetaData md; if (credential instanceof CredentialMetaData) { md = (CredentialMetaData) credential; } else { md = new BasicCredentialMetaData(credential); } return new HandlerResult(this, md); } else { throw new FailedLoginException( String.format("%s failed to authenticate %s", this.getName(), credential)); } } catch (final AuthenticationException e) { throw new GeneralSecurityException( String.format("%s failed to authenticate %s", this.getName(), credential), e); } } LegacyAuthenticationHandlerAdapter(final org.jasig.cas.authentication.handler.AuthenticationHandler legacy); LegacyAuthenticationHandlerAdapter(
final org.jasig.cas.authentication.handler.AuthenticationHandler legacy,
final CredentialsAdapter adapter); @Override HandlerResult authenticate(final Credential credential); @Override boolean supports(final Credential credential); @Override String getName(); }### Answer:
@Test public void testAuthenticateSuccess() throws Exception { final HandlerResult result = alwaysPassHandler.authenticate(new UsernamePasswordCredential("a", "b")); assertEquals("TestAlwaysPassAuthenticationHandler", result.getHandlerName()); }
@Test(expected = FailedLoginException.class) public void testAuthenticateFailure() throws Exception { alwaysFailHandler.authenticate(new UsernamePasswordCredential("a", "b")); } |
### Question:
JRadiusServerImpl implements RadiusServer { @Override public boolean authenticate(final String username, final String password) throws PreventedException { final AttributeList attributeList = new AttributeList(); attributeList.add(new Attr_UserName(username)); attributeList.add(new Attr_UserPassword(password)); RadiusClient client = null; try { client = this.radiusClientFactory.newInstance(); LOGGER.debug("Created RADIUS client instance {}", client); final AccessRequest request = new AccessRequest(client, attributeList); final RadiusPacket response = client.authenticate( request, RadiusClient.getAuthProtocol(this.protocol.getName()), this.retries); LOGGER.debug("RADIUS response from {}: {}", client.getRemoteInetAddress().getCanonicalHostName(), response.getClass().getName()); if (response instanceof AccessAccept) { return true; } } catch (final Exception e) { throw new PreventedException(e); } finally { if (client != null) { client.close(); } } return false; } JRadiusServerImpl(final RadiusProtocol protocol, final RadiusClientFactory clientFactory); @Override boolean authenticate(final String username, final String password); void setRetries(final int retries); static final int DEFAULT_RETRY_COUNT; }### Answer:
@Test public void testAuthenticate() { assertNotNull(this.radiusServer); } |
### Question:
SmartOpenIdController extends DelegateController implements Serializable { @Override public boolean canHandle(final HttpServletRequest request, final HttpServletResponse response) { String openIdMode = request.getParameter("openid.mode"); if (openIdMode != null && openIdMode.equals("associate")) { logger.info("Handling request. openid.mode : {}", openIdMode); return true; } logger.info("Cannot handle request. openid.mode : {}", openIdMode); return false; } Map<String, String> getAssociationResponse(final HttpServletRequest request); @Override boolean canHandle(final HttpServletRequest request, final HttpServletResponse response); void setSuccessView(final String successView); void setFailureView(final String failureView); @NotNull void setServerManager(final ServerManager serverManager); }### Answer:
@Test public void testCanHandle() { request.addParameter("openid.mode", "associate"); boolean canHandle = smartOpenIdController.canHandle(request, response); request.removeParameter("openid.mode"); assertEquals(true, canHandle); }
@Test public void testCannotHandle() { request.addParameter("openid.mode", "anythingElse"); boolean canHandle = smartOpenIdController.canHandle(request, response); request.removeParameter("openid.mode"); assertEquals(false, canHandle); } |
### Question:
SmartOpenIdController extends DelegateController implements Serializable { public Map<String, String> getAssociationResponse(final HttpServletRequest request) { ParameterList parameters = new ParameterList(request.getParameterMap()); final String mode = parameters.hasParameter("openid.mode") ? parameters.getParameterValue("openid.mode") : null; Message response = null; if (mode != null && mode.equals("associate")) { response = serverManager.associationResponse(parameters); } final Map<String, String> responseParams = new HashMap<String, String>(); if (response != null) { responseParams.putAll(response.getParameterMap()); } return responseParams; } Map<String, String> getAssociationResponse(final HttpServletRequest request); @Override boolean canHandle(final HttpServletRequest request, final HttpServletResponse response); void setSuccessView(final String successView); void setFailureView(final String failureView); @NotNull void setServerManager(final ServerManager serverManager); }### Answer:
@Test public void testGetAssociationResponse() { request.addParameter("openid.mode", "associate"); request.addParameter("openid.session_type", "DH-SHA1"); request.addParameter("openid.assoc_type", "HMAC-SHA1"); request.addParameter("openid.dh_consumer_public", "NzKoFMyrzFn/5iJFPdX6MVvNA/BChV1/sJdnYbupDn7ptn+cerwEzyFfWFx25KsoLSkxQCaSMmYtc1GPy/2GI1BSKSDhpdJmDBb" + "QRa/9Gs+giV/5fHcz/mHz8sREc7RTGI+0Ka9230arwrWt0fnoaJLRKEGUsmFR71rCo4EUOew="); Map<String, String> assocResponse = smartOpenIdController.getAssociationResponse(request); assertTrue(assocResponse.containsKey("assoc_handle")); assertTrue(assocResponse.containsKey("expires_in")); assertTrue(assocResponse.containsKey("dh_server_public")); assertTrue(assocResponse.containsKey("enc_mac_key")); request.removeParameter("openid.mode"); } |
### Question:
AvailableForm extends BaseForm { public boolean isRegistrationForm(){ return Constants.FORM_DISCRIMINATOR_REGISTRATION.equalsIgnoreCase(getDiscriminator()) || Constants.FORM_JSON_DISCRIMINATOR_REGISTRATION.equalsIgnoreCase(getDiscriminator()) || Constants.FORM_JSON_DISCRIMINATOR_GENERIC_REGISTRATION.equalsIgnoreCase(getDiscriminator()) || Constants.FORM_JSON_DISCRIMINATOR_SHR_REGISTRATION.equalsIgnoreCase(getDiscriminator()); } Tag[] getTags(); void setTags(Tag[] tags); boolean isDownloaded(); void setDownloaded(boolean downloaded); boolean isRegistrationForm(); boolean isProviderReport(); boolean isRelationshipForm(); }### Answer:
@Test public void shouldReturnFalseIfHasNoRegistrationDiscriminator() { AvailableForm availableForm = new AvailableForm(); assertFalse(availableForm.isRegistrationForm()); for(String discriminator: nonRegistrationDiscriminators) { availableForm.setDiscriminator(discriminator); assertFalse(availableForm.isRegistrationForm()); } }
@Test public void shouldReturnTrueIfHasRegistrationDiscriminator() { AvailableForm availableForm = new AvailableForm(); for(String discriminator: registrationDiscriminators) { availableForm.setDiscriminator(discriminator); assertTrue(availableForm.isRegistrationForm()); } } |
### Question:
LocationController { public List<Location> downloadLocationFromServerByName(String name) throws LocationDownloadException { try { return locationService.downloadLocationsByName(name); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error while searching for patients in the server", e); throw new LocationDownloadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }### Answer:
@Test public void shouldSearchOnServerForLocationsByNames() throws Exception, LocationController.LocationDownloadException { String name = "name"; List<Location> locations = new ArrayList<>(); when(locationService.downloadLocationsByName(name)).thenReturn(locations); assertThat(locationController.downloadLocationFromServerByName(name), is(locations)); verify(locationService).downloadLocationsByName(name); }
@Test(expected = LocationController.LocationDownloadException.class) public void shouldReturnEmptyListIsExceptionThrown() throws Exception, LocationController.LocationDownloadException { String searchString = "name"; doThrow(new IOException()).when(locationService).downloadLocationsByName(searchString); assertThat(locationController.downloadLocationFromServerByName(searchString).size(), is(0)); } |
### Question:
LocationController { public Location downloadLocationFromServerByUuid(String uuid) throws LocationDownloadException { try { return locationService.downloadLocationByUuid(uuid); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error while searching for patients in the server", e); throw new LocationDownloadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }### Answer:
@Test public void shouldSearchOnServerForLocationByUuid() throws Exception, LocationController.LocationDownloadException { String uuid = "uuid"; Location location = new Location(); when(locationService.downloadLocationByUuid(uuid)).thenReturn(location); assertThat(locationController.downloadLocationFromServerByUuid(uuid), is(location)); verify(locationService).downloadLocationByUuid(uuid); } |
### Question:
LocationController { public List<Location> getAllLocations() throws LocationLoadException { try { return locationService.getAllLocations(); } catch (IOException e) { throw new LocationLoadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }### Answer:
@Test public void getAllLocations_shouldReturnAllAvailableLocations() throws IOException, LocationController.LocationLoadException { List<Location> locations = new ArrayList<>(); when(locationService.getAllLocations()).thenReturn(locations); assertThat(locationController.getAllLocations(), is(locations)); }
@Test(expected = LocationController.LocationLoadException.class) public void getAllLocations_shouldThrowLoLocationFetchExceptionIfExceptionThrownByLocationService() throws IOException, LocationController.LocationLoadException { doThrow(new IOException()).when(locationService).getAllLocations(); locationController.getAllLocations(); } |
### Question:
LocationController { public Location getLocationByUuid(String uuid) throws LocationLoadException { try { return locationService.getLocationByUuid(uuid); } catch (IOException e) { throw new LocationLoadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }### Answer:
@Test public void getLocationByUuid_shouldReturnLocationForId() throws Exception, LocationController.LocationLoadException { Location location = new Location(); String uuid = "uuid"; when(locationService.getLocationByUuid(uuid)).thenReturn(location); assertThat(locationController.getLocationByUuid(uuid), is(location)); } |
### Question:
ConceptController { public List<Concept> downloadConceptsByNames(List<String> names) throws ConceptDownloadException { HashSet<Concept> result = new HashSet<>(); for (String name : names) { List<Concept> concepts = downloadConceptsByNamePrefix(name); Iterator<Concept> iterator = concepts.iterator(); while (iterator.hasNext()) { Concept next = iterator.next(); if (next == null || !next.containsNameIgnoreLowerCase(name)) { iterator.remove(); } } result.addAll(concepts); } return new ArrayList<>(result); } ConceptController(ConceptService conceptService, ObservationService observationService); List<Concept> downloadConceptsByNamePrefix(String name); void deleteConcept(Concept concept); void deleteConcepts(List<Concept> concepts); void saveConcepts(List<Concept> concepts); Concept getConceptByName(String name); Concept getConceptById(int id); Concept getConceptByUuid(String uuid); List<Concept> downloadConceptsByNames(List<String> names); List<Concept> downloadConceptsByUuid(String[] uuids); List<Concept> searchConceptsLocallyByNamePrefix(String prefix); List<Concept> getConcepts(); void newConcepts(List<Concept> concepts); void resetNewConceptsList(); List<Concept> newConcepts(); List<Concept> getRelatedConcepts(List<FormTemplate> formTemplates); void deleteAllConcepts(); }### Answer:
@Test public void shouldDownloadConceptUsingNonPreferredName() throws Exception, ConceptController.ConceptDownloadException { List<Concept> concepts = new ArrayList<>(); final String nonPreferredName = "NonPreferredName"; Concept aConcept = new Concept() {{ setConceptNames(new ArrayList<ConceptName>() {{ add(new ConceptName() {{ setName("PreferredName"); setPreferred(true); }}); add(new ConceptName() {{ setName(nonPreferredName); setPreferred(false); }}); }}); }}; concepts.add(aConcept); when(service.downloadConceptsByName(nonPreferredName)).thenReturn(concepts); List<String> listOfName = new ArrayList<String>() {{ add(nonPreferredName); }}; List<Concept> expectedResult = new ArrayList<>(); expectedResult.add(aConcept); assertThat(controller.downloadConceptsByNames(listOfName), is(expectedResult)); } |
### Question:
ConceptController { public Concept getConceptByName(String name) throws ConceptFetchException { try { List<Concept> concepts = conceptService.getConceptsByName(name); for (Concept concept : concepts) { if (concept.getName().equals(name)) { return concept; } } } catch (IOException e) { throw new ConceptFetchException(e); } return null; } ConceptController(ConceptService conceptService, ObservationService observationService); List<Concept> downloadConceptsByNamePrefix(String name); void deleteConcept(Concept concept); void deleteConcepts(List<Concept> concepts); void saveConcepts(List<Concept> concepts); Concept getConceptByName(String name); Concept getConceptById(int id); Concept getConceptByUuid(String uuid); List<Concept> downloadConceptsByNames(List<String> names); List<Concept> downloadConceptsByUuid(String[] uuids); List<Concept> searchConceptsLocallyByNamePrefix(String prefix); List<Concept> getConcepts(); void newConcepts(List<Concept> concepts); void resetNewConceptsList(); List<Concept> newConcepts(); List<Concept> getRelatedConcepts(List<FormTemplate> formTemplates); void deleteAllConcepts(); }### Answer:
@Test public void shouldReturnAConceptThatMatchesNameExactly() throws Exception, ConceptController.ConceptFetchException { String conceptName = "conceptName"; List<Concept> conceptList = asList(createConceptByName("someName"),createConceptByName(conceptName)); when(service.getConceptsByName(conceptName)).thenReturn(conceptList); Concept conceptByName = controller.getConceptByName(conceptName); assertThat(conceptByName.getName(),is(conceptName)); }
@Test public void shouldReturnNullIfNoConceptMatchesTheName() throws Exception, ConceptController.ConceptFetchException { String conceptName = "conceptName"; List<Concept> conceptList = asList(createConceptByName("someName"),createConceptByName("someOtherName")); when(service.getConceptsByName(conceptName)).thenReturn(conceptList); Concept conceptByName = controller.getConceptByName(conceptName); assertThat(conceptByName,nullValue()); } |
### Question:
ObservationController { public void saveObservations(List<Observation> observations) throws SaveObservationException { try { observationService.saveObservations(observations); } catch (IOException e) { throw new SaveObservationException(e); } } ObservationController(ObservationService observationService, ConceptService conceptService,
EncounterService encounterService, LastSyncTimeService lastSyncTimeService,
SntpService sntpService); Concepts getConceptWithObservations(String patientUuid); Concepts getConceptWithObservations(String patientUuid, String conceptUuid ); List<Observation> getObservationsByPatientuuidAndConceptId(String patientUuid,int conceptid); List<Observation> getObservationsByEncounterId(int encounterId); List<Observation> getObservationsByEncounterType(int encounterTypeId,String patientUuid); int getObservationsCountByPatient(String patientUuid); int getConceptColor(String uuid); void replaceObservations(List<Observation> allObservations); Concepts searchObservationsGroupedByConcepts(String term, String patientUuid); Encounters getEncountersWithObservations(String patientUuid); Encounters getObservationsByEncounterUuid(String encounterUuid); List<Observation> getObservationsByPatient(String patientUuid); Encounters searchObservationsGroupedByEncounter(String term, String patientUuid); List<Observation> downloadObservationsByPatientUuidsAndConceptUuids(List<String> patientUuids, List<String> conceptUuids); void saveObservations(List<Observation> observations); void deleteObservations(List<Observation> observations); void deleteAllObservations(List<Concept> concepts); }### Answer:
@Test public void saveObservations_shouldSaveObservationsForPatient() throws Exception, ObservationController.SaveObservationException { final Concept concept1 = new Concept() {{ setUuid("concept1"); }}; final Concept concept2 = new Concept() {{ setUuid("concept2"); }}; final List<Observation> observations = buildObservations(concept1, concept2); observationController.saveObservations(observations); verify(observationService).saveObservations(observations); } |
### Question:
CohortController { public List<Cohort> getAllCohorts() throws CohortFetchException { try { return cohortService.getAllCohorts(); } catch (IOException e) { throw new CohortFetchException(e); } } CohortController(CohortService cohortService, LastSyncTimeService lastSyncTimeService, SntpService sntpService, MuzimaApplication muzimaApplication); String getDefaultLocation(); Provider getLoggedInProvider(); List<Cohort> getAllCohorts(); int countAllCohorts(); List<Cohort> downloadAllCohorts(String defaultLocation); List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation); List<CohortData> downloadRemovedCohortData(String[] cohortUuids); CohortData downloadCohortDataByUuid(String uuid,String defaultLocation); CohortData downloadRemovedCohortDataByUuid(String uuid); List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation); void saveAllCohorts(List<Cohort> cohorts); void saveOrUpdateCohorts(List<Cohort> cohorts); void deleteAllCohorts(); void deleteCohorts(List<Cohort> cohorts); List<Cohort> getSyncedCohorts(); boolean isDownloaded(Cohort cohort); boolean isUpdateAvailable(); List<Cohort> getCohortsWithPendingUpdates(); void markAsUpToDate(String[] cohortUuids); void setSyncStatus(String[] cohortUuids); int countSyncedCohorts(); void deleteAllCohortMembers(String cohortUuid); void addCohortMembers(List<CohortMember> cohortMembers); int countCohortMembers(Cohort cohort); List<Cohort> downloadCohortByName(String name); List<Cohort> downloadCohortsByUuidList(String[] uuidList); List<CohortMember> getCohortMembershipByPatientUuid(String patientUuid); void deleteAllCohortMembers(List<Cohort> allCohorts); void deleteCohortMembers(List<CohortMember> cohortMembers); }### Answer:
@Test public void getAllCohorts_shouldReturnAllAvailableCohorts() throws IOException, CohortController.CohortFetchException { List<Cohort> cohorts = new ArrayList<>(); when(cohortService.getAllCohorts()).thenReturn(cohorts); assertThat(controller.getAllCohorts(), is(cohorts)); }
@Test(expected = CohortController.CohortFetchException.class) public void getAllCohorts_shouldThrowCohortFetchExceptionIfExceptionThrownByCohortService() throws IOException, CohortController.CohortFetchException { doThrow(new IOException()).when(cohortService).getAllCohorts(); controller.getAllCohorts(); doThrow(new ParseException()).when(cohortService).getAllCohorts(); controller.getAllCohorts(); } |
### Question:
CohortController { public List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation) throws CohortDownloadException { ArrayList<CohortData> allCohortData = new ArrayList<>(); for (String cohortUuid : cohortUuids) { allCohortData.add(downloadCohortDataByUuid(cohortUuid, defaulLocation)); } return allCohortData; } CohortController(CohortService cohortService, LastSyncTimeService lastSyncTimeService, SntpService sntpService, MuzimaApplication muzimaApplication); String getDefaultLocation(); Provider getLoggedInProvider(); List<Cohort> getAllCohorts(); int countAllCohorts(); List<Cohort> downloadAllCohorts(String defaultLocation); List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation); List<CohortData> downloadRemovedCohortData(String[] cohortUuids); CohortData downloadCohortDataByUuid(String uuid,String defaultLocation); CohortData downloadRemovedCohortDataByUuid(String uuid); List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation); void saveAllCohorts(List<Cohort> cohorts); void saveOrUpdateCohorts(List<Cohort> cohorts); void deleteAllCohorts(); void deleteCohorts(List<Cohort> cohorts); List<Cohort> getSyncedCohorts(); boolean isDownloaded(Cohort cohort); boolean isUpdateAvailable(); List<Cohort> getCohortsWithPendingUpdates(); void markAsUpToDate(String[] cohortUuids); void setSyncStatus(String[] cohortUuids); int countSyncedCohorts(); void deleteAllCohortMembers(String cohortUuid); void addCohortMembers(List<CohortMember> cohortMembers); int countCohortMembers(Cohort cohort); List<Cohort> downloadCohortByName(String name); List<Cohort> downloadCohortsByUuidList(String[] uuidList); List<CohortMember> getCohortMembershipByPatientUuid(String patientUuid); void deleteAllCohortMembers(List<Cohort> allCohorts); void deleteCohortMembers(List<CohortMember> cohortMembers); }### Answer:
@Test public void downloadCohortDataAndSyncDate_shouldDownloadDeltaCohortDataBySyncDate() throws IOException, CohortController.CohortDownloadException, ProviderController.ProviderLoadException { String[] uuids = new String[]{"uuid1", "uuid2"}; CohortData cohortData1 = new CohortData(); CohortData cohortData2 = new CohortData(); when(cohortService.downloadCohortDataAndSyncDate(uuids[0], false, null, null, null)).thenReturn(cohortData1); when(cohortService.downloadCohortDataAndSyncDate(uuids[1], false, null, null ,null)).thenReturn(cohortData2); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS_DATA, "uuid1")).thenReturn(null); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS_DATA, "uuid2")).thenReturn(null); List<CohortData> allCohortData = controller.downloadCohortData(uuids, null); assertThat(allCohortData.size(), is(2)); assertThat(allCohortData, hasItem(cohortData1)); assertThat(allCohortData, hasItem(cohortData2)); } |
### Question:
CohortController { public void saveAllCohorts(List<Cohort> cohorts) throws CohortSaveException { try { cohortService.saveCohorts(cohorts); } catch (IOException e) { throw new CohortSaveException(e); } } CohortController(CohortService cohortService, LastSyncTimeService lastSyncTimeService, SntpService sntpService, MuzimaApplication muzimaApplication); String getDefaultLocation(); Provider getLoggedInProvider(); List<Cohort> getAllCohorts(); int countAllCohorts(); List<Cohort> downloadAllCohorts(String defaultLocation); List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation); List<CohortData> downloadRemovedCohortData(String[] cohortUuids); CohortData downloadCohortDataByUuid(String uuid,String defaultLocation); CohortData downloadRemovedCohortDataByUuid(String uuid); List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation); void saveAllCohorts(List<Cohort> cohorts); void saveOrUpdateCohorts(List<Cohort> cohorts); void deleteAllCohorts(); void deleteCohorts(List<Cohort> cohorts); List<Cohort> getSyncedCohorts(); boolean isDownloaded(Cohort cohort); boolean isUpdateAvailable(); List<Cohort> getCohortsWithPendingUpdates(); void markAsUpToDate(String[] cohortUuids); void setSyncStatus(String[] cohortUuids); int countSyncedCohorts(); void deleteAllCohortMembers(String cohortUuid); void addCohortMembers(List<CohortMember> cohortMembers); int countCohortMembers(Cohort cohort); List<Cohort> downloadCohortByName(String name); List<Cohort> downloadCohortsByUuidList(String[] uuidList); List<CohortMember> getCohortMembershipByPatientUuid(String patientUuid); void deleteAllCohortMembers(List<Cohort> allCohorts); void deleteCohortMembers(List<CohortMember> cohortMembers); }### Answer:
@Test public void saveAllCohorts_shouldSaveAllCohorts() throws CohortController.CohortSaveException, IOException { ArrayList<Cohort> cohorts = new ArrayList<Cohort>() {{ add(new Cohort()); add(new Cohort()); add(new Cohort()); }}; controller.saveAllCohorts(cohorts); verify(cohortService).saveCohorts(cohorts); verifyNoMoreInteractions(cohortService); }
@Test(expected = CohortController.CohortSaveException.class) public void saveAllCohorts_shouldThrowCohortSaveExceptionIfExceptionThrownByCohortService() throws IOException, CohortController.CohortSaveException { ArrayList<Cohort> cohorts = new ArrayList<Cohort>() {{ add(new Cohort()); }}; doThrow(new IOException()).when(cohortService).saveCohorts(cohorts); controller.saveAllCohorts(cohorts); } |
### Question:
CohortController { public int countAllCohorts() throws CohortFetchException { try { return cohortService.countAllCohorts(); } catch (IOException e) { throw new CohortFetchException(e); } } CohortController(CohortService cohortService, LastSyncTimeService lastSyncTimeService, SntpService sntpService, MuzimaApplication muzimaApplication); String getDefaultLocation(); Provider getLoggedInProvider(); List<Cohort> getAllCohorts(); int countAllCohorts(); List<Cohort> downloadAllCohorts(String defaultLocation); List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation); List<CohortData> downloadRemovedCohortData(String[] cohortUuids); CohortData downloadCohortDataByUuid(String uuid,String defaultLocation); CohortData downloadRemovedCohortDataByUuid(String uuid); List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation); void saveAllCohorts(List<Cohort> cohorts); void saveOrUpdateCohorts(List<Cohort> cohorts); void deleteAllCohorts(); void deleteCohorts(List<Cohort> cohorts); List<Cohort> getSyncedCohorts(); boolean isDownloaded(Cohort cohort); boolean isUpdateAvailable(); List<Cohort> getCohortsWithPendingUpdates(); void markAsUpToDate(String[] cohortUuids); void setSyncStatus(String[] cohortUuids); int countSyncedCohorts(); void deleteAllCohortMembers(String cohortUuid); void addCohortMembers(List<CohortMember> cohortMembers); int countCohortMembers(Cohort cohort); List<Cohort> downloadCohortByName(String name); List<Cohort> downloadCohortsByUuidList(String[] uuidList); List<CohortMember> getCohortMembershipByPatientUuid(String patientUuid); void deleteAllCohortMembers(List<Cohort> allCohorts); void deleteCohortMembers(List<CohortMember> cohortMembers); }### Answer:
@Test public void getTotalCohortsCount_shouldReturnEmptyListOfNoCohortsHaveBeenSynced() throws IOException, CohortController.CohortFetchException { when(cohortService.countAllCohorts()).thenReturn(2); assertThat(controller.countAllCohorts(), is(2)); } |
### Question:
MuzimaProgressDialog { @JavascriptInterface public void show(String title) { dialog.setTitle(title); dialog.setMessage(dialog.getContext().getResources().getString(R.string.general_progress_message)); dialog.show(); } MuzimaProgressDialog(Activity activity); MuzimaProgressDialog(ProgressDialog dialog); @JavascriptInterface void show(String title); @JavascriptInterface void updateMessage(String message); @JavascriptInterface void dismiss(); }### Answer:
@Test public void shouldShowProgressDialogWithGivenText() { dialog.show("title"); Mockito.verify(progressDialog).setCancelable(false); Mockito.verify(progressDialog).setTitle("title"); Mockito.verify(progressDialog).setMessage("This might take a while"); Mockito.verify(progressDialog).show(); } |
### Question:
MuzimaProgressDialog { @JavascriptInterface public void dismiss() { if (dialog.isShowing()) { dialog.dismiss(); } } MuzimaProgressDialog(Activity activity); MuzimaProgressDialog(ProgressDialog dialog); @JavascriptInterface void show(String title); @JavascriptInterface void updateMessage(String message); @JavascriptInterface void dismiss(); }### Answer:
@Test public void shouldDismissADialogOnlyWhenVisible() { when(progressDialog.isShowing()).thenReturn(true); dialog.dismiss(); Mockito.verify(progressDialog).dismiss(); }
@Test public void shouldNotCallDismissIfProgressBarISNotVisible() { when(progressDialog.isShowing()).thenReturn(false); dialog.dismiss(); Mockito.verify(progressDialog, Mockito.never()).dismiss(); } |
### Question:
HTMLFormDataStore { @JavascriptInterface public void saveHTML(String jsonPayload, String status) { saveHTML(jsonPayload, status, false); } HTMLFormDataStore(HTMLFormWebViewActivity formWebViewActivity, FormData formData, boolean isFormReload, MuzimaApplication application); @JavascriptInterface String getStatus(); @JavascriptInterface void saveHTML(String jsonPayload, String status); @JavascriptInterface void saveHTML(String jsonPayload, String status, boolean keepFormOpen); @JavascriptInterface String getLocationNamesFromDevice(); @JavascriptInterface String getRelationshipTypesFromDevice(); @JavascriptInterface String getPatientDetailsFromServerByUuid(String uuid); @JavascriptInterface String getPersonDetailsFromDeviceByUuid(String uuid); @JavascriptInterface String searchPersons(String searchTerm, boolean searchServer); @JavascriptInterface String searchPersonsLocally(String searchTerm); @JavascriptInterface String searchPatientOnServer(String searchTerm); @JavascriptInterface String getProviderNamesFromDevice(); @JavascriptInterface String getDefaultEncounterProvider(); @JavascriptInterface String getFontSizePreference(); Date getEncounterDateFromForm(String jsonPayload); @JavascriptInterface String getStringResource(String stringResourceName); @JavascriptInterface String getConcepts(); @JavascriptInterface String getEncountersByPatientUuid(String patientuuid); @JavascriptInterface String getEncounterTypes(String patientuuid); @JavascriptInterface String getObsByConceptId(String patientUuid, int conceptId); @JavascriptInterface String getObsByEncounterId(int encounterid); @JavascriptInterface String getObsByEncounterType(String patientUuid, String encounterType); @JavascriptInterface boolean isMedicalRecordNumberRequired(); @JavascriptInterface void checkForPossibleFormDuplicate(String formUuid, String encounterDateTime, String patientUuid, String encounterPayLoad); @JavascriptInterface boolean getDefaultEncounterLocationSetting(); @JavascriptInterface String getDefaultEncounterLocationPreference(); @JavascriptInterface String getLastKnowGPSLocation(String jsonReturnType); @JavascriptInterface void logEvent(String tag, String details); @JavascriptInterface String getCohortMembershipByPatientUuid(String patientUuid); @JavascriptInterface void createPersonAndDiscardHTML(String jsonPayload); }### Answer:
@Test public void shouldNotParseIncompletedForm() throws SetupConfigurationController.SetupConfigurationFetchException { when(formWebViewActivity.getString(anyInt())).thenReturn("success"); SetupConfigurationTemplate setupConfigurationTemplate = new SetupConfigurationTemplate(); setupConfigurationTemplate.setUuid("dummySetupConfig"); when(setupConfigurationController.getActiveSetupConfigurationTemplate()).thenReturn(setupConfigurationTemplate); String jsonPayLoad = readFile(); htmlFormDataStore.saveHTML(jsonPayLoad, Constants.STATUS_INCOMPLETE); verify(htmlFormObservationCreator, times(0)).createAndPersistObservations(jsonPayLoad,formData.getUuid()); } |
### Question:
FormDataStore { @JavascriptInterface public String getFormPayload() { return formData.getJsonPayload(); } FormDataStore(FormWebViewActivity formWebViewActivity, FormController formController, FormData formData); @JavascriptInterface void save(String jsonData, String xmlData, String status); @JavascriptInterface String getFormPayload(); @JavascriptInterface String getFormStatus(); @JavascriptInterface void showSaveProgressBar(); }### Answer:
@Test public void getFormPayload_shouldGetTheFormDataPayload() { formData.setJsonPayload("payload"); assertThat(store.getFormPayload(), is("payload")); } |
### Question:
StringUtils { public static String getCommaSeparatedStringFromList(final List<String> values){ if(values == null){ return ""; } StringBuilder builder = new StringBuilder(); for (String next : values) { builder.append(next).append(","); } String commaSeparated = builder.toString(); return commaSeparated.substring(0, commaSeparated.length() - 1); } static String getCommaSeparatedStringFromList(final List<String> values); static List<String> getListFromCommaSeparatedString(String value); static boolean isEmpty(String string); static String defaultString(String string); static boolean equals(String str1, String str2); static boolean equalsIgnoreCase(String str1, String str2); static int nullSafeCompare(String str1, String str2); static final String EMPTY; }### Answer:
@Test public void shouldReturnCommaSeparatedList(){ ArrayList<String> listOfStrings = new ArrayList<String>() {{ add("Patient"); add("Registration"); add("New Tag"); }}; String commaSeparatedValues = StringUtils.getCommaSeparatedStringFromList(listOfStrings); assertThat(commaSeparatedValues, is("Patient,Registration,New Tag")); } |
### Question:
PatientComparator implements Comparator<Patient> { @Override public int compare(Patient patient1, Patient patient2) { if (patient1 == null) { patient1 = new Patient(); } if (patient2 == null) { patient2 = new Patient(); } int familyNameCompareResult = StringUtils.nullSafeCompare(patient1.getFamilyName(), patient2.getFamilyName()); if (familyNameCompareResult != 0) { return familyNameCompareResult; } int givenNameCompareResult = StringUtils.nullSafeCompare(patient1.getGivenName(), patient2.getGivenName()); if (givenNameCompareResult != 0) { return givenNameCompareResult; } return StringUtils.nullSafeCompare(patient1.getMiddleName(), patient2.getMiddleName()); } @Override int compare(Patient patient1, Patient patient2); }### Answer:
@Test public void shouldSortByFamilyName() { Patient obama = patient("Obama", "Barack", "Hussein", "id1"); Patient bush = patient("Bush", "George", "W", "id2"); assertTrue(patientComparator.compare(obama, bush) > 0); }
@Test public void shouldSortByGivenNameIfFamilyNameIsSame() { Patient barack = patient("Obama", "Barack", "Hussein", "id1"); Patient george = patient("Obama", "George", "W", "id2"); assertTrue(patientComparator.compare(barack, george) < 0); }
@Test public void shouldSortByMiddleNameIfGivenNameAndFamilyNameAreSame() { Patient hussein = patient("Obama", "Barack", "Hussein", "id1"); Patient william = patient("Obama", "Barack", "William", "id2"); assertTrue(patientComparator.compare(hussein, william) < 0); } |
### Question:
Concepts extends ArrayList<ConceptWithObservations> { public void sortByDate() { Collections.sort(this, new Comparator<ConceptWithObservations>() { @Override public int compare(ConceptWithObservations lhs, ConceptWithObservations rhs) { return -(lhs.getObservations().get(0).getObservationDatetime() .compareTo(rhs.getObservations().get(0).getObservationDatetime())); } }); } Concepts(); Concepts(Observation... observations); Concepts(List<Observation> observationsByPatient); void sortByDate(); }### Answer:
@Test public void shouldSortTheConceptsByDate() { final Observation observation1 = createObservation(createConcept("c1"), "01", new Date(1)); final Observation observation2 = createObservation(createConcept("c2"), "02", new Date(3)); final Observation observation3 = createObservation(createConcept("c1"), "03", new Date(2)); final Concepts concepts = new Concepts(observation1, observation2, observation3); concepts.sortByDate(); final Concepts expectedOrderedConcept = new Concepts() {{ add(conceptWithObservations(observation2)); add(conceptWithObservations(observation3, observation1)); }}; assertThat(concepts, is(expectedOrderedConcept)); } |
### Question:
Encounters extends ArrayList<EncounterWithObservations> { public void sortByDate() { Collections.sort(this, new Comparator<EncounterWithObservations>() { @Override public int compare(EncounterWithObservations lhs, EncounterWithObservations rhs) { if (lhs.getEncounter().getEncounterDatetime()==null) return -1; if (rhs.getEncounter().getEncounterDatetime()==null) return 1; return -(lhs.getEncounter().getEncounterDatetime() .compareTo(rhs.getEncounter().getEncounterDatetime())); } }); } Encounters(); Encounters(Observation... observations); Encounters(List<Observation> observationsByPatient); void sortByDate(); }### Answer:
@Test public void shouldSortTheEncountersByDate() { final Observation observation1 = createObservation(createEncounter("c1", new Date(1)), "01"); final Observation observation2 = createObservation(createEncounter("c2", new Date(3)), "02"); final Encounters encounters = new Encounters(observation1, observation2); encounters.sortByDate(); final Encounters expectedOrderedConcept = new Encounters() {{ add(encounterWithObservations(observation2)); add(encounterWithObservations(observation1)); }}; assertThat(encounters, is(expectedOrderedConcept)); }
@Test public void shouldPutEncounterWithNullDateAtTheTopWhenItsNotAtTheTop() { final Observation observation1 = createObservation(createEncounter("c1", new Date(1)), "01"); final Observation observation2 = createObservation(createEncounter("c2", null), "02"); final Encounters encounters = new Encounters(observation1, observation2); encounters.sortByDate(); final Encounters expectedOrderedConcept = new Encounters() {{ add(encounterWithObservations(observation2)); add(encounterWithObservations(observation1)); }}; assertThat(encounters, is(expectedOrderedConcept)); }
@Test public void shouldPutEncounterWithNullDateAtTheTopWhenItsAtTheTop() { final Observation observation1 = createObservation(createEncounter("c1", null), "01"); final Observation observation2 = createObservation(createEncounter("c2", new Date(1)), "02"); final Encounters encounters = new Encounters(observation1, observation2); encounters.sortByDate(); final Encounters expectedOrderedConcept = new Encounters() {{ add(encounterWithObservations(observation1)); add(encounterWithObservations(observation2)); }}; assertThat(encounters, is(expectedOrderedConcept)); } |
### Question:
MuzimaSyncService { public void consolidatePatients() { List<Patient> allLocalPatients = patientController.getAllPatientsCreatedLocallyAndNotSynced(); for (Patient localPatient : allLocalPatients) { Patient patientFromServer = patientController.consolidateTemporaryPatient(localPatient); if (patientFromServer != null) { checkChangeInPatientId(localPatient, patientFromServer); patientFromServer.addIdentifier(localPatient.getIdentifier(LOCAL_PATIENT)); patientController.deletePatient(localPatient); try { patientController.savePatient(patientFromServer); } catch (PatientController.PatientSaveException e) { Log.e(getClass().getSimpleName(), "Error while saving patients.", e); } } } } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }### Answer:
@Test public void consolidatePatients_shouldGetAllPatientsConsolidateSavePatientFromServerAndDeleteLocalPatient() throws PatientController.PatientSaveException { Patient localPatient = mock(Patient.class); Patient remotePatient = mock(Patient.class); when(patientController.consolidateTemporaryPatient(localPatient)).thenReturn(remotePatient); when(patientController.getAllPatientsCreatedLocallyAndNotSynced()).thenReturn(Collections.singletonList(localPatient)); muzimaSyncService.consolidatePatients(); verify(patientController).getAllPatientsCreatedLocallyAndNotSynced(); verify(patientController).consolidateTemporaryPatient(localPatient); verify(patientController).savePatient(remotePatient); verify(patientController).deletePatient(localPatient); } |
### Question:
MuzimaSyncService { public List<Patient> updatePatientsNotPartOfCohorts() { List<Patient> patientsNotInCohorts = patientController.getPatientsNotInCohorts(); List<Patient> downloadedPatients = new ArrayList<>(); try { for (Patient patient : patientsNotInCohorts) { downloadedPatients.add(patientController.downloadPatientByUUID(patient.getUuid())); } downloadedPatients.removeAll(singleton(null)); patientController.replacePatients(downloadedPatients); } catch (PatientController.PatientSaveException e) { Log.e(getClass().getSimpleName(), "Exception thrown while updating patients from server.", e); } catch (PatientController.PatientDownloadException e) { Log.e(getClass().getSimpleName(), "Exception thrown while downloading patients from server.", e); } return downloadedPatients; } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }### Answer:
@Test public void shouldUpdatePatientsThatAreNotInCohorts() throws PatientController.PatientSaveException, PatientController.PatientDownloadException { Patient localPatient1 = patient("patientUUID1"); Patient localPatient2 = patient("patientUUID2"); Patient serverPatient1 = patient("patientUUID3"); when(patientController.getPatientsNotInCohorts()).thenReturn(asList(localPatient1, localPatient2)); when(patientController.downloadPatientByUUID("patientUUID1")).thenReturn(serverPatient1); when(patientController.downloadPatientByUUID("patientUUID2")).thenReturn(null); muzimaSyncService.updatePatientsNotPartOfCohorts(); verify(patientController).downloadPatientByUUID("patientUUID1"); verify(patientController).downloadPatientByUUID("patientUUID2"); verify(patientController).replacePatients(Collections.singletonList(serverPatient1)); } |
### Question:
ObservationParserUtility { public Encounter getEncounterEntity(Date encounterDateTime,String formUuid,String providerId, int locationId, String userSystemId, Patient patient, String formDataUuid) { Encounter encounter = new Encounter(); encounter.setProvider(getDummyProvider(providerId)); encounter.setUuid(getEncounterUUID()); encounter.setLocation(getDummyLocation(locationId)); encounter.setEncounterType(getDummyEncounterType(formUuid)); encounter.setEncounterDatetime(encounterDateTime); encounter.setUserSystemId(userSystemId); encounter.setFormDataUuid(formDataUuid); encounter.setPatient(patient); return encounter; } ObservationParserUtility(MuzimaApplication muzimaApplication, boolean createObservationsForConceptsNotAvailableLocally); Encounter getEncounterEntity(Date encounterDateTime,String formUuid,String providerId, int locationId, String userSystemId, Patient patient, String formDataUuid); Concept getConceptEntity(String rawConceptName, boolean isCoded, boolean createConceptIfNotAvailableLocally); Observation getObservationEntity(Concept concept, String value); List<Concept> getNewConceptList(); static boolean isFormattedAsConcept(String peek); String getObservationUuid(); }### Answer:
@Test public void shouldCreateEncounterEntityWithAppropriateValues() throws ProviderController.ProviderLoadException, FormController.FormFetchException { Date encounterDateTime = new Date(); final String formUuid = "formUuid"; String providerId = "providerId"; int locationId = 1; String userSystemId = "userSystemId"; final EncounterType encounterType = new EncounterType(){{ setUuid("encounterTypeForObservationsCreatedOnPhone"); }}; Form form = new Form(){{ setUuid(formUuid); setEncounterType(encounterType); }}; List<Provider> providers = new ArrayList<Provider>() {{ add(new Provider() {{ setUuid("provider1"); }}); }}; when(providerController.getAllProviders()).thenReturn(providers); when(formController.getFormByUuid(formUuid)).thenReturn(form); Encounter encounter = observationParserUtility.getEncounterEntity(encounterDateTime, formUuid,providerId, locationId, userSystemId, patient, formDataUuid); assertTrue(encounter.getUuid().startsWith("encounterUuid")); assertThat(encounter.getEncounterType().getUuid(), is(form.getEncounterType().getUuid())); assertThat(encounter.getProvider().getUuid(), is("providerForObservationsCreatedOnPhone")); assertThat(encounter.getEncounterDatetime(), is(encounterDateTime)); } |
### Question:
ObservationParserUtility { public List<Concept> getNewConceptList() { return newConceptList; } ObservationParserUtility(MuzimaApplication muzimaApplication, boolean createObservationsForConceptsNotAvailableLocally); Encounter getEncounterEntity(Date encounterDateTime,String formUuid,String providerId, int locationId, String userSystemId, Patient patient, String formDataUuid); Concept getConceptEntity(String rawConceptName, boolean isCoded, boolean createConceptIfNotAvailableLocally); Observation getObservationEntity(Concept concept, String value); List<Concept> getNewConceptList(); static boolean isFormattedAsConcept(String peek); String getObservationUuid(); }### Answer:
@Test public void shouldNotCreateNewConceptOrObservationForInvalidConceptName() { observationParserUtility = new ObservationParserUtility(muzimaApplication,true); assertThat(observationParserUtility.getNewConceptList().size(), is(0)); } |
### Question:
ObservationParserUtility { public Observation getObservationEntity(Concept concept, String value) throws ConceptController.ConceptFetchException, ConceptController.ConceptParseException, ObservationController.ParseObservationException{ if (concept == null) { throw new ObservationController.ParseObservationException("Could not create Observation entity." + " Reason: No Concept provided."); } if (StringUtils.isEmpty(value)) { throw new ObservationController.ParseObservationException("Could not create Observation entity for concept '" + concept.getName() + "'. Reason: No Observation value provided."); } Observation observation = new Observation(); observation.setUuid(getObservationUuid()); observation.setValueCoded(defaultValueCodedConcept()); if (concept.isCoded()) { try { Concept valueCoded = getConceptEntity(value,false, true); observation.setValueCoded(valueCoded); } catch (ConceptController.ConceptParseException e) { throw new ConceptController.ConceptParseException("Could not get value for coded concept '" + concept.getName() + "', from provided value '" + value + "'"); } } else if (concept.isNumeric()) { observation.setValueNumeric(getDoubleValue(value)); } else { observation.setValueText(value); } observation.setConcept(concept); return observation; } ObservationParserUtility(MuzimaApplication muzimaApplication, boolean createObservationsForConceptsNotAvailableLocally); Encounter getEncounterEntity(Date encounterDateTime,String formUuid,String providerId, int locationId, String userSystemId, Patient patient, String formDataUuid); Concept getConceptEntity(String rawConceptName, boolean isCoded, boolean createConceptIfNotAvailableLocally); Observation getObservationEntity(Concept concept, String value); List<Concept> getNewConceptList(); static boolean isFormattedAsConcept(String peek); String getObservationUuid(); }### Answer:
@Test public void shouldCreateNumericObservation() throws ConceptController.ConceptFetchException, ConceptController.ConceptParseException, ObservationController.ParseObservationException{ Concept concept = mock(Concept.class); when(concept.isNumeric()).thenReturn(true); when(concept.isCoded()).thenReturn(false); Observation observation = observationParserUtility.getObservationEntity(concept, "20.0"); assertThat(observation.getValueNumeric(), is(20.0)); assertTrue(observation.getUuid().startsWith("observationFromPhoneUuid")); }
@Test public void shouldCreateObsWithStringForNonNumericNonCodedConcept() throws ConceptController.ConceptFetchException, ConceptController.ConceptParseException, ObservationController.ParseObservationException{ observationParserUtility = new ObservationParserUtility(muzimaApplication,true); Concept concept = mock(Concept.class); when(concept.getName()).thenReturn("SomeConcept"); when(concept.isNumeric()).thenReturn(false); when(concept.isCoded()).thenReturn(false); Observation observation = observationParserUtility.getObservationEntity(concept, "someString"); assertThat(observation.getValueAsString(), is("someString")); } |
### Question:
HTMLFormObservationCreator { public void createAndPersistObservations(String jsonResponse,String formDataUuid) { parseJSONResponse(jsonResponse,formDataUuid); try { saveObservationsAndRelatedEntities(); } catch (ConceptController.ConceptSaveException e) { Log.e(getClass().getSimpleName(), "Error while saving concept", e); } catch (EncounterController.SaveEncounterException e) { Log.e(getClass().getSimpleName(), "Error while saving Encounter", e); } catch (ObservationController.SaveObservationException e) { Log.e(getClass().getSimpleName(), "Error while saving Observation", e); } catch (Exception e) { Log.e(getClass().getSimpleName(), "Unexpected Exception occurred", e); } } HTMLFormObservationCreator(MuzimaApplication muzimaApplication, boolean createObservationsForConceptsNotAvailableLocally); void createAndPersistObservations(String jsonResponse,String formDataUuid); void createObservationsAndRelatedEntities(String jsonResponse,String formDataUuid); List<Observation> getObservations(); Encounter getEncounter(); List<Concept> getNewConceptList(); Date getEncounterDateFromFormDate(String jsonResponse); }### Answer:
@Test public void shouldVerifyAllObservationsAndRelatedEntitiesAreSaved() throws EncounterController.SaveEncounterException, ConceptController.ConceptSaveException, ObservationController.SaveObservationException { htmlFormObservationCreator.createAndPersistObservations(readFile(),formDataUuid); verify(encounterController).saveEncounters(encounterArgumentCaptor.capture()); assertThat(encounterArgumentCaptor.getValue().size(), is(1)); verify(conceptController).saveConcepts(conceptArgumentCaptor.capture()); List<Concept> value = conceptArgumentCaptor.getValue(); assertThat(value.size(), is(33)); verify(observationController).saveObservations(observationArgumentCaptor.capture()); assertThat(observationArgumentCaptor.getValue().size(), is(30)); } |
### Question:
HTMLConceptParser { public List<String> parse(String html) { Set<String> concepts = new HashSet<>(); Document htmlDoc = Jsoup.parse(html); Elements elements = htmlDoc.select("*:not(div)[" + DATA_CONCEPT_TAG + "]"); for (Element element : elements) { concepts.add(getConceptName(element.attr(DATA_CONCEPT_TAG))); } return new ArrayList<>(concepts); } List<String> parse(String html); }### Answer:
@Test public void shouldReturnListOfConcepts() { String html = readFile(); List<String> concepts = new HTMLConceptParser().parse(html); assertThat(concepts.size(),is(7)); assertThat(concepts,hasItem("BODY PART")); assertThat(concepts,hasItem("PROCEDURES DONE THIS VISIT")); assertThat(concepts,hasItem("ANATOMIC LOCATION DESCRIPTION")); assertThat(concepts,hasItem("CLOCK FACE CERVICAL BIOPSY LOCATION ")); assertThat(concepts,hasItem("PATHOLOGICAL DIAGNOSIS ADDED")); assertThat(concepts,hasItem("FREETEXT GENERAL")); assertThat(concepts,hasItem("RETURN VISIT DATE")); } |
### Question:
ConceptParser { public List<String> parse(String model) { try { if (StringUtils.isEmpty(model)) { return new ArrayList<>(); } parser.setInput(new ByteArrayInputStream(model.getBytes()), null); parser.nextTag(); return readConceptName(parser); } catch (Exception e) { throw new ParseConceptException(e); } } ConceptParser(); ConceptParser(XmlPullParser parser); List<String> parse(String model); }### Answer:
@Test public void shouldParseConcept() { List<String> conceptNames = utils.parse(getModel("concept.xml")); assertThat(conceptNames, hasItem("PULSE")); }
@Test public void shouldParseConceptInObs() { List<String> conceptNames = utils.parse(getModel("concept_in_obs.xml")); assertThat(conceptNames, hasItem("WEIGHT (KG)")); }
@Test public void shouldNotAddItToConceptUnLessBothDateAndTimeArePresentInChildren() { List<String> conceptNames = utils.parse(getModel("concepts_in_concept.xml")); assertThat(conceptNames.size(), is(2)); assertThat(conceptNames, hasItem("PROBLEM ADDED")); assertThat(conceptNames, hasItem("PROBLEM RESOLVED")); }
@Test public void shouldNotConsiderOptionsAsConcepts() { List<String> conceptNames = utils.parse(getModel("concepts_with_options.xml")); assertThat(conceptNames.size(), is(1)); assertThat(conceptNames, hasItem("MOST RECENT PAPANICOLAOU SMEAR RESULT")); }
@Test(expected = ConceptParser.ParseConceptException.class) public void shouldThrowParseConceptExceptionWhenTheModelHasNoEndTag() { utils.parse(getModel("concept_no_end_tag.xml")); }
@Test public void shouldParseConceptTM() { List<String> conceptNames = utils.parse(getModel("dispensary_concept_in_obs.xml")); assertThat(conceptNames, hasItem("START TIME")); assertThat(conceptNames, hasItem("END TIME")); } |
### Question:
PatientController { public List<Patient> getAllPatients() throws PatientLoadException { try { return patientService.getAllPatients(); } catch (IOException e) { throw new PatientLoadException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }### Answer:
@Test public void getAllPatients_shouldReturnAllAvailablePatients() throws IOException, PatientController.PatientLoadException { List<Patient> patients = new ArrayList<>(); when(patientService.getAllPatients()).thenReturn(patients); assertThat(patientController.getAllPatients(), is(patients)); }
@Test(expected = PatientController.PatientLoadException.class) public void getAllForms_shouldThrowFormFetchExceptionIfExceptionThrownByFormService() throws IOException, PatientController.PatientLoadException { doThrow(new IOException()).when(patientService).getAllPatients(); patientController.getAllPatients(); } |
### Question:
PatientController { public int countAllPatients() throws PatientLoadException { try { return patientService.countAllPatients(); } catch (IOException e) { throw new PatientLoadException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }### Answer:
@Test public void getTotalPatientsCount_shouldReturnPatientsCount() throws IOException, PatientController.PatientLoadException { when(patientService.countAllPatients()).thenReturn(2); assertThat(patientController.countAllPatients(), is(2)); } |
### Question:
PatientController { public void replacePatients(List<Patient> patients) throws PatientSaveException { try { patientService.updatePatients(patients); } catch (IOException e) { throw new PatientSaveException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }### Answer:
@Test public void replacePatients_shouldReplaceAllExistingPatientsAndAddNewPatients() throws IOException, PatientController.PatientSaveException { List<Patient> patients = buildPatients(); patientController.replacePatients(patients); verify(patientService).updatePatients(patients); verifyNoMoreInteractions(patientService); }
@Test(expected = PatientController.PatientSaveException.class) public void replacePatients_shouldThrowPatientReplaceExceptionIfExceptionThrownByService() throws IOException, PatientController.PatientSaveException { List<Patient> patients = buildPatients(); doThrow(new IOException()).when(patientService).updatePatients(patients); patientController.replacePatients(patients); } |
### Question:
PatientController { public List<Patient> getPatients(String cohortId) throws PatientLoadException { try { List<CohortMember> cohortMembers = cohortService.getCohortMembers(cohortId); return patientService.getPatientsFromCohortMembers(cohortMembers); } catch (IOException e) { throw new PatientLoadException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }### Answer:
@Test public void getPatientsInCohort_shouldReturnThePatientsInTheCohort() throws IOException, PatientController.PatientLoadException { String cohortId = "cohortId"; List<CohortMember> members = buildCohortMembers(cohortId); when(cohortService.getCohortMembers(cohortId)).thenReturn(members); Patient patient = new Patient(); patient.setUuid(members.get(0).getPatientUuid()); when(patientService.getPatientsFromCohortMembers(members)).thenReturn(Collections.singletonList(patient)); List<Patient> patients = patientController.getPatients(cohortId); assertThat(patients.size(), is(1)); } |
### Question:
ConceptsByPatient extends ConceptAction { @Override Concepts get() throws ObservationController.LoadObservationException { return controller.getConceptWithObservations(patientUuid); } ConceptsByPatient(ConceptController conceptController, ObservationController controller, String patientUuid); @Override String toString(); }### Answer:
@Test public void shouldGetObservationsByPatientUUID() throws ObservationController.LoadObservationException { ObservationController controller = mock(ObservationController.class); ConceptController conceptController = mock(ConceptController.class); ConceptsByPatient byPatient = new ConceptsByPatient(conceptController,controller, "uuid"); byPatient.get(); verify(controller).getConceptWithObservations("uuid"); } |
### Question:
PatientController { public List<Patient> searchPatientLocally(String term, String cohortUuid) throws PatientLoadException { try { return StringUtils.isEmpty(cohortUuid) ? patientService.searchPatients(term) : patientService.searchPatients(term, cohortUuid); } catch (IOException | ParseException e) { throw new PatientLoadException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }### Answer:
@Test public void shouldSearchWithOutCohortUUIDIsNull() throws IOException, ParseException, PatientController.PatientLoadException { String searchString = "searchString"; List<Patient> patients = new ArrayList<>(); when(patientService.searchPatients(searchString)).thenReturn(patients); assertThat(patientController.searchPatientLocally(searchString, null), is(patients)); verify(patientService).searchPatients(searchString); }
@Test public void shouldSearchWithOutCohortUUIDIsEmpty() throws IOException, ParseException, PatientController.PatientLoadException { String searchString = "searchString"; List<Patient> patients = new ArrayList<>(); when(patientService.searchPatients(searchString)).thenReturn(patients); assertThat(patientController.searchPatientLocally(searchString, StringUtils.EMPTY), is(patients)); verify(patientService).searchPatients(searchString); }
@Test public void shouldCallSearchPatientWithCohortIDIfPresent() throws Exception, PatientController.PatientLoadException { String searchString = "searchString"; String cohortUUID = "cohortUUID"; List<Patient> patients = new ArrayList<>(); when(patientService.searchPatients(searchString, cohortUUID)).thenReturn(patients); assertThat(patientController.searchPatientLocally(searchString, cohortUUID), is(patients)); verify(patientService).searchPatients(searchString, cohortUUID); } |
### Question:
PatientController { public Patient getPatientByUuid(String uuid) throws PatientLoadException { try { return patientService.getPatientByUuid(uuid); } catch (IOException e) { throw new PatientLoadException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }### Answer:
@Test public void getPatientByUuid_shouldReturnPatientForId() throws Exception, PatientController.PatientLoadException { Patient patient = new Patient(); String uuid = "uuid"; when(patientService.getPatientByUuid(uuid)).thenReturn(patient); assertThat(patientController.getPatientByUuid(uuid), is(patient)); } |
### Question:
PatientController { public List<Patient> searchPatientOnServer(String name) { try { return patientService.downloadPatientsByName(name); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error while searching for patients in the server", e); } return new ArrayList<>(); } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }### Answer:
@Test public void shouldSearchOnServerForPatientByNames() throws Exception { String name = "name"; List<Patient> patients = new ArrayList<>(); when(patientService.downloadPatientsByName(name)).thenReturn(patients); assertThat(patientController.searchPatientOnServer(name), is(patients)); verify(patientService).downloadPatientsByName(name); }
@Test public void shouldReturnEmptyListIsExceptionThrown() throws Exception { String searchString = "name"; doThrow(new IOException()).when(patientService).downloadPatientsByName(searchString); assertThat(patientController.searchPatientOnServer(searchString).size(), is(0)); } |
### Question:
PatientController { public Patient consolidateTemporaryPatient(Patient patient) { try { return patientService.consolidateTemporaryPatient(patient); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error while consolidating the temporary patient.", e); } return null; } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }### Answer:
@Test public void shouldConsolidatePatients() throws Exception { Patient tempPatient = mock(Patient.class); Patient patient = mock(Patient.class); when(patientService.consolidateTemporaryPatient(tempPatient)).thenReturn(patient); assertThat(patient, is(patientController.consolidateTemporaryPatient(tempPatient))); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.