method2testcases
stringlengths
118
6.63k
### Question: AbstractRegistry implements Registry { @Override public void unsubscribe(URL url, NotifyListener listener) { if (url == null) { throw new IllegalArgumentException("unsubscribe url == null"); } if (listener == null) { throw new IllegalArgumentException("unsubscribe listener == null"); } if (logger.isInfoEnabled()) { logger.info("Unsubscribe: " + url); } Set<NotifyListener> listeners = subscribed.get(url); if (listeners != null) { listeners.remove(listener); } } AbstractRegistry(URL url); @Override URL getUrl(); Set<URL> getRegistered(); Map<URL, Set<NotifyListener>> getSubscribed(); Map<URL, Map<String, List<URL>>> getNotified(); File getCacheFile(); Properties getCacheProperties(); AtomicLong getLastCacheChanged(); void doSaveProperties(long version); List<URL> getCacheUrls(URL url); @Override List<URL> lookup(URL url); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); @Override String toString(); }### Answer: @Test public void testUnsubscribeIfUrlNull() throws Exception { Assertions.assertThrows(IllegalArgumentException.class, () -> { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener = urls -> notified.set(Boolean.TRUE); abstractRegistry.unsubscribe(null, listener); Assertions.fail("unsubscribe url == null"); }); } @Test public void testUnsubscribeIfNotifyNull() throws Exception { Assertions.assertThrows(IllegalArgumentException.class, () -> { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); URL url = new URL("dubbo", "192.168.0.1", 2200); abstractRegistry.unsubscribe(url, null); Assertions.fail("unsubscribe listener == null"); }); } @Test public void testUnsubscribe() throws Exception { try { abstractRegistry.unsubscribe(testUrl, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalArgumentException); } try { abstractRegistry.unsubscribe(null, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalArgumentException); } Assertions.assertNull(abstractRegistry.getSubscribed().get(testUrl)); abstractRegistry.subscribe(testUrl, listener); abstractRegistry.unsubscribe(testUrl, listener); Assertions.assertNotNull(abstractRegistry.getSubscribed().get(testUrl)); Assertions.assertFalse(abstractRegistry.getSubscribed().get(testUrl).contains(listener)); }
### Question: AbstractRegistry implements Registry { protected static List<URL> filterEmpty(URL url, List<URL> urls) { if (CollectionUtils.isEmpty(urls)) { List<URL> result = new ArrayList<>(1); result.add(url.setProtocol(Constants.EMPTY_PROTOCOL)); return result; } return urls; } AbstractRegistry(URL url); @Override URL getUrl(); Set<URL> getRegistered(); Map<URL, Set<NotifyListener>> getSubscribed(); Map<URL, Map<String, List<URL>>> getNotified(); File getCacheFile(); Properties getCacheProperties(); AtomicLong getLastCacheChanged(); void doSaveProperties(long version); List<URL> getCacheUrls(URL url); @Override List<URL> lookup(URL url); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); @Override String toString(); }### Answer: @Test public void filterEmptyTest() throws Exception { try { AbstractRegistry.filterEmpty(null, null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof NullPointerException); } List<URL> urls = new ArrayList<>(); try { AbstractRegistry.filterEmpty(null, urls); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof NullPointerException); } urls.add(testUrl.setProtocol(Constants.EMPTY_PROTOCOL)); Assertions.assertEquals(AbstractRegistry.filterEmpty(testUrl, null), urls); List<URL> testUrls = new ArrayList<>(); Assertions.assertEquals(AbstractRegistry.filterEmpty(testUrl, testUrls), urls); testUrls.add(testUrl); Assertions.assertEquals(AbstractRegistry.filterEmpty(testUrl, testUrls), testUrls); }
### Question: AbstractRegistry implements Registry { @Override public List<URL> lookup(URL url) { List<URL> result = new ArrayList<>(); Map<String, List<URL>> notifiedUrls = getNotified().get(url); if (notifiedUrls != null && notifiedUrls.size() > 0) { for (List<URL> urls : notifiedUrls.values()) { for (URL u : urls) { if (!Constants.EMPTY_PROTOCOL.equals(u.getProtocol())) { result.add(u); } } } } else { final AtomicReference<List<URL>> reference = new AtomicReference<>(); NotifyListener listener = reference::set; subscribe(url, listener); List<URL> urls = reference.get(); if (CollectionUtils.isNotEmpty(urls)) { for (URL u : urls) { if (!Constants.EMPTY_PROTOCOL.equals(u.getProtocol())) { result.add(u); } } } } return result; } AbstractRegistry(URL url); @Override URL getUrl(); Set<URL> getRegistered(); Map<URL, Set<NotifyListener>> getSubscribed(); Map<URL, Map<String, List<URL>>> getNotified(); File getCacheFile(); Properties getCacheProperties(); AtomicLong getLastCacheChanged(); void doSaveProperties(long version); List<URL> getCacheUrls(URL url); @Override List<URL> lookup(URL url); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); @Override String toString(); }### Answer: @Test public void lookupTest() throws Exception { try { abstractRegistry.lookup(null); Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof NullPointerException); } List<URL> urlList1 = abstractRegistry.lookup(testUrl); Assertions.assertFalse(urlList1.contains(testUrl)); List<URL> urls = new ArrayList<>(); urls.add(testUrl); abstractRegistry.notify(urls); List<URL> urlList2 = abstractRegistry.lookup(testUrl); Assertions.assertTrue(urlList2.contains(testUrl)); }
### Question: AbstractRegistry implements Registry { @Override public void destroy() { if (logger.isInfoEnabled()) { logger.info("Destroy registry:" + getUrl()); } Set<URL> destroyRegistered = new HashSet<>(getRegistered()); if (!destroyRegistered.isEmpty()) { for (URL url : new HashSet<>(getRegistered())) { if (url.getParameter(Constants.DYNAMIC_KEY, true)) { try { unregister(url); if (logger.isInfoEnabled()) { logger.info("Destroy unregister url " + url); } } catch (Throwable t) { logger.warn("Failed to unregister url " + url + " to registry " + getUrl() + " on destroy, cause: " + t.getMessage(), t); } } } } Map<URL, Set<NotifyListener>> destroySubscribed = new HashMap<>(getSubscribed()); if (!destroySubscribed.isEmpty()) { for (Map.Entry<URL, Set<NotifyListener>> entry : destroySubscribed.entrySet()) { URL url = entry.getKey(); for (NotifyListener listener : entry.getValue()) { try { unsubscribe(url, listener); if (logger.isInfoEnabled()) { logger.info("Destroy unsubscribe url " + url); } } catch (Throwable t) { logger.warn("Failed to unsubscribe url " + url + " to registry " + getUrl() + " on destroy, cause: " + t.getMessage(), t); } } } } } AbstractRegistry(URL url); @Override URL getUrl(); Set<URL> getRegistered(); Map<URL, Set<NotifyListener>> getSubscribed(); Map<URL, Map<String, List<URL>>> getNotified(); File getCacheFile(); Properties getCacheProperties(); AtomicLong getLastCacheChanged(); void doSaveProperties(long version); List<URL> getCacheUrls(URL url); @Override List<URL> lookup(URL url); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); @Override String toString(); }### Answer: @Test public void destroyTest() throws Exception { abstractRegistry.register(testUrl); abstractRegistry.subscribe(testUrl, listener); Assertions.assertEquals(1, abstractRegistry.getRegistered().size()); Assertions.assertEquals(1, abstractRegistry.getSubscribed().get(testUrl).size()); abstractRegistry.destroy(); Assertions.assertEquals(0, abstractRegistry.getRegistered().size()); Assertions.assertEquals(0, abstractRegistry.getSubscribed().get(testUrl).size()); }
### Question: AbstractRegistry implements Registry { public List<URL> getCacheUrls(URL url) { for (Map.Entry<Object, Object> entry : properties.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); if (key != null && key.length() > 0 && key.equals(url.getServiceKey()) && (Character.isLetter(key.charAt(0)) || key.charAt(0) == '_') && value != null && value.length() > 0) { String[] arr = value.trim().split(URL_SPLIT); List<URL> urls = new ArrayList<>(); for (String u : arr) { urls.add(URL.valueOf(u)); } return urls; } } return null; } AbstractRegistry(URL url); @Override URL getUrl(); Set<URL> getRegistered(); Map<URL, Set<NotifyListener>> getSubscribed(); Map<URL, Map<String, List<URL>>> getNotified(); File getCacheFile(); Properties getCacheProperties(); AtomicLong getLastCacheChanged(); void doSaveProperties(long version); List<URL> getCacheUrls(URL url); @Override List<URL> lookup(URL url); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); @Override String toString(); }### Answer: @Test public void getCacheUrlsTest() { List<URL> urls = new ArrayList<>(); urls.add(testUrl); Assertions.assertFalse(notifySuccess); abstractRegistry.notify(testUrl, listener, urls); Assertions.assertTrue(notifySuccess); List<URL> cacheUrl = abstractRegistry.getCacheUrls(testUrl); Assertions.assertTrue(cacheUrl.size() == 1); URL nullUrl = URL.valueOf("http: cacheUrl = abstractRegistry.getCacheUrls(nullUrl); Assertions.assertTrue(Objects.isNull(cacheUrl)); }
### Question: FailbackRegistry extends AbstractRegistry { @Override public void register(URL url) { super.register(url); removeFailedRegistered(url); removeFailedUnregistered(url); try { doRegister(url); } catch (Exception e) { Throwable t = e; boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true) && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t); } addFailedRegistered(url); } } FailbackRegistry(URL url); void removeFailedRegisteredTask(URL url); void removeFailedUnregisteredTask(URL url); void removeFailedSubscribedTask(URL url, NotifyListener listener); void removeFailedUnsubscribedTask(URL url, NotifyListener listener); void removeFailedNotifiedTask(URL url, NotifyListener listener); ConcurrentMap<URL, FailedRegisteredTask> getFailedRegistered(); ConcurrentMap<URL, FailedUnregisteredTask> getFailedUnregistered(); ConcurrentMap<Holder, FailedSubscribedTask> getFailedSubscribed(); ConcurrentMap<Holder, FailedUnsubscribedTask> getFailedUnsubscribed(); ConcurrentMap<Holder, FailedNotifiedTask> getFailedNotified(); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); abstract void doRegister(URL url); abstract void doUnregister(URL url); abstract void doSubscribe(URL url, NotifyListener listener); abstract void doUnsubscribe(URL url, NotifyListener listener); }### Answer: @Test public void testDoRetry_subscribe() throws Exception { final CountDownLatch latch = new CountDownLatch(1); registry = new MockRegistry(registryUrl, latch); registry.setBad(true); registry.register(serviceUrl); registry.setBad(false); for (int i = 0; i < trytimes; i++) { System.out.println("failback registry retry ,times:" + i); if (latch.getCount() == 0) break; Thread.sleep(sleeptime); } assertEquals(0, latch.getCount()); }
### Question: FailbackRegistry extends AbstractRegistry { @Override protected void recover() throws Exception { Set<URL> recoverRegistered = new HashSet<URL>(getRegistered()); if (!recoverRegistered.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Recover register url " + recoverRegistered); } for (URL url : recoverRegistered) { addFailedRegistered(url); } } Map<URL, Set<NotifyListener>> recoverSubscribed = new HashMap<URL, Set<NotifyListener>>(getSubscribed()); if (!recoverSubscribed.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Recover subscribe url " + recoverSubscribed.keySet()); } for (Map.Entry<URL, Set<NotifyListener>> entry : recoverSubscribed.entrySet()) { URL url = entry.getKey(); for (NotifyListener listener : entry.getValue()) { addFailedSubscribed(url, listener); } } } } FailbackRegistry(URL url); void removeFailedRegisteredTask(URL url); void removeFailedUnregisteredTask(URL url); void removeFailedSubscribedTask(URL url, NotifyListener listener); void removeFailedUnsubscribedTask(URL url, NotifyListener listener); void removeFailedNotifiedTask(URL url, NotifyListener listener); ConcurrentMap<URL, FailedRegisteredTask> getFailedRegistered(); ConcurrentMap<URL, FailedUnregisteredTask> getFailedUnregistered(); ConcurrentMap<Holder, FailedSubscribedTask> getFailedSubscribed(); ConcurrentMap<Holder, FailedUnsubscribedTask> getFailedUnsubscribed(); ConcurrentMap<Holder, FailedNotifiedTask> getFailedNotified(); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); abstract void doRegister(URL url); abstract void doUnregister(URL url); abstract void doSubscribe(URL url, NotifyListener listener); abstract void doUnsubscribe(URL url, NotifyListener listener); }### Answer: @Test public void testRecover() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(4); final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener = new NotifyListener() { @Override public void notify(List<URL> urls) { notified.set(Boolean.TRUE); } }; MockRegistry mockRegistry = new MockRegistry(registryUrl, countDownLatch); mockRegistry.register(serviceUrl); mockRegistry.subscribe(serviceUrl, listener); Assertions.assertEquals(1, mockRegistry.getRegistered().size()); Assertions.assertEquals(1, mockRegistry.getSubscribed().size()); mockRegistry.recover(); countDownLatch.await(); Assertions.assertEquals(0, mockRegistry.getFailedRegistered().size()); FailbackRegistry.Holder h = new FailbackRegistry.Holder(registryUrl, listener); Assertions.assertEquals(null, mockRegistry.getFailedSubscribed().get(h)); Assertions.assertEquals(countDownLatch.getCount(), 0); }
### Question: InternalThreadLocal { @SuppressWarnings("unchecked") public static void removeAll() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); if (threadLocalMap == null) { return; } try { Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); if (v != null && v != InternalThreadLocalMap.UNSET) { Set<InternalThreadLocal<?>> variablesToRemove = (Set<InternalThreadLocal<?>>) v; InternalThreadLocal<?>[] variablesToRemoveArray = variablesToRemove.toArray(new InternalThreadLocal[variablesToRemove.size()]); for (InternalThreadLocal<?> tlv : variablesToRemoveArray) { tlv.remove(threadLocalMap); } } } finally { InternalThreadLocalMap.remove(); } } InternalThreadLocal(); @SuppressWarnings("unchecked") static void removeAll(); static int size(); static void destroy(); @SuppressWarnings("unchecked") final V get(); final void set(V value); @SuppressWarnings("unchecked") final void remove(); @SuppressWarnings("unchecked") final void remove(InternalThreadLocalMap threadLocalMap); }### Answer: @Test public void testRemoveAll() throws InterruptedException { final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>(); internalThreadLocal.set(1); Assertions.assertTrue(internalThreadLocal.get() == 1, "set failed"); final InternalThreadLocal<String> internalThreadLocalString = new InternalThreadLocal<String>(); internalThreadLocalString.set("value"); Assertions.assertTrue("value".equals(internalThreadLocalString.get()), "set failed"); InternalThreadLocal.removeAll(); Assertions.assertTrue(internalThreadLocal.get() == null, "removeAll failed!"); Assertions.assertTrue(internalThreadLocalString.get() == null, "removeAll failed!"); }
### Question: InternalThreadLocal { public static int size() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); if (threadLocalMap == null) { return 0; } else { return threadLocalMap.size(); } } InternalThreadLocal(); @SuppressWarnings("unchecked") static void removeAll(); static int size(); static void destroy(); @SuppressWarnings("unchecked") final V get(); final void set(V value); @SuppressWarnings("unchecked") final void remove(); @SuppressWarnings("unchecked") final void remove(InternalThreadLocalMap threadLocalMap); }### Answer: @Test public void testSize() throws InterruptedException { final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>(); internalThreadLocal.set(1); Assertions.assertTrue(InternalThreadLocal.size() == 1, "size method is wrong!"); final InternalThreadLocal<String> internalThreadLocalString = new InternalThreadLocal<String>(); internalThreadLocalString.set("value"); Assertions.assertTrue(InternalThreadLocal.size() == 2, "size method is wrong!"); }
### Question: InternalThreadLocal { @SuppressWarnings("unchecked") public final void remove() { remove(InternalThreadLocalMap.getIfSet()); } InternalThreadLocal(); @SuppressWarnings("unchecked") static void removeAll(); static int size(); static void destroy(); @SuppressWarnings("unchecked") final V get(); final void set(V value); @SuppressWarnings("unchecked") final void remove(); @SuppressWarnings("unchecked") final void remove(InternalThreadLocalMap threadLocalMap); }### Answer: @Test public void testRemove() { final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>(); internalThreadLocal.set(1); Assertions.assertTrue(internalThreadLocal.get() == 1, "get method false!"); internalThreadLocal.remove(); Assertions.assertTrue(internalThreadLocal.get() == null, "remove failed!"); }
### Question: NamedInternalThreadFactory extends NamedThreadFactory { @Override public Thread newThread(Runnable runnable) { String name = mPrefix + mThreadNum.getAndIncrement(); InternalThread ret = new InternalThread(mGroup, runnable, name, 0); ret.setDaemon(mDaemon); return ret; } NamedInternalThreadFactory(); NamedInternalThreadFactory(String prefix); NamedInternalThreadFactory(String prefix, boolean daemon); @Override Thread newThread(Runnable runnable); }### Answer: @Test public void newThread() throws Exception { NamedInternalThreadFactory namedInternalThreadFactory = new NamedInternalThreadFactory(); Thread t = namedInternalThreadFactory.newThread(new Runnable() { @Override public void run() { } }); Assertions.assertTrue(t.getClass().equals(InternalThread.class), "thread is not InternalThread"); }
### Question: AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { String msg = String.format("Thread pool is EXHAUSTED!" + " Thread Name: %s, Pool Size: %d (active: %d, core: %d, max: %d, largest: %d), Task: %d (completed: %d)," + " Executor status:(isShutdown:%s, isTerminated:%s, isTerminating:%s), in %s: threadName, e.getPoolSize(), e.getActiveCount(), e.getCorePoolSize(), e.getMaximumPoolSize(), e.getLargestPoolSize(), e.getTaskCount(), e.getCompletedTaskCount(), e.isShutdown(), e.isTerminated(), e.isTerminating(), url.getProtocol(), url.getIp(), url.getPort()); logger.warn(msg); dumpJStack(); throw new RejectedExecutionException(msg); } AbortPolicyWithReport(String threadName, URL url); @Override void rejectedExecution(Runnable r, ThreadPoolExecutor e); }### Answer: @Test public void jStackDumpTest() throws InterruptedException { URL url = URL.valueOf("dubbo: AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url); try { abortPolicyWithReport.rejectedExecution(new Runnable() { @Override public void run() { System.out.println("hello"); } }, (ThreadPoolExecutor) Executors.newFixedThreadPool(1)); } catch (RejectedExecutionException rj) { } Thread.sleep(1000); }
### Question: LimitedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); int cores = url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS); int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES); return new ThreadPoolExecutor(cores, threads, Long.MAX_VALUE, TimeUnit.MILLISECONDS, queues == 0 ? new SynchronousQueue<Runnable>() : (queues < 0 ? new LinkedBlockingQueue<Runnable>() : new LinkedBlockingQueue<Runnable>(queues)), new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); } @Override Executor getExecutor(URL url); }### Answer: @Test public void getExecutor1() throws Exception { URL url = URL.valueOf("dubbo: Constants.THREAD_NAME_KEY + "=demo&" + Constants.CORE_THREADS_KEY + "=1&" + Constants.THREADS_KEY + "=2&" + Constants.QUEUES_KEY + "=0"); ThreadPool threadPool = new LimitedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getCorePoolSize(), is(1)); assertThat(executor.getMaximumPoolSize(), is(2)); assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(SynchronousQueue.class)); assertThat(executor.getRejectedExecutionHandler(), Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class)); final CountDownLatch latch = new CountDownLatch(1); executor.execute(new Runnable() { @Override public void run() { Thread thread = Thread.currentThread(); assertThat(thread, instanceOf(InternalThread.class)); assertThat(thread.getName(), startsWith("demo")); latch.countDown(); } }); latch.await(); assertThat(latch.getCount(), is(0L)); } @Test public void getExecutor2() throws Exception { URL url = URL.valueOf("dubbo: ThreadPool threadPool = new LimitedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(LinkedBlockingQueue.class)); }
### Question: WebServiceProtocol extends AbstractProxyProtocol { public WebServiceProtocol() { super(Fault.class); bus.setExtension(new ServletDestinationFactory(), HttpDestinationFactory.class); } WebServiceProtocol(); void setHttpBinder(HttpBinder httpBinder); @Override int getDefaultPort(); static final int DEFAULT_PORT; }### Answer: @Test public void testWebserviceProtocol() throws Exception { DemoService service = new DemoServiceImpl(); protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("webservice: service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("webservice: assertEquals(service.create(1, "kk").getName(), "kk"); assertEquals(service.getSize(null), -1); assertEquals(service.getSize(new String[]{"", "", ""}), 3); Object object = service.invoke("webservice: System.out.println(object); assertEquals("webservice: StringBuffer buf = new StringBuffer(); for (int i = 0; i < 1024 * 32 + 32; i++) buf.append('A'); assertEquals(32800, service.stringLength(buf.toString())); }
### Question: DaggerLifecycleDelegate { public Object onRetainCustomNonConfigurationInstance() { return daggerComponent; } DaggerLifecycleDelegate(@NonNull DaggerComponentFactory<T> daggerComponentFactory); @SuppressWarnings("unchecked") void onCreate(AppCompatActivity activity); Object onRetainCustomNonConfigurationInstance(); T daggerComponent(); }### Answer: @Test public void onRetainCustomNonConfigurationInstance_THEN_return_dagger_component() throws Exception { assertThat(tested.onRetainCustomNonConfigurationInstance()).isEqualTo(tested.daggerComponent); }
### Question: DaggerLifecycleDelegate { public T daggerComponent() { return daggerComponent; } DaggerLifecycleDelegate(@NonNull DaggerComponentFactory<T> daggerComponentFactory); @SuppressWarnings("unchecked") void onCreate(AppCompatActivity activity); Object onRetainCustomNonConfigurationInstance(); T daggerComponent(); }### Answer: @Test public void daggerComponent_THEN_return_dagger_component() throws Exception { assertThat(tested.daggerComponent()).isEqualTo(tested.daggerComponent); }
### Question: CollectionsX { public static <T> List<T> concat(@NonNull List<T> list1, @NonNull List<T> list2) { final ArrayList<T> list = new ArrayList<>(list1.size() + list2.size()); if (!list1.isEmpty()) { list.addAll(list1); } if (!list2.isEmpty()) { list.addAll(list2); } return list; } private CollectionsX(); static List<T> concat(@NonNull List<T> list1, @NonNull List<T> list2); }### Answer: @Test public void should_return_concatenated_list() throws Exception { assertThat(CollectionsX.concat(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6))) .isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6)); }
### Question: AppRouter { public Intent loginIntent(Context context) { return intentFactory.create(context, LoginActivity.class); } AppRouter(); @VisibleForTesting AppRouter(IntentFactory intentFactory); Intent loginIntent(Context context); }### Answer: @Test public void should_return_loginIntent() throws Exception { tested.loginIntent(mockedContext); verify(mockedIntentFactory).create(mockedContext, LoginActivity.class); }
### Question: EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } boolean isValid(CharSequence email); Observable<Boolean> checkEmail(CharSequence email); }### Answer: @Test public void should_return_false_when_email_is_null() throws Exception { assertThat(tested.isValid(null)).isFalse(); } @Test public void should_return_false_when_email_is_invalid() throws Exception { assertThat(tested.isValid("abc")).isFalse(); } @Test public void should_return_true_when_email_is_valid() throws Exception { assertThat(tested.isValid("[email protected]")).isTrue(); }
### Question: PolicyConditionCacheConfig { @Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); } @Bean GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled); }### Answer: @Test public void testPolicyConditionCacheConfigDisabled() { assertThat(this.policyConditionCacheConfig.conditionCache(true), instanceOf(NonCachingGroovyConditionCache.class)); } @Test public void testPolicyConditionCacheConfigEnabled() { assertThat(this.policyConditionCacheConfig.conditionCache(false), instanceOf(InMemoryGroovyConditionCache.class)); }
### Question: PolicyEvaluationRequestCacheKey { @Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; } PolicyEvaluationRequestCacheKey(final PolicyEvaluationRequestV1 request, final String zoneId); String toDecisionKey(); @Override int hashCode(); @Override boolean equals(final Object obj); PolicyEvaluationRequestV1 getRequest(); LinkedHashSet<String> getPolicySetIds(); String getResourceId(); String getSubjectId(); String getZoneId(); static final String ANY_POLICY_SET_KEY; static final LinkedHashSet<String> EVALUATION_ORDER_ANY_POLICY_SET_KEY; }### Answer: @Test public void testKeyEqualsForSameRequests() { PolicyEvaluationRequestV1 request = new PolicyEvaluationRequestV1(); request.setAction(ACTION_GET); request.setSubjectIdentifier(AGENT_MULDER); request.setResourceIdentifier(XFILES_ID); request.setPolicySetsEvaluationOrder(EVALUATION_ORDER_POLICYONE); PolicyEvaluationRequestCacheKey key = new PolicyEvaluationRequestCacheKey(request, ZONE_NAME); PolicyEvaluationRequestV1 otherRequest = new PolicyEvaluationRequestV1(); otherRequest.setAction(ACTION_GET); otherRequest.setSubjectIdentifier(AGENT_MULDER); otherRequest.setResourceIdentifier(XFILES_ID); otherRequest.setPolicySetsEvaluationOrder(EVALUATION_ORDER_POLICYONE); PolicyEvaluationRequestCacheKey otherKey = new PolicyEvaluationRequestCacheKey(otherRequest, ZONE_NAME); assertTrue(key.equals(otherKey)); } @Test public void testKeyEqualsForDifferentRequests() { PolicyEvaluationRequestV1 request = new PolicyEvaluationRequestV1(); request.setAction(ACTION_GET); request.setSubjectIdentifier(AGENT_MULDER); request.setResourceIdentifier(XFILES_ID); request.setPolicySetsEvaluationOrder(EVALUATION_ORDER_POLICYONE); PolicyEvaluationRequestCacheKey key = new PolicyEvaluationRequestCacheKey(request, ZONE_NAME); PolicyEvaluationRequestV1 otherRequest = new PolicyEvaluationRequestV1(); otherRequest.setAction(ACTION_GET); otherRequest.setSubjectIdentifier(AGENT_MULDER); otherRequest.setResourceIdentifier(XFILES_ID); PolicyEvaluationRequestCacheKey otherKey = new PolicyEvaluationRequestCacheKey(otherRequest, ZONE_NAME); assertFalse(key.equals(otherKey)); }
### Question: GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }### Answer: @Test(dataProvider = "validScript") public void testParseValidScript(final String script, final Map<String, Object> boundVariables, final boolean expectedResult) throws ConditionParsingException { ConditionScript parsedScript = this.shell.parse(script); Assert.assertNotNull(parsedScript); } @Test(dataProvider = "illegalScript", expectedExceptions = IllegalArgumentException.class) public void testParseBlankScript(final String script) throws ConditionParsingException { this.shell.parse(script); } @Test(dataProvider = "blackListedScript", expectedExceptions = ConditionParsingException.class) public void testParseBlackListedScript(final String script) throws ConditionParsingException { this.shell.parse(script); }
### Question: GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }### Answer: @Test(dataProvider = "validScript") public void testExecuteValidScript(final String script, final Map<String, Object> boundVariables, final boolean expectedResult) throws ConditionParsingException { Assert.assertEquals(this.shell.execute(script, boundVariables), expectedResult); } @Test(dataProvider = "illegalScript", expectedExceptions = IllegalArgumentException.class) public void testExecuteBlankScript(final String script) throws ConditionParsingException { this.shell.execute(script, emptyBindingMap); } @Test(dataProvider = "invalidScript", expectedExceptions = ClassCastException.class) public void testExecuteInvalidScript(final String script) throws ConditionParsingException { this.shell.execute(script, emptyBindingMap); } @Test(dataProvider = "blackListedScript", expectedExceptions = ConditionParsingException.class) public void testExecuteBlackListedScript(final String script) throws ConditionParsingException { this.shell.execute(script, emptyBindingMap); }
### Question: URL implements URLComponent, Validating, Comparable<URL> { public URL withProtocol(Protocol protocol) { if (protocol.equals(this.protocol)) { return this; } return new URL(userName, password, protocol, host, port, path, parameters, anchor); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }### Answer: @Test public void testWithProtocol() { URL u = URL.parse("http: URL u2 = u.withProtocol(Protocols.WS); assertEquals(u.getPath(), u2.getPath()); assertNotEquals(u.getProtocol(), u2.getProtocol()); assertEquals(Protocols.HTTP, u.getProtocol()); assertEquals(Protocols.WS, u2.getProtocol()); }
### Question: Path implements URLComponent, Iterable<PathElement> { public static Path parse(String path) { return Path.parse(path, false); } Path(PathElement... elements); Path(NormalizeResult n); static Path parse(String path); static Path parse(String path, boolean decode); Path toURLDecodedPath(); Iterator<PathElement> iterator(); PathElement lastElement(); Path normalize(); Path replace(String old, String nue); final Path elideEmptyElements(); Path prepend(String part); Path append(String part); static Path merge(Path... paths); boolean isParentOf(Path path); boolean isChildOf(Path path); int size(); PathElement[] getElements(); Path getChildPath(); String toStringWithLeadingSlash(); Path getParentPath(); boolean lastElementMatches(CharSequence s); boolean lastElementMatches(CharSequence s, boolean ignoreCase); @Override String toString(); static AbstractBuilder<PathElement, Path> builder(); @Override boolean isValid(); @Override String getComponentName(); boolean isProbableFileReference(); void appendTo(StringBuilder sb); PathElement getElement(int ix); PathElement getLastElement(); @Override boolean equals(Object obj); @Override int hashCode(); URI toURI(); URI toURIWithLeadingSlash(); String[] toStringArray(); }### Answer: @Test public void testLeadingAndTrailingSlashesDontAffectEquality() { Path a = Path.parse("foo/bar/baz"); Path b = Path.parse("/foo/bar/baz"); Path c = Path.parse("foo/bar/baz/"); Path d = Path.parse("/foo/bar/baz/"); Path e = Path.parse("foo/bar/baz/bean"); Path f = Path.parse("moo/bar/baz"); assertEquals(a, b); assertEquals(a, c); assertEquals(a, d); assertEquals(b, a); assertEquals(b, c); assertEquals(b, d); assertEquals(c, a); assertEquals(c, b); assertEquals(c, d); assertNotEquals(a, e); assertNotEquals(b, e); assertNotEquals(c, e); assertNotEquals(d, e); assertNotEquals(a, f); assertNotEquals(b, f); assertNotEquals(c, f); assertNotEquals(d, f); }
### Question: ChainRunner { @Inject public ChainRunner(ExecutorService svc, ReentrantScope scope) { Checks.notNull("svc", svc); Checks.notNull("scope", scope); this.svc = svc; this.scope = scope; } @Inject ChainRunner(ExecutorService svc, ReentrantScope scope); void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled); }### Answer: @Test(timeout = 10000) public void testChainRunner() throws Exception, Throwable { AtomicBoolean cancelled = new AtomicBoolean(); ChainRunner cr = new ChainRunner(svc, scope); TestCallback chainWithDeferResults = new TestCallback(); TestCallback dontRespondChainResults = new TestCallback(); TestCallback plainChainResults = new TestCallback(); TestCallback errorChainResults = new TestCallback(); TestCallback rejectChainResults = new TestCallback(); TestCallback remnantChainResults = new TestCallback(); try (AutoCloseable cl = scope.enter()) { cr.submit(chain, chainWithDeferResults, cancelled); cr.submit(dontRespond, dontRespondChainResults, cancelled); cr.submit(plainChain, plainChainResults, cancelled); cr.submit(errorChain, errorChainResults, cancelled); cr.submit(rejectIt, rejectChainResults, cancelled); cr.submit(remnantChain, remnantChainResults, cancelled); cr.submit(remnantChain, remnantChainResults, cancelled); } chainWithDeferResults.assertGotResponse().assertActeurClass(AddedA.class).throwIfError().assertNotRejected(); dontRespondChainResults.assertNoResponse().throwIfError(); plainChainResults.throwIfError().assertGotResponse().assertActeurClass(AddedA.class).assertNotRejected(); errorChainResults.assertException(SpecialError.class); rejectChainResults.throwIfError().assertRejected(); remnantChainResults.throwIfError().assertRejected(); }
### Question: ChainRunner { public <A extends AbstractActeur<T, R, S>, S extends ActeurState<T, R>, P extends Chain<? extends A, ?>, T, R extends T> void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled) { ActeurInvoker<A, S, P, T, R> cc = new ActeurInvoker<>(svc, scope, chain, onDone, cancelled); try (QuietAutoCloseable ac = scope.enter(chain, cc.deferral)) { if (firstSync) { try { cc.call(); } catch (Exception ex) { Exceptions.chuck(ex); } } else { svc.submit(scope.wrap(cc)); } } } @Inject ChainRunner(ExecutorService svc, ReentrantScope scope); void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled); }### Answer: @Test(timeout = 20000) public void testMultiChainRunner() throws Exception, Throwable { AtomicBoolean cancelled = new AtomicBoolean(); List<ArrayChain<AbstractActeur<Response, ResponseImpl, ActeurState<Response, ResponseImpl>>, ?>> l = new LinkedList<>(); for (int i = 0; i < 5; i++) { ArrayChain<AbstractActeur<Response, ResponseImpl, ActeurState<Response, ResponseImpl>>, ?> ch = new NamedChain("Chain " + i, deps, AbstractActeur.class) .add(FirstA.class).add(Rejecter.class).add(SecondWithoutTimeoutA.class).add(EndA.class); l.add(ch); } l.add(plainChain); ChainsRunner cr = new ChainsRunner(svc, scope, new ChainRunner(svc, scope)); TestCallback callback = new TestCallback(); cr.submit(l, callback, cancelled); callback.throwIfError().assertNotRejected().assertGotResponse(); l.remove(l.size() - 1); callback = new TestCallback(); cr.submit(l, callback, cancelled); callback.throwIfError().assertNoResponse(); }
### Question: StrictTransportSecurityHeader extends AbstractHeader<StrictTransportSecurity> { @Override public StrictTransportSecurity toValue(CharSequence value) { return StrictTransportSecurity.parse(value); } StrictTransportSecurityHeader(); @Override StrictTransportSecurity toValue(CharSequence value); @Override CharSequence toCharSequence(StrictTransportSecurity value); }### Answer: @Test public void testStrictTransportHeader() { HeaderValueType<StrictTransportSecurity> h = new StrictTransportSecurityHeader(); assertEquals(StrictTransportSecurity.FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD, h.toValue(StrictTransportSecurity.FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD.toString())); assertEquals(StrictTransportSecurity.ONE_YEAR, h.toValue(StrictTransportSecurity.ONE_YEAR.toString())); }
### Question: CookieHeaderNetty428 extends AbstractHeader<Cookie[]> { @Override public Cookie[] toValue(CharSequence value) { ServerCookieDecoder decoder = strict ? ServerCookieDecoder.STRICT : ServerCookieDecoder.LAX; Set<Cookie> result = decoder.decode(notNull("value", value).toString()); return result == null ? EMPTY : result.toArray(new Cookie[result.size()]); } CookieHeaderNetty428(boolean strict); @Override CharSequence toCharSequence(Cookie[] value); @Override Cookie[] toValue(CharSequence value); }### Answer: @Test @SuppressWarnings("deprecation") public void testLegacyCookies() { CookieHeader h = new CookieHeader(); io.netty.handler.codec.http.DefaultCookie a = new io.netty.handler.codec.http.DefaultCookie("a", "a"); io.netty.handler.codec.http.DefaultCookie b = new io.netty.handler.codec.http.DefaultCookie("b", "b"); io.netty.handler.codec.http.DefaultCookie c = new io.netty.handler.codec.http.DefaultCookie("c", "c"); String val = h.toString(new io.netty.handler.codec.http.Cookie[]{a, b, c}); io.netty.handler.codec.http.Cookie[] result = h.toValue(val); assertNotNull(result); assertNotNull(val); assertTrue("Should contain all cookies:" + val, val.contains("a") && val.contains("b") && val.contains("c")); assertEquals(3, result.length); }
### Question: FrameOptions { public static FrameOptions allowFrom(URI uri) { return new FrameOptions(FrameOptionType.ALLOW_FROM, notNull("uri", uri)); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); static final FrameOptions DENY; static final FrameOptions SAMEORIGIN; }### Answer: @Test public void testAllowFrom() { FrameOptions fo = FrameOptions.allowFrom(URI.create("http: assertEquals(URI.create("http: assertSame(FrameOptionType.ALLOW_FROM, fo.type()); assertEquals("ALLOW-FROM http: FrameOptions fo2 = FrameOptions.parse(fo.toString()); assertEquals(fo, fo2); assertEquals(fo.hashCode(), fo2.hashCode()); FrameOptions fo3 = FrameOptions.parse(fo.toString().toLowerCase()); assertEquals(fo, fo3); assertEquals(fo.hashCode(), fo3.hashCode()); assertEquals(fo.toString(), fo3.toString()); }
### Question: FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); static final FrameOptions DENY; static final FrameOptions SAMEORIGIN; }### Answer: @Test(expected=IllegalArgumentException.class) public void testMissingArgument() { FrameOptions.parse("DENY http: } @Test(expected=IllegalArgumentException.class) public void testMissingArgumen2t() { FrameOptions.parse("SAMEORIGIN http: } @Test(expected=IllegalArgumentException.class) public void testInvalidName() { FrameOptions.parse("PERCEIVE http: } @Test(expected=IllegalArgumentException.class) public void testInvalidName2() { FrameOptions.parse("DENI http: } @Test(expected=IllegalArgumentException.class) public void testInvalidUri() { FrameOptions.parse("ALLOW-FROM \\u0000 }
### Question: URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }### Answer: @Test public void testHostEquality() { Label l1 = new Label("one"); Label l2 = new Label("one"); Label l3 = new Label("ONE"); Label l4 = new Label("oNe"); assertEquals(l1, l2); assertEquals(l2, l3); assertEquals(l3, l4); assertEquals(l1, l4); assertEquals(l2, l4); Host one = Host.parse("WWW.Test.CoM"); Host two = Host.parse("www.test.com"); assertEquals(one, two); } @Test public void testParse() throws Exception { test("http: test("http: test("http: test("http: test("http: test("http: test("http: test("http: test("http: test("http: } @Test public void testHostParents() { Host h = Host.parse("www.timboudreau.com"); assertEquals(Host.parse("timboudreau.com"), h.getParentDomain()); Label[] l = h.getLabels(); assertEquals(new Label("com"), l[0]); assertEquals(new Label("timboudreau"), l[1]); assertEquals(new Label("www"), l[2]); assertEquals(new Label("com"), h.getTopLevelDomain()); assertEquals(new Label("timboudreau"), h.getDomain()); } @Test public void testSameDomain() { Host h = Host.parse("weblogs.java.net"); assertTrue(h.isDomain("java.net")); assertTrue(h.isDomain("weblogs.java.net")); assertFalse(h.isDomain("bubble.java.net")); assertFalse(h.isDomain("java.com")); }
### Question: StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); static final StrictTransportSecurity ONE_YEAR; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS_PRELOAD; static final StrictTransportSecurity FIVE_YEARS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD; }### Answer: @Test(expected=IllegalArgumentException.class) public void testInvalidParse1() { StrictTransportSecurity.parse(""); } @Test(expected=NullArgumentException.class) public void testInvalidConstruct() { StrictTransportSecurity.parse(null); } @Test(expected=IllegalArgumentException.class) public void testInvalidParse2() { StrictTransportSecurity.parse("preload; includeSubDomains; max-age=61; foodbar"); } @Test(expected=IllegalArgumentException.class) public void testInvalidParse3() { StrictTransportSecurity.parse("foodbar; preload; includeSubDomains; max-age=61;"); } @Test(expected=NumberFormatException.class) public void testInvalidParse4() { StrictTransportSecurity.parse("preload; includeSubDomains; max-age=073r8b;"); } @Test(expected=NumberFormatException.class) public void testInvalidParse5() { StrictTransportSecurity.parse("preload; includeSubDomains; max-age=infinity;"); }
### Question: PasswordHasher { public boolean checkPassword(String unhashed, String hashed) { try { String[] saltAndPassAndAlgorithm = findSalt(hashed); if (saltAndPassAndAlgorithm.length == 1) { byte[] bytes = hash(unhashed, algorithm); byte[] check = Base64.getDecoder().decode(hashed); return Arrays.equals(bytes, check); } if (saltAndPassAndAlgorithm.length != 3) { encryptPassword("DaCuBYLAlxBbT6lTyatauRp2iXCsf9WGDi8a2SyWeFVsoxGBk3Y3l1l9IHie" + "+aVuOGQBD8mZlrhj8yGjl1ghjw==", "3J5pgcx0", algorithm); return false; } String enc = encryptPassword(unhashed, saltAndPassAndAlgorithm[1], decodeAlgorithm(saltAndPassAndAlgorithm[0])); return slowEquals(enc, hashed); } catch (NoSuchAlgorithmException ex) { return Exceptions.chuck(ex); } } @Inject PasswordHasher(Settings settings, Charset charset); boolean checkPassword(String unhashed, String hashed); String hash(String s); String encryptPassword(String password); static final String SETTINGS_KEY_PASSWORD_SALT; static final String SETTINGS_KEY_HASHING_ALGORITHM; static final String DEFAULT_HASHING_ALGORITHM; static final String SETTINGS_KEY_RANDOM_SALT_LENGTH; static final int DEFAULT_RANDOM_SALT_LENGTH; }### Answer: @Test public void testCheckPassword() throws IOException, NoSuchAlgorithmException { assertTrue(true); PasswordHasher h = new PasswordHasher(new SettingsBuilder().build(), Charset.forName("UTF-8")); String pw = "password"; String enc = h.encryptPassword(pw); assertNotNull(enc); String pw2 = "somethingElse"; String enc2 = h.encryptPassword(pw2); assertNotNull(enc2); assertNotEquals(enc, enc2); boolean matches = h.checkPassword(pw2, enc2); assertTrue(matches); matches = h.checkPassword(pw, enc); assertTrue(matches); matches = h.checkPassword(pw2, enc); assertFalse(matches); matches = h.checkPassword(pw, enc2); assertFalse(matches); String old = "a:Du4EC8d82VujiPSlommA2XHrQLtUvytrowONoiG5q0yjG3Ed:4jhJV/hZ4Ab0liMsX0HDG/qJCIvgPCqyAeVB69n+ZdOWNWTXOCypD+WlzJELpKQ1/8tHL6jI709ogWTiJt0/9Q=="; assertTrue("Something has broken password compatibility", h.checkPassword("somethingElse", old)); old = "a:3wWOjtsJci7mL3wknhhtCsZnNmywjXI9w39Y2SiUVIfOaA2s:XZ6i/sDDGW0tEGYW3Bbcg1BitWugNm8DNQnx1p7CowRj9b0tkUQXRwqez60rSmRnBqOSRDw/4FUcg43fdliCZw=="; assertTrue("Something has broken password compatibility", h.checkPassword("password", old)); }
### Question: RotatingRealmProvider implements Provider<Realm> { @Override public Realm get() { Duration since1970 = Duration.ofMillis(System.currentTimeMillis()); long minutesSince1970 = since1970.toMinutes(); long intervals = minutesSince1970 / interval.toMinutes(); return new Realm(Strings.interleave(Long.toString(intervals, 36), salt)); } @Inject RotatingRealmProvider(Settings s); @Override Realm get(); static final String SETTINGS_KEY_ROTATE_INTERVAL_MINUTES; static final int DEFAULT_ROTATE_INTERVAL; }### Answer: @Test public void testDurationConversionWorks() { RotatingRealmProvider prov = new RotatingRealmProvider(Settings.EMPTY); Realm realm = prov.get(); assertEquals(realm, prov.get()); }
### Question: PagePathAndMethodFilter { public boolean match(HttpRequest req) { String path = this.basePathFilter.apply(req.uri()); if (path == null) { return false; } path = trimLeadingAndTrailingSlashes(trimQuery(path)); Method method = Method.get(req); MethodPath mp = new MethodPath(method, path); if (nonMatchesCache.contains(mp)) { return false; } if (matchesCache.contains(mp)) { return true; } ByMethod bm = all.get(mp.method); if (bm == null) { nonMatchesCache.add(mp); return false; } if (bm.match(mp.path)) { matchesCache.add(mp); return true; } else { nonMatchesCache.add(mp); return false; } } PagePathAndMethodFilter(Function<String, String> basePathFilter); PagePathAndMethodFilter(); PagePathAndMethodFilter(String basePath); @Override String toString(); boolean match(HttpRequest req); List<Object> listFor(HttpRequest req); }### Answer: @Test @SuppressWarnings("unchecked") public void testTypeMatching() { for (Class<?> c : classes) { Class<? extends Page> pg = (Class<? extends Page>) c; ShouldMatch shoulds = pg.getAnnotation(ShouldMatch.class); if (shoulds != null) { Method mth = pg.getAnnotation(Methods.class).value()[0]; for (String uri : shoulds.value()) { HttpRequest req = req(mth, uri); assertTrue(mth + " " + uri + " should be matched but isn't", pgs.match(req)); } } ShouldNotMatch shouldntss = pg.getAnnotation(ShouldNotMatch.class); if (shouldntss != null) { Method mth = pg.getAnnotation(Methods.class).value()[0]; for (String uri : shouldntss.value()) { HttpRequest req = req(mth, uri); assertFalse(mth + " " + uri + " should be matched but isn't", pgs.match(req)); } } } }
### Question: URL implements URLComponent, Validating, Comparable<URL> { @Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }### Answer: @Test public void testHighAsciiCharactersInPath() { PathElement el = new PathElement("foo"); assertTrue(el.isValid()); el = new PathElement(createHighAsciiString()); assertTrue(el.isValid()); } @Test public void testHighAsciiCharactersInLabel() { Label lbl = new Label("foo"); assertTrue(lbl.isValid()); lbl = new Label(createHighAsciiString()); assertFalse(lbl.isValid()); }
### Question: DefaultPathFactory implements PathFactory { @Override public URL constructURL(Path path) { return constructURL(path, secure); } @Inject DefaultPathFactory(Settings settings); @Override int portForProtocol(Protocol protocol); @Override Path toExternalPath(String path); @Override Path toExternalPath(Path path); @Override URL constructURL(Path path); @Override Path toPath(String uri); @Override URL constructURL(Protocol protocol, Path path); URL constructURL(Protocol protocol, Path path, boolean secure); URL constructURL(Protocol protocol, Path path, int port); @Override URL constructURL(Path path, boolean secure); @Override URL constructURL(String path, HttpEvent evt); }### Answer: @Test public void testNewerFeatures() throws Throwable { DefaultPathFactory f = new DefaultPathFactory(new SettingsBuilder() .add(ServerModule.SETTINGS_KEY_BASE_PATH, "/foo") .add(ServerModule.SETTINGS_KEY_GENERATE_SECURE_URLS, "true") .add(ServerModule.SETTINGS_KEY_URLS_HOST_NAME, "paths.example") .add(ServerModule.SETTINGS_KEY_URLS_EXTERNAL_PORT, 5720) .add(ServerModule.SETTINGS_KEY_URLS_EXTERNAL_SECURE_PORT, 5721) .build()); URL url = f.constructURL("/hey/you"); assertTrue(url.isValid()); String test1 = "https: String test2 = "https: assertEquals(test1 + "\tversus\n" + url, test1, url.toString()); assertEquals(url.toString(), f.constructURI("/hey/you").toString()); EventImpl fakeEvent = new EventImpl(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/up/down", new DefaultHttpHeaders().add(HttpHeaderNames.HOST, "timboudreau.org:5223")), f); url = f.constructURL("/whee?this=that&you=me", fakeEvent); assertTrue(url.isValid()); assertEquals("timboudreau.org", url.getHost().toString()); assertEquals(5223, url.getPort().intValue()); assertEquals(test2 + "\tversus\n" + url, test2, url.toString()); url = f.constructURL("/whee?this=that&you=me#woohoo", fakeEvent); assertTrue(url.isValid()); assertEquals("woohoo", url.getAnchor().toString()); assertNotNull(url + " has no parameters", url.getParameters()); assertTrue(url.getParameters().isValid()); fakeEvent = new EventImpl(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/up/down", new DefaultHttpHeaders() .add(Headers.X_FORWARDED_PROTO.name(), "http")), f); url = f.constructURL("/should/be/insecure", fakeEvent); assertEquals("/foo/should/be/insecure", url.getPath().toStringWithLeadingSlash()); assertEquals(HTTP, url.getProtocol()); assertEquals("paths.example", url.getHost().toString()); assertEquals(5720, url.getPort().intValue()); }
### Question: ByteBufCodec implements Codec<ByteBuf> { @Override public ByteBuf decode(BsonReader reader, DecoderContext dc) { ByteBuf buf = alloc.buffer(); JsonWriterSettings settings = JsonWriterSettings.builder() .indent(false).build(); PlainJsonWriter json = new PlainJsonWriter(buf, settings); json.pipe(reader); return buf; } @Inject ByteBufCodec(ByteBufAllocator alloc); void writeDateTime(BsonWriter writer, ZonedDateTime t, EncoderContext ec); @Override void encode(BsonWriter writer, ByteBuf t, EncoderContext ec); @Override Class<ByteBuf> getEncoderClass(); @Override ByteBuf decode(BsonReader reader, DecoderContext dc); }### Answer: @Test public void test(@Named("stuff") MongoCollection<Document> stuff) throws InterruptedException, IOException { byte[] bytes = new byte[120]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) (120 - i); } List<Object> list = new LinkedList<>(); list.add(1); list.add(2); list.add(2); list.add("hello"); list.add(new Document("in", "list")); Document document = new Document("hello", "world") .append("boolValue", true) .append("list", list) .append("intValue", 32) .append("dbl", 32.000235D) .append("subdoc", new Document("other", "stuff")) .append("longValue", Long.valueOf(Integer.MAX_VALUE + 1L)) .append("_id", new ObjectId()) .append("bytes", bytes); CB<Void> cb = new CB<Void>(); stuff.insertOne(document, cb); cb.get(); Thread.sleep(200); MongoCollection<ByteBuf> bbc = stuff.withDocumentClass(ByteBuf.class); CB<ByteBuf> bb = new CB<ByteBuf>(); bbc.find(new Document("_id", document.get("_id"))) .batchSize(1) .projection(new Document("hello", 1) .append("boolValue", 1) .append("intValue", 1) .append("longValue", 1) .append("dbl", 1) .append("list", 1) .append("subdoc", 1) .append("bytes", 1) .append("_id", 1)) .first(bb); ByteBuf buf = bb.get(); assertNotNull(buf); String content = Streams.readString(new ByteBufInputStream(buf)); buf.resetReaderIndex(); Map m = new ObjectMapper().readValue(content, Map.class); for (Map.Entry<String, Object> e : document.entrySet()) { Object other = m.get(e.getKey()); assertNotNull(e.getKey() + " is null", other); Object value = e.getValue(); assertNotNull(value); switch (e.getKey()) { case "_id": assertTrue(value instanceof ObjectId); assertTrue(other instanceof String); value = value.toString(); break; case "bytes": assertTrue(other.getClass().getName(), other instanceof String); other = Base64.getDecoder().decode((String)other); continue; } if (value instanceof byte[]) { assertTrue(other instanceof byte[]); assertTrue(value instanceof byte[]); assertArrayEquals((byte[]) value, (byte[]) other); } else { assertEquals(other, value); } } }
### Question: URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }### Answer: @Test public void testUnescape2() { StringBuilder sb = new StringBuilder(); for (char c = 1; c < 6; c++) { sb.append(c); } String unescaped = sb.toString(); String escaped = URLBuilder.escape(unescaped); String re_unescaped = URLBuilder.unescape(escaped); assertEquals(unescaped, re_unescaped); } @Test public void testUnescape3() { StringBuilder sb = new StringBuilder(); for (char c = 5; c < 25; c++) { sb.append(c); } String unescaped = sb.toString(); String escaped = URLBuilder.escape(unescaped); String re_unescaped = URLBuilder.unescape(escaped); assertEquals(unescaped, re_unescaped); } @Test public void testUnescape() { assertEquals("hello world", URLBuilder.unescape("hello%20world")); assertEquals(" ", URLBuilder.unescape("%20")); StringBuilder sb = new StringBuilder(); for (char c = 1; c < 255; c++) { if (c == 25) { continue; } sb.append(c); } String unescaped = sb.toString(); String escaped = URLBuilder.escape(unescaped); String re_unescaped = URLBuilder.unescape(escaped); assertEquals(examine(unescaped, re_unescaped), unescaped, re_unescaped); }
### Question: ValidationByResponseHandler { <T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } } }### Answer: @Test public void test_WHEN_valid_GIVEN_valid_model_THEN_ok_no_errors() { PersonModel person = new PersonModel( "Kim", "Kardashian", new GregorianCalendar(1980, Calendar.OCTOBER, 21)); ValidationByResponseHandler validator = new ValidationByResponseHandler(); Response response = validator.validate(person); assertThat(response.getStatus()).isEqualTo(200); } @Test public void test_WHEN_valid_GIVEN_invalid_model_THEN_error() { PersonModel person = new PersonModel( null, "", null); ValidationByResponseHandler validator = new ValidationByResponseHandler(); Response response = validator.validate(person); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.getEntity().toString()) .contains("Invalid Bean, constraint error(s) : ") .contains("birthDate may not be null.") .contains("firstName may not be null.") .contains("lastName size must be between 1 and 16."); }
### Question: ValidationByExceptionHandler { <T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } } }### Answer: @Test public void test_WHEN_valid_GIVEN_valid_model_THEN_ok_no_errors() { PersonModel person = new PersonModel( "Kim", "Kardashian", new GregorianCalendar(1980, Calendar.OCTOBER, 21)); ValidationByExceptionHandler validator = new ValidationByExceptionHandler(); validator.validate(person); } @Test public void test_WHEN_valid_GIVEN_invalid_model_THEN_error() { PersonModel person = new PersonModel( null, "", null); ValidationByExceptionHandler validator = new ValidationByExceptionHandler(); try { validator.validate(person); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()) .contains("Invalid Bean, constraint error(s) : ") .contains("birthDate may not be null.") .contains("firstName may not be null.") .contains("lastName size must be between 1 and 16."); } }
### Question: HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } static void main(String[] args); }### Answer: @Test public void test_batch_execution() { String[] args = { "10" }; HelloWorldBatch.main(args); } @Test public void test_args_validation() { try { HelloWorldBatch.main(null); fail("error expected"); } catch (IllegalArgumentException e) { } try { HelloWorldBatch.main(new String[] {}); fail("error expected"); } catch (IllegalArgumentException e) { } try { HelloWorldBatch.main(new String[] { null }); fail("error expected"); } catch (IllegalArgumentException e) { } } @Test(expected = RuntimeException.class) public void test_batch_execution_error() { HelloWorldBatch.main(new String[] { "ERROR" }); }
### Question: ProgressButton extends CompoundButton { public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }### Answer: @Test public void invalidProgressValue() { try { button.setProgress(101); fail("Setting progress > max should throw"); } catch (IllegalArgumentException e) { } } @Test public void anotherInvalidProgressValue() { try { button.setProgress(-1); fail("Setting progress < 0 should throw"); } catch (IllegalArgumentException e) { } }
### Question: ProgressButton extends CompoundButton { public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }### Answer: @Test public void setMaxToUnderZero() { try { button.setMax(-1); fail("Setting max <= 0 should throw"); } catch (IllegalArgumentException e) { } } @Test public void setMaxToZero() { try { button.setMax(0); fail("Setting max <= 0 should throw"); } catch (IllegalArgumentException e) { } }
### Question: ProgressButton extends CompoundButton { public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }### Answer: @Test public void onCheckedChangeListenerIsNotified() { CompoundButton.OnCheckedChangeListener publisher = mock(CompoundButton.OnCheckedChangeListener.class); button.setOnCheckedChangeListener(publisher); button.setPinned(true); verify(publisher).onCheckedChanged(button, true); button.setPinned(false); verify(publisher).onCheckedChanged(button, false); } @Test public void onCheckedChangeListenerIsNotifiedOnToggle() { button.setPinned(true); CompoundButton.OnCheckedChangeListener publisher = mock(CompoundButton.OnCheckedChangeListener.class); button.setOnCheckedChangeListener(publisher); button.toggle(); verify(publisher).onCheckedChanged(button, false); }
### Question: ProgressButton extends CompoundButton { @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); if (isSaveEnabled()) { SavedState ss = new SavedState(superState); ss.mMax = mMax; ss.mProgress = mProgress; return ss; } return superState; } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }### Answer: @Test public void onSaveInstanceState() { button.setProgress(72); button.setMax(842); final Parcelable parcelable = button.onSaveInstanceState(); button.setProgress(2); button.setMax(50); assertThat(button.getProgress()).isEqualTo(2); assertThat(button.getMax()).isEqualTo(50); button.onRestoreInstanceState(parcelable); assertThat(button.getProgress()).isEqualTo(72); assertThat(button.getMax()).isEqualTo(842); }
### Question: ProgressButton extends CompoundButton { public void setProgressAndMax(int progress, int max) { if (progress > max || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, max)); } else if (max <= 0) { throw new IllegalArgumentException(String.format("Max (%d) must be > 0", max)); } mProgress = progress; mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }### Answer: @Test public void settingInvalidProgressAndMax() { try { button.setProgressAndMax(10, 5); fail("Setting progress > max should throw"); } catch (IllegalArgumentException e) { } try { button.setProgressAndMax(0, 0); fail("Setting max = 0 should throw"); } catch (IllegalArgumentException e) { } try { button.setProgressAndMax(-1, 10); fail("Setting progress < 0 should throw"); } catch (IllegalArgumentException e) { } }
### Question: WriteController { @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) public void delete(@PathVariable(value = "id") String id, HttpServletResponse response) throws IOException { service.delete(id); } @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) @ResponseBody String create(@RequestParam("comment") final String comment, @RequestParam("pageId") final String pageId, @RequestParam("emailAddress") final String emailAddress, @RequestParam("username") final String username); @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) void delete(@PathVariable(value = "id") String id, HttpServletResponse response); @ExceptionHandler(EmptyResultDataAccessException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); }### Answer: @Test public void testDelete() throws Exception { CommentModel model = new CommentModel(); model.setUsername("testuser"); model.setId("dqe345e456rf34rw"); model.setPageId("product0815"); model.setEmailAddress("[email protected]"); model.setComment("I am the comment"); String id = service.put(model); this.mvc.perform(delete("/" + id)).andExpect(status().isOk()); assertNull(service.get(model.getId())); }
### Question: ReadController { @RequestMapping(value = "/list/{id}") public List<CommentDTO> getComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get comments for pageId {}", pageId); counterService.increment("commentstore.list_comments"); List<CommentModel> r = service.list(pageId); if (r.isEmpty()) { LOGGER.info("get comments for pageId {} - not found", pageId); throw new FileNotFoundException("/list/" + pageId); } LOGGER.info("get comments for pageId {} - done", pageId); return transformToDTO(r); } @RequestMapping(value = "/list/{id}") List<CommentDTO> getComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/listspam/{id}") List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/{id}", method=RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }) CommentDTO getComment(@PathVariable(value = "id") String commentId); @RequestMapping(value = "/comments") Page<CommentModel> listComments(@RequestParam(name="page", required=false) String pageIn, @RequestParam(name="size", required=false) String pageSizeIn); @ExceptionHandler(FileNotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); }### Answer: @Test public void testGetComments() throws Exception { CommentModel model = setupDummyModel(); List<CommentModel> mockReturn = new ArrayList<CommentModel>(); mockReturn.add(model); when(this.commentService.list( anyString())).thenReturn(mockReturn); this.mvc.perform(get("/list/" + model.getPageId())) .andExpect(status().is(200)) .andExpect(jsonPath("$[0].id", is(model.getId()))) .andExpect( jsonPath("$[0].created", is(SDF.format(model .getCreationDate().getTime())))) .andExpect(jsonPath("$[0].username", is(model.getUsername()))) .andExpect(jsonPath("$[0].comment", is(model.getComment()))) .andExpect( jsonPath("$[0].email_address", is(model.getEmailAddress()))); verify(this.commentService, times(1)).list( anyString()); }
### Question: ReadController { @RequestMapping(value = "/listspam/{id}") public List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get spam comments for pageId {}", pageId); counterService.increment("commentstore.list_spamcomments"); List<CommentModel> r = service.listSpamComments(pageId); LOGGER.info("get spam comments for pageId {} - done", pageId); return transformToDTO(r); } @RequestMapping(value = "/list/{id}") List<CommentDTO> getComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/listspam/{id}") List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/{id}", method=RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }) CommentDTO getComment(@PathVariable(value = "id") String commentId); @RequestMapping(value = "/comments") Page<CommentModel> listComments(@RequestParam(name="page", required=false) String pageIn, @RequestParam(name="size", required=false) String pageSizeIn); @ExceptionHandler(FileNotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); }### Answer: @Test public void testGetSpamComments() throws Exception { CommentModel model = setupDummyModel(); List<CommentModel> mockReturn = new ArrayList<CommentModel>(); mockReturn.add(model); when(this.commentService.list( anyString())).thenReturn(mockReturn); this.mvc.perform(get("/listspam/" + model.getPageId())) .andExpect(status().is(200)) .andExpect(jsonPath("$", hasSize(0))); ; }
### Question: Logger { public static void addLogPrinter(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.add(logPrinter); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); }### Answer: @Test(expected = NullPointerException.class) public void nullAddLogPrinter() { Logger.addLogPrinter(null); }
### Question: Logger { public static void removeLogPrint(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.remove(logPrinter); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); }### Answer: @Test(expected = NullPointerException.class) public void nullRemoveLogPrinter() { Logger.removeLogPrint(null); }
### Question: Logger { public static void d(String msg, Object...args) { logAdapter.d(msg, args); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); }### Answer: @Test public void dontAddLogPrinter() { String message = "Hello, world!"; Logger.d(message); assertLog() .hasNoMoreMessages(); }
### Question: Decorator implements Component { @Override public double calc(String user ,int seniority) { return this.component.calc(user ,seniority); } Decorator(Component component); @Override double calc(String user ,int seniority); }### Answer: @Test public void test() { String user = "zlikun" ; int seniority = 7 ; Component component = new ComponetImpl() ; Assert.assertEquals(0 ,component.calc(user ,seniority) ,0); Decorator d1 = new MonthDecorator(component) ; Assert.assertEquals(1000 ,d1.calc(user ,seniority) ,0); Decorator d2 = new YearDecorator(d1) ; Assert.assertEquals(3000 ,d2.calc(user ,seniority) ,0); }
### Question: Singleton2 { public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; } Singleton2(); static final Singleton2 getInstance(); }### Answer: @Test public void test_multi() { final ConcurrentMap<Singleton2 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(200) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton2.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertTrue(map.size() > 1); } @Test public void test_single() { Assert.assertTrue(Singleton2.getInstance() == Singleton2.getInstance()); Assert.assertTrue(new Singleton2() != new Singleton2()); }
### Question: TrainFactory { public String process() { StringBuilder sb = new StringBuilder() ; sb.append(builder.buildHeader()).append("-") ; sb.append(builder.buildBody()).append("-") ; sb.append(builder.buildFooter()) ; return sb.toString() ; } TrainFactory(TrainBuilder builder); String process(); }### Answer: @Test public void test() { TrainFactory factory = new TrainFactory(new TrainBuilder()) ; String train = factory.process() ; Assert.assertEquals("火车头-火车身-火车尾" ,train); }
### Question: Singleton0 { public static final Singleton0 getInstance() { return INSTANCE ; } private Singleton0(); static final Singleton0 getInstance(); }### Answer: @Test public void test_single() { Assert.assertTrue(Singleton0.getInstance() == Singleton0.getInstance()); } @Test public void test_multi() { final Set<Singleton0> set = new HashSet<>() ; ExecutorService exec = Executors.newFixedThreadPool(50) ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { set.add(Singleton0.getInstance()) ; } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,set.size()); }
### Question: Singleton5 { public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; } private Singleton5(); static final Singleton5 getInstance(); }### Answer: @Test public void test_single() { Assert.assertTrue(Singleton5.getInstance() == Singleton5.getInstance()); } @Test public void test_multi() { final ConcurrentMap<Singleton5 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(400) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton5.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,map.size()); }
### Question: Singleton3 { public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; } private Singleton3(); static final Singleton3 getInstance(); }### Answer: @Test public void test_single() { Assert.assertTrue(Singleton3.getInstance() == Singleton3.getInstance()); } @Test public void test_multi() { final ConcurrentMap<Singleton3 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(400) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton3.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,map.size()); }
### Question: Singleton4 { public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; } private Singleton4(); static final Singleton4 getInstance(); }### Answer: @Test public void test_single() { Assert.assertTrue(Singleton4.getInstance() == Singleton4.getInstance()); } @Test public void test_multi() { final ConcurrentMap<Singleton4 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(400) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton4.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,map.size()); }
### Question: BasicRule_5_Builder extends BasicRuleBuilder { public BasicRule create_BR_5(Rule rule) throws Exception { try { String finalEml; String title = rule.getTitle(); String incomingObservationsCountPatternId = title + "_incoming_observations_count_stream"; String incomingObservationsEventName = title + "_incoming_observations_count"; String noObservationsReceivedStreamPatternId = title + "_no_observation_received_stream"; String observationsReceivedStreamPatternId = title + "_observation_received_stream"; String noObservationsNotificationPatternId = title + "_no_observation_notification"; String observationsNotificationPatternId = title + "_observation_notification"; String noObservationsReceivedEventName = title + "_no_observation_received"; String observationsReceivedEventName = title + "_observation_received"; String noObservationsOutputName = title + "_no_observation_output"; String observationsOutputName = title + "_observation_output"; EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); SimplePatternType incomingObservationCount = simplePatterns.getSimplePatternArray(0); processSimplePattern(incomingObservationCount, incomingObservationsCountPatternId, incomingObservationsEventName); processPropertyRestrictions(incomingObservationCount, rule.getTimeseriesMetadata()); processDurationValue(incomingObservationCount, rule); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); ComplexPattern noObservationsReceived = complexPatterns.getComplexPatternArray(0); processComplexPattern(noObservationsReceived, noObservationsReceivedStreamPatternId, noObservationsReceivedEventName); setSelectEventName(noObservationsReceived, incomingObservationsEventName); noObservationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); noObservationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processEqualToFilterGuard(noObservationsReceived, incomingObservationsEventName); ComplexPattern observationsReceived = complexPatterns.getComplexPatternArray(1); processComplexPattern(observationsReceived, observationsReceivedStreamPatternId, observationsReceivedEventName); setSelectEventName(observationsReceived, incomingObservationsEventName); observationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); observationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processNotEqualToFilterGuard(observationsReceived, incomingObservationsEventName); ComplexPattern noObservationsReceivedNotification = complexPatterns.getComplexPatternArray(2); processComplexPattern(noObservationsReceivedNotification, noObservationsNotificationPatternId, noObservationsReceivedEventName); setOutputName(noObservationsReceivedNotification, noObservationsOutputName); noObservationsReceivedNotification.getFirstPattern().setPatternReference(observationsReceivedStreamPatternId); noObservationsReceivedNotification.getSecondPattern().setPatternReference(noObservationsReceivedStreamPatternId); ComplexPattern observationsReceivedNotification = complexPatterns.getComplexPatternArray(3); processComplexPattern(observationsReceivedNotification, observationsNotificationPatternId, observationsReceivedEventName); setOutputName(observationsReceivedNotification, observationsOutputName); observationsReceivedNotification.getFirstPattern().setPatternReference(noObservationsReceivedStreamPatternId); observationsReceivedNotification.getSecondPattern().setPatternReference(observationsReceivedStreamPatternId); finalEml = emlTemplateDoc.xmlText(); User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR5", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } } BasicRule_5_Builder(); BasicRule create_BR_5(Rule rule); Rule getRuleByEML(BasicRule basicRule); }### Answer: @Test public void havingRule_parseEmlFromBasicRule_noXmlErrors() throws Exception { String eml = builder.create_BR_5(rule).getEml(); assertThat(XMLBeansParser.validate(XmlObject.Factory.parse(eml)), is(empty())); }
### Question: QueryParser { public Collection<String> parseFeatures() { String featureValues = kvps.get(FEATURES.name()); return parseCommaSeparatedValues(featureValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }### Answer: @Test public void testParseStationKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("features=").append("Heldra_41700105"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedStations = parser.parseFeatures(); assertTrue("Invalid size: " + parsedStations.size(), parsedStations.size() == 1); assertTrue("Stations could not be parsed.", parsedStations.contains("Heldra_41700105")); }
### Question: QueryParser { public Collection<String> parsePhenomenons() { String phenomenonValues = kvps.get(PHENOMENONS.name()); return parseCommaSeparatedValues(phenomenonValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }### Answer: @Test public void testParsePhenomenonsKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("phenomenons=").append("Wasserstand"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedPhenomenons = parser.parsePhenomenons(); assertTrue("Invalid size: " + parsedPhenomenons.size(), parsedPhenomenons.size() == 1); assertTrue("Stations could not be parsed.", parsedPhenomenons.contains("Wasserstand")); }
### Question: QueryParser { public Collection<String> parseProcedures() { String procedureValues = kvps.get(PROCEDURES.name()); return parseCommaSeparatedValues(procedureValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }### Answer: @Test public void testParseProceduresKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("procedures=").append("Wasserstand-Heldra_41700105"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedProcedures = parser.parseProcedures(); assertTrue("Invalid size: " + parsedProcedures.size(), parsedProcedures.size() == 1); assertTrue("Stations could not be parsed.", parsedProcedures.contains("Wasserstand-Heldra_41700105")); }
### Question: QueryParser { public TimeRange parseTimeRange() { String begin = kvps.get(BEGIN.name()); String end = kvps.get(END.name()); return TimeRange.createTimeRange(begin, end); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }### Answer: @Test public void testParsingBeginAndEndKvps() { StringBuilder validQuery = new StringBuilder(); validQuery.append("begin"); validQuery.append("="); validQuery.append("2012-10-01T12:01:00"); validQuery.append("&"); validQuery.append("end"); validQuery.append("="); validQuery.append("2014-10-01T12:01:00"); QueryParser parser = new QueryParser(validQuery.toString(), false); TimeRange parsedTimeRange = parser.parseTimeRange(); assertEquals("2012-10-01T12:01:00", parsedTimeRange.getStart()); assertEquals("2014-10-01T12:01:00", parsedTimeRange.getEnd()); }
### Question: XmlHelper { public <T> T parseFirst(XmlObject from, String xPath, Class<T> ofType) { T[] results = parseAll(from, xPath, ofType); return results.length > 0 ? results[0] : null; } XmlHelper(Map<String, String> namespaceDecarations); String getShortName(IdentifierList identifiers); String getUniqueId(IdentifierList identifiers); String[] getRelatedFeatures(Capabilities identifiers); PointDocument getPoint(FeaturePropertyType member, CRSUtils referenceHelper); String[] getRelatedPhenomena(Outputs outputs); T parseFirst(XmlObject from, String xPath, Class<T> ofType); @SuppressWarnings("unchecked") T[] parseAll(XmlObject from, String xPath, Class<T> ofType); }### Answer: @Test public void shouldParseSystemViaXPath() { SystemType systemType = xmlHelper.parseFirst(smlDoc, "$this assertNotNull(systemType); }
### Question: TimeseriesFactory { public TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType) { TimeSeries timeSeries = new TimeSeries(timeseries.getTimeseriesId()); ITimePosition timeArray[] = collection.getSortedTimeArray(); ObservedValueTuple prevObservation; ObservedValueTuple nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[0]); ObservedValueTuple observation = nextObservation; int counter = 0; Double sum = 0.0; LOGGER.debug("Compressionlevel none"); for (int i = 0; i < timeArray.length; i++) { prevObservation = observation; observation = nextObservation; if (i + 1 < timeArray.length) { nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[i + 1]); } counter++; Double resultVal = getValidData(observation.getValue(0).toString()); if (seriesType.equals("1")) { } else if (seriesType.equals("2")) { if (resultVal != null) { resultVal += sum; } else { resultVal = sum; } } else { } sum = resultVal; ITimePosition timePos = (ITimePosition) observation.getTime(); DateTime time = DateTime.parse(timePos.toISO8601Format()); timeSeries.add(new FixedMillisecond(time.getMillis()), resultVal); } LOGGER.debug("Compressed observations from " + timeArray.length + " to " + counter); return timeSeries; } TimeseriesFactory(ObservationSeriesCollection collection); TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType); TimeSeries compressToTimeSeries(SosTimeseries timeseries, boolean force, String seriesType); HashMap<Long, Double> compressToHashMap(String foiID, String phenID, String procID); }### Answer: @Test public void shouldNotAddValuesTwiceWhenCreatingTimeseriesDuringDaylightSavingSwitch() throws Exception { SosTimeseries timeseries = createSosTimeseries(); GetObservationResponseToOxfFeatureCollectionReader reader = createReader(); String[] foiIds = new String[]{timeseries.getFeatureId()}; String[] procedureIds = new String[]{timeseries.getProcedureId()}; String[] observedPropertyIds = new String[]{timeseries.getPhenomenonId()}; OXFFeatureCollection obsColl = reader.getFeatureCollection(); ObservationSeriesCollection seriesCollection = new ObservationSeriesCollection(obsColl, foiIds, observedPropertyIds, procedureIds, true); assertThat(seriesCollection.getAllTuples().size(), is(277)); TimeseriesFactory factory = new TimeseriesFactory(seriesCollection); TimeSeries chartTimeseries = factory.createTimeSeries(timeseries, "1"); assertThat(chartTimeseries.getItemCount(), is(277)); }
### Question: SosMetadataUpdate { protected static String createPostfix(String url) { if (url.startsWith("http: url = url.substring("http: } return url.replaceAll("/", "_").replaceAll("\\?", "_").replaceAll(":", "_").replaceAll("@", "_"); } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); }### Answer: @Test public void testCreatePostfix() { String postfix = SosMetadataUpdate.createPostfix(validServiceUrl); assertEquals("my.server.net_52n-SOS-Vx.x_sos", postfix); }
### Question: SosMetadataUpdate { protected static File getCacheTarget(String serviceUrl) { String postfix = createPostfix(serviceUrl); return new File(generateCacheFilePath(postfix)); } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); }### Answer: @Test public void testGetCacheTarget() { File expected = new File(cacheTargetFile); File cacheTarget = SosMetadataUpdate.getCacheTarget(validServiceUrl); assertEquals(expected.getAbsoluteFile(), cacheTarget.getAbsoluteFile()); }
### Question: SosMetadataUpdate { protected static void prepareCacheTargetDirectory() throws IOException { File cacheDirectory = getCacheDir(); if (!cacheDirectory.exists() && !cacheDirectory.mkdirs()) { throw new IOException("Unable to create cache directory."); } } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); }### Answer: @Test public void testPrepareCacheTarget() throws IOException { SosMetadataUpdate.prepareCacheTargetDirectory(); assertTrue(temporalCacheDirectory.exists()); }
### Question: BasicRule_4_Builder extends BasicRuleBuilder { public BasicRule create(Rule rule) { String title = rule.getTitle(); this.overshootPatternId = title + this.overshootStream; this.undershootPatternId = title + this.undershootStream; this.entryNotificationPatternId = title + this.overshootNotificationStream; this.exitNotificationPatternId = title + this.undershootNotificationStream; this.overshootEventName = title + this.overshoot; this.undershootEventName = title + this.undershoot; this.entryEventName = title + this.overshootNotification; this.exitEventName = title + this.undershootNotification; this.output_enter = title + this.enter; this.output_exit = title + this.exit; try { EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); SimplePatternType staticInitPattern = simplePatterns.getSimplePatternArray(INDEX_SIMPLE_PATTERN_INTIAL_COUNT); processPropertyRestrictions(staticInitPattern, rule.getTimeseriesMetadata()); RuleFilter entryFilter = createEntryFilter(rule); SimplePatternType ruleUndershoot = simplePatterns.getSimplePatternArray(INDEX_ENTRY_CONDITION_PATTERN); processSimplePattern(ruleUndershoot, overshootPatternId, overshootEventName); processPropertyRestrictions(ruleUndershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleUndershoot.getGuard(), entryFilter, INPUT_STREAM_NAME); RuleFilter exitFilter = createExitFilter(rule); SimplePatternType ruleOvershoot = simplePatterns.getSimplePatternArray(INDEX_EXIT_CONDITION_PATTERN); processSimplePattern(ruleOvershoot, undershootPatternId, undershootEventName); processPropertyRestrictions(ruleOvershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleOvershoot.getGuard(), exitFilter, INPUT_STREAM_NAME); ComplexPattern entryClause = complexPatterns.getComplexPatternArray(INDEX_ENTRY_NOTIFICATION_PATTERN); processComplexPattern(entryClause, entryNotificationPatternId, entryEventName, output_enter); entryClause.getFirstPattern().setPatternReference(undershootPatternId); entryClause.getSecondPattern().setPatternReference(overshootPatternId); ComplexPattern exitClause = complexPatterns.getComplexPatternArray(INDEX_EXIT_NOTIFICATION_PATTERN); processComplexPattern(exitClause, exitNotificationPatternId, exitEventName, output_exit); exitClause.getFirstPattern().setPatternReference(overshootPatternId); exitClause.getSecondPattern().setPatternReference(undershootPatternId); ComplexPattern initialEntryClause = complexPatterns.getComplexPatternArray(INDEX_COMPLEX_PATTERN_INTIAL_ENTRY); processFilterGuard(initialEntryClause.getGuard(), entryFilter, INITIAL_STREAM_NAME); eml = emlTemplateDoc.xmlText(); finalEml = eml; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR4", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } BasicRule_4_Builder(); BasicRule create(Rule rule); Rule getRuleByEML(BasicRule basicRule); }### Answer: @Test public void havingRule_parseEmlFromBasicRule_noXmlErrors() throws Exception { String eml = builder.create(rule).getEml(); assertThat(XMLBeansParser.validate(XmlObject.Factory.parse(eml)), is(empty())); }
### Question: DescribeSensorParser { public HashMap<String, ReferenceValue> parseReferenceValues() { final Capabilities[] capabilities = getSensorMLCapabilities(smlDoc.getSensorML()); final HashMap<String, ReferenceValue> map = new HashMap<String, ReferenceValue>(); if (capabilities == null || capabilities.length == 0) { return map; } for (final Capabilities capability : capabilities) { final AbstractDataRecordType abstractDataRecord = capability.getAbstractDataRecord(); if (abstractDataRecord instanceof SimpleDataRecordType) { final SimpleDataRecordType simpleDataRecord = (SimpleDataRecordType) abstractDataRecord; for (final AnyScalarPropertyType field : simpleDataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } else if (abstractDataRecord instanceof DataRecordType) { final DataRecordType dataRecord = (DataRecordType) abstractDataRecord; for (final DataComponentPropertyType field : dataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } } return map; } DescribeSensorParser(final InputStream inputStream, final SOSMetadata metadata); String buildUpSensorMetadataStationName(); String buildUpSensorMetadataUom(final String phenomenonID); String buildUpSensorMetadataHtmlUrl(final SosTimeseries timeseries); String createSensorDescriptionFileName(final SosTimeseries timeseries); Point buildUpSensorMetadataPosition(); HashMap<String, ReferenceValue> parseReferenceValues(); List<String> parseFOIReferences(); List<String> getPhenomenons(); static SensorMLDocument unwrapSensorMLFrom(XmlObject xmlObject); void setReferencingHelper(final CRSUtils refHelper); }### Answer: @Test public void shouldParseReferenceValuesFromCapabilitiesSection() { assertThat(parser.parseReferenceValues().size(), is(5)); }
### Question: DescribeSensorParser { public static SensorMLDocument unwrapSensorMLFrom(XmlObject xmlObject) throws XmlException, XMLHandlingException, IOException { if (SoapUtil.isSoapEnvelope(xmlObject)) { xmlObject = SoapUtil.stripSoapEnvelope(xmlObject); } if (xmlObject instanceof SensorMLDocument) { return (SensorMLDocument) xmlObject; } if (xmlObject instanceof DescribeSensorResponseDocument) { DescribeSensorResponseDocument responseDoc = (DescribeSensorResponseDocument) xmlObject; DescribeSensorResponseType response = responseDoc.getDescribeSensorResponse(); DescribeSensorResponseType.Description[] descriptionArray = response.getDescriptionArray(); if (descriptionArray.length == 0) { LOGGER.warn("No SensorDescription available in response!"); } else { for (DescribeSensorResponseType.Description description : descriptionArray) { SensorDescriptionType.Data dataDescription = description.getSensorDescription().getData(); String namespace = "declare namespace gml='http: for (XmlObject xml : dataDescription.selectPath(namespace + "$this XmlCursor cursor = xml.newCursor(); String gmlId = cursor.getTextValue(); if ( !NcNameResolver.isNCName(gmlId)) { cursor.setTextValue(NcNameResolver.fixNcName(gmlId)); } } XmlObject object = XmlObject.Factory.parse(dataDescription.xmlText()); if (object instanceof SystemDocumentImpl) { SensorMLDocument smlDoc = SensorMLDocument.Factory.newInstance(); SensorMLDocument.SensorML.Member member = smlDoc.addNewSensorML().addNewMember(); member.set(XMLBeansParser.parse(object.newInputStream())); return smlDoc; } return SensorMLDocument.Factory.parse(dataDescription.newInputStream()); } } } LOGGER.warn("Failed to unwrap SensorML from '{}'. Return an empty description.", xmlObject.xmlText()); return SensorMLDocument.Factory.newInstance(); } DescribeSensorParser(final InputStream inputStream, final SOSMetadata metadata); String buildUpSensorMetadataStationName(); String buildUpSensorMetadataUom(final String phenomenonID); String buildUpSensorMetadataHtmlUrl(final SosTimeseries timeseries); String createSensorDescriptionFileName(final SosTimeseries timeseries); Point buildUpSensorMetadataPosition(); HashMap<String, ReferenceValue> parseReferenceValues(); List<String> parseFOIReferences(); List<String> getPhenomenons(); static SensorMLDocument unwrapSensorMLFrom(XmlObject xmlObject); void setReferencingHelper(final CRSUtils refHelper); }### Answer: @Test public void shouldUnwrapSensorMLFromDescribeSensorResponseAndSoapEnvelope() throws XmlException, IOException, XMLHandlingException { XmlObject response = XmlFileLoader.loadXmlFileViaClassloader(soapResponse, getClass()); response = DescribeSensorParser.unwrapSensorMLFrom(response); SensorMLDocument.class.cast(response); } @Test public void shouldUnwrapSensorMLFromDescribeSensorResponse() throws XmlException, IOException, XMLHandlingException { XmlObject response = XmlFileLoader.loadXmlFileViaClassloader(poxResponse, getClass()); response = DescribeSensorParser.unwrapSensorMLFrom(response); SensorMLDocument.class.cast(response); } @Test public void shouldUnwrapSensorMLFromPlainSensorMLResponse() throws XmlException, IOException, XMLHandlingException { XmlObject response = XmlFileLoader.loadXmlFileViaClassloader(smlResponse, getClass()); response = DescribeSensorParser.unwrapSensorMLFrom(response); SensorMLDocument.class.cast(response); }
### Question: SOSRequestBuilderGET_200 implements ISOSRequestBuilder { String encodePlusInParameter(String parameter) { return parameter.replace("+", "%2B"); } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); @Override String buildDescribeSensorRequest(ParameterContainer parameters); @Override String buildGetFeatureOfInterestRequest(ParameterContainer parameters); String encode(String parameter); @Override String buildGetObservationByIDRequest(ParameterContainer parameters); @Override String buildInsertObservation(ParameterContainer parameters); @Override String buildRegisterSensor(ParameterContainer parameters); }### Answer: @Test public void testEncodePlusInParameter() { String encoded = builder.encodePlusInParameter("a string with a \"+\""); assertEquals("a string with a \"%2B\"", encoded); }
### Question: SOSRequestBuilderGET_200 implements ISOSRequestBuilder { String fixTimeZone(String timeString) { StringBuilder sb = new StringBuilder(timeString); int insertionIndex = timeString.length() - 2; if (sb.charAt(insertionIndex - 1) != ':') { sb.insert(insertionIndex, ":"); } return sb.toString(); } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); @Override String buildDescribeSensorRequest(ParameterContainer parameters); @Override String buildGetFeatureOfInterestRequest(ParameterContainer parameters); String encode(String parameter); @Override String buildGetObservationByIDRequest(ParameterContainer parameters); @Override String buildInsertObservation(ParameterContainer parameters); @Override String buildRegisterSensor(ParameterContainer parameters); }### Answer: @Test public void testFixTimeZone() { String incorrectTime = "2012-08-06T13:49:30.0+0200"; String correctTime = builder.fixTimeZone(incorrectTime); assertEquals("2012-08-06T13:49:30.0+02:00", correctTime); }
### Question: SOSRequestBuilderGET_200 implements ISOSRequestBuilder { public String encode(String parameter) { try { return encodePlusInParameter(URLEncoder.encode(parameter, "utf-8")); } catch (UnsupportedEncodingException e) { LOGGER.warn("Could not encode parameter {}!", parameter); return parameter; } } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); @Override String buildDescribeSensorRequest(ParameterContainer parameters); @Override String buildGetFeatureOfInterestRequest(ParameterContainer parameters); String encode(String parameter); @Override String buildGetObservationByIDRequest(ParameterContainer parameters); @Override String buildInsertObservation(ParameterContainer parameters); @Override String buildRegisterSensor(ParameterContainer parameters); }### Answer: @Test public void testEncodeParameter() { String encoded = builder.encode("2012-08-06T13:49:30.0+02:00"); assertEquals("2012-08-06T13%3A49%3A30.0%2B02%3A00", encoded); String encodedCharacters = builder.encode("#$&'()+,/:;=?@[]"); assertEquals("%23%24%26%27%28%29%2B%2C%2F%3A%3B%3D%3F%40%5B%5D", encodedCharacters); }
### Question: SOSRequestBuilderGET_200 implements ISOSRequestBuilder { String createIso8601Duration(String start, String end) { StringBuilder sb = new StringBuilder(); sb.append(fixTimeZone(start)).append("/"); return sb.append(fixTimeZone(end)).toString(); } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); @Override String buildDescribeSensorRequest(ParameterContainer parameters); @Override String buildGetFeatureOfInterestRequest(ParameterContainer parameters); String encode(String parameter); @Override String buildGetObservationByIDRequest(ParameterContainer parameters); @Override String buildInsertObservation(ParameterContainer parameters); @Override String buildRegisterSensor(ParameterContainer parameters); }### Answer: @Test public void testCreateIso8601Duration() { String start = "2012-08-06T13:49:30.0+02:00"; String end = "2012-08-01T13:49:30.0+02:00"; String duration = builder.createIso8601Duration(start, end); assertEquals("2012-08-06T13:49:30.0+02:00/2012-08-01T13:49:30.0+02:00", duration); }
### Question: ClientUtils { public static String[] splitJsonObjects(String value) { int openCurlies = 0; List<String> objects = new ArrayList<String>(); StringBuilder object = new StringBuilder(); for (int i=0; i < value.length() ; i++) { char currentChar = value.charAt(i); object.append(currentChar); if (currentChar == '{') { openCurlies++; } if (currentChar == '}') { openCurlies--; } if (openCurlies == 0) { objects.add(object.toString()); object = new StringBuilder(); i++; } } return objects.toArray(new String[0]); } private ClientUtils(); static String getRandomHexColor(); static boolean isValidTimeFrameForZoomIn(long begin, long end); static String[] getDecodedParameters(PermalinkParameter parameter); static String[] getDecodedParameters(String parameter); static String[] splitJsonObjects(String value); static boolean isSesEnabled(); }### Answer: @Test public void shouldReadEmptyJson() { assertThat(splitJsonObjects("{}").length, is(1)); } @Test public void shouldReadSingleJsonObject() { assertThat(splitJsonObjects("{\"parameter\":\"value\"}").length, is(1)); } @Test public void shouldReadMultipleJsonObject() { assertThat(splitJsonObjects("{\"parameter\":\"value\"},{\\\"parameter\\\":\\\"value\\\"}").length, is(2)); } @Test public void shouldReturnEmptyArrayIfInvalid() { assertThat(splitJsonObjects("{\"parameter\":\"value\"").length, is(0)); }
### Question: QueryBuilder { String encodeValue(String value) { value = value.replace("%", "%25"); value = value.replace("+", "%2B"); value = value.replace(" ", "+"); value = value.replace("!", "%21"); value = value.replace("#", "%23"); value = value.replace("$", "%24"); value = value.replace("&", "%26"); value = value.replace("'", "%27"); value = value.replace("(", "%28"); value = value.replace(")", "%29"); value = value.replace(",", "%2C"); value = value.replace("/", "%2F"); value = value.replace(":", "%3A"); value = value.replace(";", "%3B"); value = value.replace("=", "%3D"); value = value.replace("?", "%3F"); value = value.replace("@", "%40"); value = value.replace("[", "%5B"); value = value.replace("]", "%5D"); return value; } void removeLastComma(StringBuilder builder); int length(); void appendCompressedParameter(); StringBuilder initialize(String baseUrl); @Override String toString(); }### Answer: @Test public void testEncodeValues() { queryBuilder = new QueryBuilder(); assertEquals("value+with+spaces", queryBuilder.encodeValue("value with spaces")); assertEquals("value%2Cwith%2Ccommas", queryBuilder.encodeValue("value,with,commas")); assertEquals("value+with+spaces%2Bplus+sign", queryBuilder.encodeValue("value with spaces+plus sign")); assertEquals("%21+%23+%24", queryBuilder.encodeValue("! # $")); assertEquals("%25+%26+%27+%28", queryBuilder.encodeValue("% & ' (")); assertEquals("%26+%27+%25+%28", queryBuilder.encodeValue("& ' % (")); }
### Question: EventSubscriptionController { String replaceNonAlphaNumerics(String toReplace) { return toReplace.replaceAll("[^0-9a-zA-Z_]", "_"); } void setTimeseries(TimeseriesLegendData timeseries); TimeseriesLegendData getTimeSeries(); String getServiceUrl(); String getOffering(); String getPhenomenon(); String getProcedure(); String getFeatureOfInterest(); void setSelectedAbonnementName(String currentAbonnementName); String getSelectedAbonnementName(); boolean isSelectionValid(); void setSelectedSubscriptionTemplate(SubscriptionTemplate template); void updateSelectedRuleTemplate(SubscriptionTemplate template); String createSuggestedAbonnementName(); SimpleRuleType getSelectedRuleTemplate(); OverUndershootSelectionData getOverUndershootEntryConditions(); OverUndershootSelectionData getOverUndershootExitConditions(); SensorLossSelectionData getSensorLossConditions(); void clearSelectionData(); Rule createSimpleRuleFromSelection(); }### Answer: @Test public void shouldReplaceAllNonAlphaNumericsWithUnderscore() { assertThat(controllerUnderTest.replaceNonAlphaNumerics("#'+`´^°!§$%&/()=?-"), is("__________________")); } @Test public void shouldNotReplaceAlphaNumericsWithUnderscores() { assertThat(controllerUnderTest.replaceNonAlphaNumerics("ABCNksdfjiu098723049234lkjdsf"), is("ABCNksdfjiu098723049234lkjdsf")); }
### Question: EventSubscriptionController { String replaceAllUmlauts(String toReplace) { toReplace = toReplace.replaceAll("[ö]", "oe"); toReplace = toReplace.replaceAll("^Ö", "Oe"); toReplace = toReplace.replaceAll("[Ö]", "OE"); toReplace = toReplace.replaceAll("[ä]", "ae"); toReplace = toReplace.replaceAll("^Ä", "Ae"); toReplace = toReplace.replaceAll("[Ä]", "AE"); toReplace = toReplace.replaceAll("[ü]", "ue"); toReplace = toReplace.replaceAll("^Ü", "Ue"); toReplace = toReplace.replaceAll("[Ü]", "UE"); toReplace = toReplace.replaceAll("[ß]", "ss"); return toReplace; } void setTimeseries(TimeseriesLegendData timeseries); TimeseriesLegendData getTimeSeries(); String getServiceUrl(); String getOffering(); String getPhenomenon(); String getProcedure(); String getFeatureOfInterest(); void setSelectedAbonnementName(String currentAbonnementName); String getSelectedAbonnementName(); boolean isSelectionValid(); void setSelectedSubscriptionTemplate(SubscriptionTemplate template); void updateSelectedRuleTemplate(SubscriptionTemplate template); String createSuggestedAbonnementName(); SimpleRuleType getSelectedRuleTemplate(); OverUndershootSelectionData getOverUndershootEntryConditions(); OverUndershootSelectionData getOverUndershootExitConditions(); SensorLossSelectionData getSensorLossConditions(); void clearSelectionData(); Rule createSimpleRuleFromSelection(); }### Answer: @Test public void shouldReplaceAllUmlautsWithAlternatives() { assertThat(controllerUnderTest.replaceAllUmlauts("ÜüÖöÄäß"), is("UeueOEoeAEaess")); }
### Question: EventSubscriptionController { String normalize(String toNormalize) { return replaceNonAlphaNumerics(replaceAllUmlauts(toNormalize)); } void setTimeseries(TimeseriesLegendData timeseries); TimeseriesLegendData getTimeSeries(); String getServiceUrl(); String getOffering(); String getPhenomenon(); String getProcedure(); String getFeatureOfInterest(); void setSelectedAbonnementName(String currentAbonnementName); String getSelectedAbonnementName(); boolean isSelectionValid(); void setSelectedSubscriptionTemplate(SubscriptionTemplate template); void updateSelectedRuleTemplate(SubscriptionTemplate template); String createSuggestedAbonnementName(); SimpleRuleType getSelectedRuleTemplate(); OverUndershootSelectionData getOverUndershootEntryConditions(); OverUndershootSelectionData getOverUndershootExitConditions(); SensorLossSelectionData getSensorLossConditions(); void clearSelectionData(); Rule createSimpleRuleFromSelection(); }### Answer: @Test public void shouldNormalizeUmlautsAndNonAlphaNumerics() { assertThat(controllerUnderTest.normalize("ÜüÖöÄäß#'+`´^°!§$%&/()=?-ABCNksdfjiu098723049234lkjdsf"), is("UeueOEoeAEaess__________________ABCNksdfjiu098723049234lkjdsf")); }
### Question: SensorNetworkParser { public Map<String, ComponentType> parseSensorDescriptions(InputStream stream) { Map<String, ComponentType> sensorDescriptions = new HashMap<String, ComponentType>(); ComponentDocument[] components = parseNetworkComponentsFromDescribeSensorResponse(stream); for (ComponentDocument componentDocument : components) { ComponentType networkComponent = componentDocument.getComponent(); if (networkComponent.getIdentificationArray().length > 0) { Identification identification = networkComponent.getIdentificationArray(0); String id = xmlHelper.getUniqueId(identification.getIdentifierList()); if (id != null) { sensorDescriptions.put(id, networkComponent); } } } return sensorDescriptions; } Map<String, ComponentType> parseSensorDescriptions(InputStream stream); }### Answer: @Test public void givenSensorNetwork_parsingNetwork_parsedCorrectNumberOfNetworkMembers() throws XmlException, IOException { XmlObject network = XmlFileLoader.loadXmlFileViaClassloader(SENSOR_NETWORK_SUBSET, getClass()); Map<String, ComponentType> descriptions = new SensorNetworkParser().parseSensorDescriptions(network.newInputStream()); assertThat(descriptions.size(), is(4)); }
### Question: ArcGISSoeEReportingMetadataHandler extends MetadataHandler { protected String parseCategory(String phenomenonLabel) { Pattern pattern = Pattern.compile("\\((.*)\\)$"); Matcher matcher = pattern.matcher(parseLastBraceGroup(phenomenonLabel)); return matcher.find() ? matcher.group(1) : phenomenonLabel; } ArcGISSoeEReportingMetadataHandler(SOSMetadata metadata); @Override void assembleTimeseriesMetadata(TimeseriesProperties properties); @Override SOSMetadata performMetadataCompletion(); boolean isCached(String procedure); @Override SOSMetadata updateMetadata(SOSMetadata metadata); }### Answer: @Test public void shouldParseCategoryFromPhenomenonLabelWithSingleBraceGroup() { String category = seam.parseCategory("Cadmium lajsdf (aerosol)"); assertThat(category, is("aerosol")); } @Test public void shouldParseCategoryFromPhenomenonLabelWithMultipleBraceGroup() { String category = seam.parseCategory("Benzo(a)anthracene in PM10 (air+aerosol)"); assertThat(category, is("air+aerosol")); } @Test public void shouldParseWholePhenomenonWhenNoBraceGroupAvailable() { String category = seam.parseCategory("aerosol"); assertThat(category, is("aerosol")); }
### Question: QueryParser { Map<String, String> parseKvps(String query) { Map<String, String> parsedKvps = new HashMap<String, String>(); if (query == null || query.isEmpty()) { return parsedKvps; } else { String[] splittedKvps = query.split("&"); for (String kvp : splittedKvps) { addKvp(kvp, parsedKvps); } return parsedKvps; } } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }### Answer: @Test public void testParseValidKvps() { String validQuery = "single=blah&multiple=value1,vlaue2"; Map<String, String> kvps = permalinkParser.parseKvps(validQuery); assertTrue("map does not contain value 'single'.", kvps.containsKey("SINGLE")); assertTrue("map does not contain value 'multiple'.", kvps.containsKey("MULTIPLE")); } @Test public void testParseInvalidKvps() { String invalidQuery = "single&multiple=value1,vlaue2"; Map<String, String> kvps = permalinkParser.parseKvps(invalidQuery); assertFalse("map does not contain value 'single'.", kvps.containsKey("SINGLE")); assertTrue("map does not contain value 'multiple'.", kvps.containsKey("MULTIPLE")); } @Test public void testParseEncodedKvps() { StringBuilder validQuery = new StringBuilder(); validQuery.append("single"); validQuery.append("="); validQuery.append("sadf"); validQuery.append("&"); validQuery.append("multiple"); validQuery.append("="); validQuery.append("value1"); validQuery.append("%2C"); validQuery.append("value2_part1+value2_part2"); validQuery.append("&"); validQuery.append("url"); validQuery.append("="); validQuery.append("http%3A QueryParser permalinkParser = new QueryParser(null, false); Map<String, String> kvps = permalinkParser.parseKvps(validQuery.toString()); assertTrue("map does not contain value 'single'.", kvps.containsKey("SINGLE")); assertTrue("map does not contain value 'multiple'.", kvps.containsKey("MULTIPLE")); assertTrue("map does not contain value 'url'.", kvps.containsKey("URL")); }
### Question: FeatureParser { public Map<Feature, Point> parseFeatures(InputStream stream) { Map<Feature, Point> featureLocations = new HashMap<Feature, Point>(); try { GetFeatureOfInterestResponseDocument responseDoc = GetFeatureOfInterestResponseDocument.Factory.parse(stream); GetFeatureOfInterestResponseType response = responseDoc.getGetFeatureOfInterestResponse(); for (FeaturePropertyType member : response.getFeatureMemberArray()) { PointDocument pointDoc = xmlHelper.getPoint(member, crsUtil); Feature feature = parseFeatureFrom(member); Point location = getCrs84Location(pointDoc); featureLocations.put(feature, location); } } catch (XmlException e) { LOGGER.error("Could not parse GetFeatureOfInterestResponse.", e); } catch (IOException e) { LOGGER.error("Could not read GetFeatureOfInterestResponse.", e); } LOGGER.debug("Parsed #" + featureLocations.size() + " feature locations."); return featureLocations; } FeatureParser(String serviceUrl, CRSUtils crsHelper); Map<Feature, Point> parseFeatures(InputStream stream); }### Answer: @Test public void shouldParseLocations() throws XmlException, IOException { XmlObject featureResponse = loadXmlFileViaClassloader(GET_FOI_RESPONSE, getClass()); Map<Feature, Point> featureLocations = featureParser.parseFeatures(featureResponse.newInputStream()); if (featureLocations == null || featureLocations.isEmpty()) { fail("No features have been parsed!"); } else { assertThat(featureLocations.size(), is(3)); } }
### Question: ArcGISSoeDescribeSensorParser { public String getUomFor(String phenomenonId) { String xPath = "$this String query = String.format(xPath, phenomenonId); Quantity output = xmlHelper.parseFirst(sensorML, query, Quantity.class); return output == null ? null : output.getUom().getCode(); } ArcGISSoeDescribeSensorParser(XmlObject sml); String getUomFor(String phenomenonId); String getShortName(); SensorML getSensorML(); }### Answer: @Test public void shouldParseFirstAvailableUomFromInconsistentMultipleOutputSection() { assertThat("UOM code is not correct!", parser.getUomFor(PHENOMENON), is("mg.m-3")); }
### Question: ArcGISSoeDescribeSensorParser { public String getShortName() { String query = "$this Identifier identifier = xmlHelper.parseFirst(sensorML, query, Identifier.class); return identifier == null ? null : identifier.getTerm().getValue(); } ArcGISSoeDescribeSensorParser(XmlObject sml); String getUomFor(String phenomenonId); String getShortName(); SensorML getSensorML(); }### Answer: @Test public void shouldParseShortName() { assertThat("shortName is incorrect!", parser.getShortName(), is("GB_StationProcess_3746")); }
### Question: HydroMetadataHandler extends MetadataHandler { protected Collection<SosTimeseries> getAvailableTimeseries(XmlObject result_xb, SosTimeseries timeserie, SOSMetadata metadata) throws XmlException, IOException { ArrayList<SosTimeseries> timeseries = new ArrayList<SosTimeseries>(); StringBuilder sb = new StringBuilder(); sb.append("declare namespace gda='"); sb.append(SoapSOSRequestBuilder_200.SOS_GDA_10_NS); sb.append("'; $this/gda:GetDataAvailabilityResponse/gda:dataAvailabilityMember"); XmlObject[] response = result_xb.selectPath(sb.toString()); if (response == null || response.length ==0) { sb = new StringBuilder(); sb.append("declare namespace gda='"); sb.append(SoapSOSRequestBuilder_200.SOS_GDA_10_PREFINAL_NS); sb.append("'; $this/gda:GetDataAvailabilityResponse/gda:dataAvailabilityMember"); response = result_xb.selectPath(sb.toString()); } for (XmlObject xmlObject : response) { SosTimeseries addedtimeserie = new SosTimeseries(); String feature = getAttributeOfChildren(xmlObject, "featureOfInterest", "href").trim(); String phenomenon = getAttributeOfChildren(xmlObject, "observedProperty", "href").trim(); String procedure = getAttributeOfChildren(xmlObject, "procedure", "href").trim(); addedtimeserie.setFeature(new Feature(feature, metadata.getServiceUrl())); addedtimeserie.setPhenomenon(new Phenomenon(phenomenon, metadata.getServiceUrl())); addedtimeserie.setProcedure(new Procedure(procedure, metadata.getServiceUrl())); String category = getLastPartOf(phenomenon) + " (" + getLastPartOf(procedure) + ")"; addedtimeserie.setCategory(new Category(category, metadata.getServiceUrl())); addedtimeserie.setOffering(new Offering(timeserie.getOfferingId(), metadata.getServiceUrl())); addedtimeserie.setSosService(new SosService(timeserie.getServiceUrl(), metadata.getVersion())); addedtimeserie.getSosService().setLabel(metadata.getTitle()); timeseries.add(addedtimeserie); } return timeseries; } HydroMetadataHandler(SOSMetadata metadata); @Override void assembleTimeseriesMetadata(TimeseriesProperties properties); @Override SOSMetadata performMetadataCompletion(); @Override SOSMetadata updateMetadata(SOSMetadata metadata); }### Answer: @Test public void shouldParseGetDataAvailabilityResponse() throws Exception { Collection<SosTimeseries> timeseries = seam.getAvailableTimeseries(); assertThat(timeseries.size(), is(140)); }
### Question: SoapSOSRequestBuilder_200 extends SOSRequestBuilder_200_OXFExtension { @Override public String buildGetObservationRequest(ParameterContainer parameters) throws OXFException { parameters.removeParameterShell(parameters.getParameterShellWithCommonName(GET_OBSERVATION_RESPONSE_FORMAT_PARAMETER)); parameters.addParameterShell(GET_OBSERVATION_RESPONSE_FORMAT_PARAMETER, WATERML_20_NS); String request = super.buildGetObservationRequest(parameters); EnvelopeDocument envelope = addSoapEnvelope(request, GET_OBS_SOAP_HEADER_ACTION); return envelope.xmlText(XmlUtil.PRETTYPRINT); } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetFeatureOfInterestRequest(ParameterContainer parameters); @Override String buildDescribeSensorRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); String buildGetDataAvailabilityRequest(ParameterContainer parameters); void setUrl(String sosUrl); }### Answer: @Test public void shouldReplaceDefaultOM20ResponseFormatWithWaterML20() throws XmlException, IOException, OXFException { String request = builder.buildGetObservationRequest(parameters); EnvelopeDocument envelope = EnvelopeDocument.Factory.parse(request); GetObservationDocument goDoc = (GetObservationDocument) readBodyNodeFrom(envelope, null); String actual = goDoc.getGetObservation().getResponseFormat(); Assert.assertThat(actual, is("http: }
### Question: TimeseriesParameter implements Serializable { public String getLabel() { return label; } TimeseriesParameter(); TimeseriesParameter(String parameterId, String[] parametersToGenerateId); @JsonIgnore String getGlobalId(); void setLabel(String label); String getLabel(); }### Answer: @Test public void shouldParseLastUrnFragmentAsLabel() { TestParameter testParameter = new TestParameter("urn:123::999:id2134"); assertThat(testParameter.getLabel(), is("id2134")); } @Test public void shouldParseLastHttpPathAsLabel() { TestParameter testParameter = new TestParameter("http: assertThat(testParameter.getLabel(), is("D_GB_Sample.xml")); } @Test public void shouldParseHttpFragmentAsLabel() { TestParameter testParameter = new TestParameter("http: assertThat(testParameter.getLabel(), is("GB_SamplingFeature_281")); }
### Question: TimeseriesParameter implements Serializable { @JsonIgnore public String getGlobalId() { return globalId; } TimeseriesParameter(); TimeseriesParameter(String parameterId, String[] parametersToGenerateId); @JsonIgnore String getGlobalId(); void setLabel(String label); String getLabel(); }### Answer: @Test public void shouldHaveTestSuffixWithinGlobalId() { TestParameter testParameter = new TestParameter("someParameterId"); assertThat(testParameter.getGlobalId(), startsWith("test_")); }
### Question: ResultPage implements Serializable { public boolean isLastPage() { return offset + results.length >= total; } @SuppressWarnings("unused") private ResultPage(); ResultPage(T[] results, int offset, int total); int getOffset(); int getTotal(); T[] getResults(); boolean isLastPage(); }### Answer: @Test public void shouldIndicateThatMorePagesAreAvailable() { ResultPage<String> firstPage = getFirstPage(); assertThat(firstPage.isLastPage(), is(false)); } @Test public void shouldIndicateLastPageWithOverlappingSize() { ResultPage<String> lastPage = getLastPageOverlapping(); assertThat(lastPage.isLastPage(), is(true)); } @Test public void shouldIndicateLastPageWhenMatchingSize() { ResultPage<String> lastPage = getLastPageWithMatchingSize(); assertThat(lastPage.isLastPage(), is(true)); }
### Question: QueryParser { String decodeValue(String value) { value = value.replace("%21", "!"); value = value.replace("%23", "#"); value = value.replace("%24", "$"); value = value.replace("%26", "&"); value = value.replace("%27", "'"); value = value.replace("%28", "("); value = value.replace("%29", ")"); value = value.replace("%2C", ","); value = value.replace("%2F", "/"); value = value.replace("%3A", ":"); value = value.replace("%3B", ";"); value = value.replace("%3D", "="); value = value.replace("%3F", "?"); value = value.replace("%40", "@"); value = value.replace("%5B", "["); value = value.replace("%5D", "]"); value = value.replace("+", " "); value = value.replace("%2B", "+"); value = value.replace("%25", "%"); return value; } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }### Answer: @Test public void testDecodeQuery() { assertEquals("Unexpected decoded URL.", DECODED_SOS_URL, permalinkParser.decodeValue(ENCODED_SOS_URL)); String decodedCharacters = "! # $ % & ' ( ) * + , / : ; = ? @ [ ]"; String encodedCharacters = "%21+%23+%24+%25+%26+%27+%28+%29+*+%2B+%2C+/+%3A+%3B+%3D+%3F+@+%5B+%5D"; assertEquals("Unexpected decoding.", decodedCharacters, permalinkParser.decodeValue(encodedCharacters)); }
### Question: QueryParser { public Collection<String> parseServices() { String serviceValues = kvps.get(SERVICES.name()); return parseCommaSeparatedValues(serviceValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }### Answer: @Test public void testParseServiceKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("services=").append(ENCODED_SOS_URL); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedServices = parser.parseServices(); assertTrue("Invalid size: " + parsedServices.size(), parsedServices.size() == 1); assertTrue("URL could not be parsed.", parsedServices.contains(DECODED_SOS_URL)); }
### Question: QueryParser { public Collection<String> parseVersions() { String versionValues = kvps.get(VERSIONS.name()); return parseCommaSeparatedValues(versionValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }### Answer: @Test public void testParseVersionKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("versions=").append("2.0.0"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedVersions = parser.parseVersions(); assertTrue("Invalid size: " + parsedVersions.size(), parsedVersions.size() == 1); assertTrue("Versions could not be parsed.", parsedVersions.contains("2.0.0")); }
### Question: QueryParser { public Collection<String> parseOfferings() { String offeringValues = kvps.get(OFFERINGS.name()); return parseCommaSeparatedValues(offeringValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }### Answer: @Test public void testParseOfferingKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("offerings=").append("WASSERSTAND_ROHDATEN"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedOfferings = parser.parseOfferings(); assertTrue("Invalid size: " + parsedOfferings.size(), parsedOfferings.size() == 1); assertTrue("Offerings could not be parsed.", parsedOfferings.contains("WASSERSTAND_ROHDATEN")); }
### Question: CheckList { public static List<Class> getChecks() { return ImmutableList.<Class> of( ParsingErrorCheck.class, XPathCheck.class ); } private CheckList(); static List<Class> getChecks(); static final String REPOSITORY_KEY; static final String REPOSITORY_NAME; static final String SONAR_WAY_PROFILE; }### Answer: @Test public void count() { int count = 0; List<File> files = (List<File>) FileUtils.listFiles(new File("src/main/java/org/sonar/_1C/checks/"), new String[] {"java"}, false); for (File file : files) { if (file.getName().endsWith("Check.java")) { count++; } } assertThat(CheckList.getChecks().size()).isEqualTo(count); } @Test public void test() { List<Class> checks = CheckList.getChecks(); if(checks.size()==0) return; for (Class cls : checks) { String testName = '/' + cls.getName().replace('.', '/') + "Test.class"; assertThat(getClass().getResource(testName)) .overridingErrorMessage("No test for " + cls.getSimpleName()) .isNotNull(); } ResourceBundle resourceBundle = ResourceBundle.getBundle("org.sonar.l10n.1C", Locale.ENGLISH); List<String> keys = Lists.newArrayList(); List<Rule> rules = new AnnotationRuleParser().parse("repositoryKey", checks); for (Rule rule : rules) { keys.add(rule.getKey()); resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".name"); assertThat(getClass().getResource("/org/sonar/l10n/1C/rules/1C/" + rule.getKey() + ".html")) .overridingErrorMessage("No description for " + rule.getKey()) .isNotNull(); assertThat(rule.getDescription()) .overridingErrorMessage("Description of " + rule.getKey() + " should be in separate file") .isNull(); for (RuleParam param : rule.getParams()) { resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".param." + param.getKey()); assertThat(param.getDescription()) .overridingErrorMessage("Description for param " + param.getKey() + " of " + rule.getKey() + " should be in separate file") .isEmpty(); } } assertThat(keys).doesNotHaveDuplicates(); }
### Question: _1CTokenizer implements Tokenizer { public final void tokenize(SourceCode source, Tokens cpdTokens) { Lexer lexer = _1CLexer.create(new _1CConfiguration(charset)); String fileName = source.getFileName(); List<Token> tokens = lexer.lex(new File(fileName)); for (Token token : tokens) { TokenEntry cpdToken = new TokenEntry(getTokenImage(token), fileName, token.getLine()); cpdTokens.add(cpdToken); } cpdTokens.add(TokenEntry.getEOF()); } _1CTokenizer(Charset charset); final void tokenize(SourceCode source, Tokens cpdTokens); }### Answer: @Test public void test() { _1CTokenizer tokenizer = new _1CTokenizer(Charset.forName("UTF-8")); SourceCode source = mock(SourceCode.class); when(source.getFileName()).thenReturn(new File("src/test/resources/cpd/Person.bsl").getAbsolutePath()); Tokens tokens = new Tokens(); tokenizer.tokenize(source, tokens); assertThat(tokens.getTokens().size()).isGreaterThan(1); assertThat(tokens.getTokens().get(tokens.size() - 1)).isEqualTo(TokenEntry.getEOF()); }