method2testcases
stringlengths 118
6.63k
|
---|
### Question:
PeriodicWatch extends ThresholdWatch implements PeriodicWatchMBean { public long getPeriod() { return (period); } PeriodicWatch(String id); PeriodicWatch(String id, Configuration config); PeriodicWatch(WatchDataSource watchDataSource, String id); void start(); void stop(); long getPeriod(); void setPeriod(long newPeriod); static final long DEFAULT_PERIOD; }### Answer:
@Test public void testGetPeriod() { MyPeriodicWatch watch = new MyPeriodicWatch("watch"); Assert.assertEquals(PeriodicWatch.DEFAULT_PERIOD, watch.getPeriod()); for (int i = 0; i < 10; i++) { long value = Math.round(Math.random() * 100) + 1; watch.setPeriod(value); Assert.assertEquals(value, watch.getPeriod()); } Utils.close(watch.getWatchDataSource()); } |
### Question:
PeriodicWatch extends ThresholdWatch implements PeriodicWatchMBean { public void setPeriod(long newPeriod) { if(newPeriod == period) return; if(newPeriod <= 0) throw new IllegalArgumentException("period cannot be less then or equal to zero"); this.period = newPeriod; if(watchTimer!=null) { stop(); start(); } } PeriodicWatch(String id); PeriodicWatch(String id, Configuration config); PeriodicWatch(WatchDataSource watchDataSource, String id); void start(); void stop(); long getPeriod(); void setPeriod(long newPeriod); static final long DEFAULT_PERIOD; }### Answer:
@Test public void testSetPeriod() { MyPeriodicWatch watch = new MyPeriodicWatch("watch"); watch.start(); Assert.assertEquals(PeriodicWatch.DEFAULT_PERIOD, watch.getPeriod()); for (int i = 0; i < 10; i++) { long value = Math.round(Math.random() * 100) + 1; watch.setPeriod(value); Assert.assertEquals(value, watch.getPeriod()); } try { watch.setPeriod(0); Assert.fail("IllegalArgumentException expected but not thrown"); } catch (IllegalArgumentException e) { } try { watch.setPeriod(-1); Assert.fail("IllegalArgumentException expected but not thrown"); } catch (IllegalArgumentException e) { } watch.setPeriod(500); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); watch.setPeriod(1000); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() >= 3); Assert.assertTrue(watch.log().length() <= 7); watch.log().delete(0, watch.log().length()); watch.setPeriod(1000); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() == 0); watch.log().delete(0, watch.log().length()); watch.setPeriod(500); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); Utils.close(watch.getWatchDataSource()); } |
### Question:
PeriodicWatch extends ThresholdWatch implements PeriodicWatchMBean { public void start() { long now = System.currentTimeMillis(); stop(); watchTimer = new Timer(true); watchTimer.schedule(new PeriodicTask(), new Date(now+period), period); } PeriodicWatch(String id); PeriodicWatch(String id, Configuration config); PeriodicWatch(WatchDataSource watchDataSource, String id); void start(); void stop(); long getPeriod(); void setPeriod(long newPeriod); static final long DEFAULT_PERIOD; }### Answer:
@Test public void testStart() { MyPeriodicWatch watch = new MyPeriodicWatch("watch"); watch.setPeriod(500); watch.stop(); watch.start(); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); watch.start(); watch.stop(); Utils.sleep(5000); Assert.assertTrue(watch.log().length() == 0); watch.start(); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); for (int i = 0; i < 1000; i++) { watch.start(); } for (int i = 0; i < 50; i++) { watch.start(); Utils.sleep(100); } Assert.assertTrue(watch.log().length() == 0); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); Utils.close(watch.getWatchDataSource()); } |
### Question:
PeriodicWatch extends ThresholdWatch implements PeriodicWatchMBean { public void stop() { if(watchTimer != null) watchTimer.cancel(); } PeriodicWatch(String id); PeriodicWatch(String id, Configuration config); PeriodicWatch(WatchDataSource watchDataSource, String id); void start(); void stop(); long getPeriod(); void setPeriod(long newPeriod); static final long DEFAULT_PERIOD; }### Answer:
@Test public void testStop() { MyPeriodicWatch watch = new MyPeriodicWatch("watch"); watch.start(); watch.setPeriod(500); Utils.sleep(5000); watch.stop(); Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); Utils.sleep(2000); Assert.assertTrue(watch.log().length() == 0); watch.stop(); Utils.sleep(2000); Assert.assertTrue(watch.log().length() == 0); watch.start(); Utils.sleep(5000); for (int i = 0; i < 100; i++) { watch.stop(); } Assert.assertTrue(watch.log().length() >= 8); Assert.assertTrue(watch.log().length() <= 12); watch.log().delete(0, watch.log().length()); for (int i = 0; i < 1000; i++) { watch.stop(); } Utils.close(watch.getWatchDataSource()); } |
### Question:
Statistics { public void setValues(Iterable<Double> vals) { if(vals==null) throw new IllegalArgumentException("vector is null"); v.clear(); for(Double d : vals) v.add(d); } Statistics(); Statistics(Iterable<Double> values); void clearAll(); int count(); double max(); double min(); double mean(); double median(); double mode(); int modeOccurrenceCount(); double range(); double standardDeviation(); Vector getValues(); void addValue(Double double1); void addValue(double d); void setValues(Iterable<Double> vals); void setValues(Calculable[] calcs); void removeValues(double d, boolean removeAll); void removeValues(Double double1, boolean removeAll); void removeValue(int location); void removeValues(Double low, Double high); void removeValues(double low, double high); double sum(); }### Answer:
@Test public void testSetValues() { Statistics stat = new Statistics(); for (int i = 0; i < 10; i++) { Vector<Double> v = new Vector<>(); int count = (int) (Math.random() * 100); for (int j = 0; j < count; j++) { v.add(Math.random()); stat.setValues(v); Assert.assertEquals(v, stat.getValues()); Assert.assertNotSame(v, stat.getValues()); } } List<Double> v = new ArrayList<>(); stat.setValues(v); Assert.assertEquals(0, stat.count()); v.add((double) 0); Assert.assertEquals(0, stat.count()); try { stat.setValues((List<Double>)null); Assert.fail("IllegalArgumentException expected but not thrown"); } catch (IllegalArgumentException e) { } } |
### Question:
GaugeWatch extends ThresholdWatch { public void addValue(long value) { addWatchRecord(new Calculable(id, (double)value, System.currentTimeMillis())); } GaugeWatch(String id); GaugeWatch(String id, Configuration config); GaugeWatch(WatchDataSource watchDataSource, String id); void addValue(long value); void addValue(double value); @SuppressWarnings("unused") void addValue(double value, String detail); }### Answer:
@Test public void testAddValue1() throws RemoteException { String id = "watch"; GaugeWatch watch = new GaugeWatch(id); DataSourceMonitor mon = new DataSourceMonitor(watch); final int checkpoints[] = new int[] {0, 1, 50, 1000, 1001, 2000, 10000}; final int collectionSize = 1000; List<Double> added = new ArrayList<Double>(); for (int checkpoint : checkpoints) { if(watch.getWatchDataSource().getMaxSize()<checkpoint) { watch.getWatchDataSource().setMaxSize(1000); } while (added.size() < checkpoint) { double d = Math.random(); added.add(d); watch.addValue(d); } mon.waitFor(Math.min(collectionSize, checkpoint)); Calculable[] calcs = watch.getWatchDataSource().getCalculable(); int offset = Math.max(added.size() - collectionSize, 0); List<Double> expected = added.subList(offset, added.size()); List<Double> actual = new ArrayList<Double>(); for (Calculable calc : calcs) { Assert.assertEquals(id, calc.getId()); actual.add(calc.getValue()); } Assert.assertEquals(expected, actual); } Utils.close(watch.getWatchDataSource()); }
@Test public void testAddValue2() throws RemoteException { String id = "watch"; GaugeWatch watch = new GaugeWatch(id); DataSourceMonitor mon = new DataSourceMonitor(watch); final int checkpoints[] = new int[] {0, 1, 50, 1000, 1001, 2000, 10000}; final int collectionSize = 1000; List<Long> added = new ArrayList<Long>(); for (int checkpoint : checkpoints) { if(watch.getWatchDataSource().getMaxSize()<checkpoint) { watch.getWatchDataSource().setMaxSize(1000); } while (added.size() < checkpoint) { long l = (long) (Math.random() * 1000); added.add(l); watch.addValue(l); } mon.waitFor(Math.min(collectionSize, checkpoint)); Calculable[] calcs = watch.getWatchDataSource().getCalculable(); int offset = Math.max(added.size() - collectionSize, 0); List<Long> expected = added.subList(offset, added.size()); List<Long> actual = new ArrayList<Long>(); for (Calculable calc : calcs) { Assert.assertEquals(id, calc.getId()); actual.add((long) calc.getValue()); } Assert.assertEquals(expected, actual); } Utils.close(watch.getWatchDataSource()); } |
### Question:
WatchDataSourceRegistry implements WatchRegistry { public void closeAll() { Watch[] watches = watchRegistry.toArray(new Watch[0]); for(Watch w : watches) { if(w instanceof PeriodicWatch) ((PeriodicWatch)w).stop(); try { WatchDataSource wd = w.getWatchDataSource(); if (wd != null) wd.close(); watchRegistry.remove(w); } catch (Exception e) { logger.warn("Closing WatchDataSource", e); } } } void deregister(Watch... watches); void closeAll(); void register(Watch... watches); void addThresholdListener(String id, ThresholdListener thresholdListener); void removeThresholdListener(String id, ThresholdListener thresholdListener); Watch findWatch(String id); WatchDataSource[] fetch(); WatchDataSource fetch(String id); void setServiceBeanContext(ServiceBeanContext context); }### Answer:
@Test public void testCloseAll() { WatchDataSourceRegistry registry = new WatchDataSourceRegistry(); int[] counts = new int[] {0, 1, 10, 100}; for (int count : counts) { Collection<Watch> watches = new ArrayList<Watch>(); for (int j = 0; j < count; j++) { String id = "watch" + j; LoggingWatchDataSource ds = new LoggingWatchDataSource( id, EmptyConfiguration.INSTANCE); Watch watch = new GaugeWatch(ds, id); watches.add(watch); } for (Watch watch : watches) { registry.register(watch); } registry.closeAll(); for (Watch watch : watches) { LoggingWatchDataSource ds = (LoggingWatchDataSource) watch.getWatchDataSource(); checkLog(ds.log(), "close()"); } for (Watch watch : watches) { registry.deregister(watch); LoggingWatchDataSource ds = (LoggingWatchDataSource) watch.getWatchDataSource(); checkLog(ds.log(), "close()"); } registry.closeAll(); for (Watch watch : watches) { LoggingWatchDataSource ds = (LoggingWatchDataSource) watch.getWatchDataSource(); checkLog(ds.log(), ""); } } } |
### Question:
WatchDataSourceRegistry implements WatchRegistry { public Watch findWatch(String id) { if(id == null) throw new IllegalArgumentException("id is null"); Watch watch = null; for(Watch w : watchRegistry) { if(id.equals(w.getId())) { watch = w; break; } } return watch; } void deregister(Watch... watches); void closeAll(); void register(Watch... watches); void addThresholdListener(String id, ThresholdListener thresholdListener); void removeThresholdListener(String id, ThresholdListener thresholdListener); Watch findWatch(String id); WatchDataSource[] fetch(); WatchDataSource fetch(String id); void setServiceBeanContext(ServiceBeanContext context); }### Answer:
@Test public void testFindWatch() { WatchDataSourceRegistry registry = new WatchDataSourceRegistry(); int[] counts = new int[] {0, 1, 10, 100}; for (int count : counts) { Collection<Watch> watches = new ArrayList<Watch>(); for (int k = 0; k < count; k++) { String id = "watch" + k; if (k == 1) { id = ""; } WatchDataSource ds = new WatchDataSourceImpl( id, EmptyConfiguration.INSTANCE); watches.add(new GaugeWatch(ds, id)); } for (int j = 0; j < 5; j++) { for (Watch watch : watches) { String id = watch.getId(); Watch res = registry.findWatch(id); Assert.assertNull(res); } for (Watch watch : watches) { registry.register(watch); } for (Watch watch : watches) { String id = watch.getId(); Watch res = registry.findWatch(id); Assert.assertNotNull(res); Assert.assertSame(watch, res); } Assert.assertNull(registry.findWatch("aaa")); for (Watch watch : watches) { registry.deregister(watch); } for (Watch watch : watches) { String id = watch.getId(); Watch res = registry.findWatch(id); Assert.assertNull(res); } } } try { registry.findWatch(null); Assert.fail("IllegalArgumentException expected but not thrown"); } catch (IllegalArgumentException e) { } } |
### Question:
WatchDataSourceRegistry implements WatchRegistry { public void addThresholdListener(String id, ThresholdListener thresholdListener) { if(id==null) throw new IllegalArgumentException("id is null"); if(thresholdListener==null) throw new IllegalArgumentException("thresholdListener is null"); Collection<ThresholdListener> collection; if(thresholdListenerTable.containsKey(id)) { collection = thresholdListenerTable.get(id); } else { collection = new ArrayList<>(); } if(!collection.contains(thresholdListener)) { if(logger.isTraceEnabled()) logger.trace("Add [{}] for watch [{}]", thresholdListener.getClass().getName(), id); collection.add(thresholdListener); thresholdListenerTable.put(id, collection); Watch watch = findWatch(id); if(logger.isTraceEnabled()) logger.trace("Found [{}] previously registered watch [{}]", (watch==null?0:1), id); if(watch!=null) { associateThresholdListener(watch); } } } void deregister(Watch... watches); void closeAll(); void register(Watch... watches); void addThresholdListener(String id, ThresholdListener thresholdListener); void removeThresholdListener(String id, ThresholdListener thresholdListener); Watch findWatch(String id); WatchDataSource[] fetch(); WatchDataSource fetch(String id); void setServiceBeanContext(ServiceBeanContext context); }### Answer:
@Test public void testAddThresholdListener() { WatchDataSourceRegistry registry = new WatchDataSourceRegistry(); int[] watchCounts = new int[] {1, 5, 10}; int[] listenerCounts = new int[] {1, 5, 10}; for (int ordering = 0; ordering < 3; ordering++) { for (int watchCount : watchCounts) { for (int listenerCount : listenerCounts) { Map<Watch, WatchEntry> map = new HashMap<Watch, WatchEntry>(); check(map, ordering); setup(map, watchCount, listenerCount); populate(registry, map, ordering); check(map, ordering); clear(registry, map); check(new HashMap<Watch, WatchEntry>(), ordering); populate(registry, map, ordering); check(map, ordering); clear(registry, map); check(new HashMap<Watch, WatchEntry>(), ordering); } } } try { registry.addThresholdListener(null, new LoggingThresholdListener()); Assert.fail("IllegalArgumentException expected but not thrown"); } catch (IllegalArgumentException e) { } try { registry.addThresholdListener("aaa", null); Assert.fail("IllegalArgumentException expected but not thrown"); } catch (IllegalArgumentException e) { } } |
### Question:
ConfigHelper { public static String[] getConfigArgs(final ServiceElement service) throws IOException { return getConfigArgs(service, Thread.currentThread().getContextClassLoader()); } static String[] getConfigArgs(final ServiceElement service); static String[] getConfigArgs(final ServiceElement service, final ClassLoader cl); static final String CLASSPATH_RESOURCE; static final String FILE_RESOURCE; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetConfigArgsNoCLassLoader() throws IOException { ConfigHelper.getConfigArgs(new ServiceElement(), null); }
@Test public void testUsingConfig() throws IOException { ServiceElement service = new ServiceElement(); service.getServiceBeanConfig().setConfigArgs(getConfig()); String[] args = ConfigHelper.getConfigArgs(service); Assert.assertNotNull(args); Assert.assertEquals(1, args.length); File file = new File(args[0]); Assert.assertTrue(file.exists()); Configuration configuration = new GroovyConfig(args, Thread.currentThread().getContextClassLoader()); Assert.assertNotNull(configuration); }
@Test public void testUsingGroovyConfig() throws IOException { ServiceElement service = new ServiceElement(); service.getServiceBeanConfig().setConfigArgs(getGroovyConfig()); String[] args = ConfigHelper.getConfigArgs(service); Assert.assertNotNull(args); Assert.assertEquals(1, args.length); File file = new File(args[0]); Assert.assertFalse(file.exists()); Configuration configuration = new GroovyConfig(args, Thread.currentThread().getContextClassLoader()); Assert.assertNotNull(configuration); }
@Test(expected = FileNotFoundException.class) public void testUsingMissingGroovyFile() throws IOException { ServiceElement service = new ServiceElement(); service.getServiceBeanConfig().setConfigArgs("file:foo"); String[] args = ConfigHelper.getConfigArgs(service); Assert.assertNotNull(args); Configuration configuration = new GroovyConfig(args, Thread.currentThread().getContextClassLoader()); Assert.assertNotNull(configuration); } |
### Question:
ClassBundleLoader { public static Class<?> loadClass(ClassBundle bundle) throws ClassNotFoundException, MalformedURLException { Class<?> theClass; final Thread currentThread = Thread.currentThread(); final ClassLoader cCL = AccessController.doPrivileged( (PrivilegedAction<ClassLoader>) currentThread::getContextClassLoader); try { theClass = loadClass(cCL, bundle); } finally { AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> { currentThread.setContextClassLoader(cCL); return (null); }); } return theClass; } static Class<?> loadClass(ClassBundle bundle); static Class<?> loadClass(final ClassLoader parent, ClassBundle bundle); }### Answer:
@Test public void testLoadClass() throws Exception { ClassBundle classBundle = new ClassBundle(JustForTesting.class.getName()); classBundle.setCodebase(System.getProperty("user.dir")+File.separator+ "target"+File.separator+ "test-classes"+File.separator); Class testClass = ClassBundleLoader.loadClass(classBundle); Assert.assertNotNull(testClass); } |
### Question:
Statistics { public void removeValue(int location) { if(location < v.size() && location >= 0) v.removeElementAt(location); } Statistics(); Statistics(Iterable<Double> values); void clearAll(); int count(); double max(); double min(); double mean(); double median(); double mode(); int modeOccurrenceCount(); double range(); double standardDeviation(); Vector getValues(); void addValue(Double double1); void addValue(double d); void setValues(Iterable<Double> vals); void setValues(Calculable[] calcs); void removeValues(double d, boolean removeAll); void removeValues(Double double1, boolean removeAll); void removeValue(int location); void removeValues(Double low, Double high); void removeValues(double low, double high); double sum(); }### Answer:
@Test public void testRemoveValue() { List<Double> v = asList(new double[]{ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); Statistics stat = new Statistics(v); while (stat.count() > 0) { int i = (int) (Math.random() * stat.count()); stat.removeValue(i); v.remove(i); Assert.assertEquals(v, stat.getValues()); } assertClean(stat); v = asList(new double[]{1, 2, 3, 4, 5}); stat.setValues(v); stat.removeValue(-1); stat.removeValue(5); Assert.assertEquals(v, stat.getValues()); } |
### Question:
AssociationInjector implements AssociationListener<T> { public void discovered(Association<T> association, T service) { inject(association, service); } AssociationInjector(Object target); void setBackend(Object target); void setCallerClassLoader(ClassLoader callerCL); void terminate(); Map<AssociationDescriptor, Long> getInvocationMap(); void injectEmpty(Association<T> association); void discovered(Association<T> association, T service); void changed(Association<T> association, T service); void broken(Association<T> association, T service); }### Answer:
@Test public void testInjectProxy() { Association<Dummy> a = new DefaultAssociation<Dummy>(createAssociationDescriptor()); Target1 t = new Target1(); AssociationInjector<Dummy> ai = new AssociationInjector<Dummy>(t); for(int i=0; i<10; i++) { Dummy dummy = new DummyImpl(i); a.addServiceItem(AssociationUtils.makeServiceItem(dummy)); ai.discovered(a, dummy); } Assert.assertEquals(1, t.injectedCount); }
@Test public void testInjectProxyWithListener() { Association<Dummy> a = new DefaultAssociation<Dummy>(createAssociationDescriptor()); Target1 t = new Target1(); AssociationInjector<Dummy> ai = new AssociationInjector<Dummy>(t); AL aL = new AL(); a.registerAssociationServiceListener(aL); for(int i=0; i<10; i++) { Dummy dummy = new DummyImpl(i); a.addServiceItem(AssociationUtils.makeServiceItem(dummy)); ai.discovered(a, dummy); } Assert.assertEquals(1, t.injectedCount); Assert.assertEquals(10, aL.addedServiceCount.get()); Assert.assertEquals(0, aL.removedServiceCount.get()); Collection<Dummy> dummies = a.getServices(); for(Dummy d: dummies) a.removeService(d); Assert.assertEquals(10, aL.removedServiceCount.get()); Assert.assertEquals(0, a.getServiceCount()); }
@Test public void testInjectIterable() { Association<Dummy> a = new DefaultAssociation<Dummy>(createAssociationDescriptor()); Target2 t = new Target2(); AssociationInjector<Dummy> ai = new AssociationInjector<Dummy>(t); for(int i=0; i<10; i++) { Dummy dummy = new DummyImpl(i); a.addServiceItem(AssociationUtils.makeServiceItem(dummy)); ai.discovered(a, dummy); } Assert.assertEquals(1, t.injectedCount); int j = 0; for(Dummy dummy : t.dummies) j++; Assert.assertEquals(10, j); }
@Test public void testInjectAssociation() { Association<Dummy> a = new DefaultAssociation<Dummy>(createAssociationDescriptor()); Target3 t = new Target3(); AssociationInjector<Dummy> ai = new AssociationInjector<Dummy>(t); for(int i=0; i<10; i++) { Dummy dummy = new DummyImpl(i); ServiceItem item = AssociationUtils.makeServiceItem(dummy); a.addServiceItem(item); ai.discovered(a, dummy); } Assert.assertEquals(1, t.injectedCount); } |
### Question:
AssociationInjector implements AssociationListener<T> { public void setBackend(Object target) { this.target = target; } AssociationInjector(Object target); void setBackend(Object target); void setCallerClassLoader(ClassLoader callerCL); void terminate(); Map<AssociationDescriptor, Long> getInvocationMap(); void injectEmpty(Association<T> association); void discovered(Association<T> association, T service); void changed(Association<T> association, T service); void broken(Association<T> association, T service); }### Answer:
@Test public void testEagerInjection() { DefaultAssociationManagement aMgr = new DefaultAssociationManagement(); Target5 target = new Target5(); aMgr.setBackend(target); AssociationDescriptor descriptor = createAssociationDescriptor(); descriptor.setLazyInject(false); Association<Dummy> a = aMgr.addAssociationDescriptor(descriptor); Assert.assertTrue(target.injectedCount==1); Assert.assertNotNull(target.dummy); Assert.assertEquals(Association.State.PENDING, target.dummy.getState()); } |
### Question:
AssociationProxyUtil { public static <T> Association<T> getAssociation(T proxy) { Association<T> association = null; if(proxy instanceof AssociationProxy) { association = ((AssociationProxy<T>)proxy).getAssociation(); } return association; } static T getService(T proxy); static T regenProxy(T proxy); static T getFirst(T proxy); static Association<T> getAssociation(T proxy); }### Answer:
@Test public void testGetAssociationFromProxy() { Association<Dummy> association = AssociationProxyUtil.getAssociation(t.getDummy()); Assert.assertNotNull(association); } |
### Question:
AssociationProxyUtil { public static <T> T regenProxy(T proxy) throws ClassNotFoundException, InstantiationException, IllegalAccessException { T newProxy = null; if(proxy instanceof AssociationProxy) { AssociationProxy<T> aProxy = (AssociationProxy)proxy; Association<T> association = aProxy.getAssociation(); String proxyClass = association.getAssociationDescriptor().getProxyClass(); proxyClass = (proxyClass==null? AssociationProxySupport.class.getName() : proxyClass); String strategyClass = aProxy.getServiceSelectionStrategy().getClass().getName(); newProxy = (T) AssociationProxyFactory.createProxy(proxyClass, strategyClass, association, aProxy.getClass().getClassLoader()); aProxy.terminate(); } return newProxy==null?proxy:newProxy; } static T getService(T proxy); static T regenProxy(T proxy); static T getFirst(T proxy); static Association<T> getAssociation(T proxy); }### Answer:
@Test public void testRegen() throws ClassNotFoundException, IllegalAccessException, InstantiationException { Dummy d = t.getDummy(); int index = d.getIndex(); Dummy d1 = AssociationProxyUtil.regenProxy(t.getDummy()); Assert.assertEquals(index, d1.getIndex()); } |
### Question:
ComputeResourceAccessor { public static ComputeResource getComputeResource() { if(computeResource==null) { try { computeResource = new ComputeResource(); computeResource.boot(); } catch (ConfigurationException | UnknownHostException e) { logger.error("Unable to create default ComputeResource", e); } } return computeResource; } static ComputeResource getComputeResource(); }### Answer:
@Test public void getComputeResource() throws Exception { ComputeResource computeResource = ComputeResourceAccessor.getComputeResource(); ComputeResourceUtilization cru = computeResource.getComputeResourceUtilization(); assertNotNull(cru); String systemCPUPercent = formatPercent(cru.getCpuUtilization().getValue()); assertNotNull(systemCPUPercent); String processCPUUtilization = formatPercent(getMeasuredValue(SystemWatchID.PROC_CPU, cru)); assertNotNull(processCPUUtilization); String systemMemoryTotal = format(cru.getSystemMemoryUtilization().getTotal(), "MB"); assertNotNull(systemMemoryTotal); String systemMemoryUtilPercent = formatPercent(cru.getSystemMemoryUtilization().getValue()); assertNotNull(systemMemoryUtilPercent); String processMemoryTotal = format(cru.getProcessMemoryUtilization().getUsedHeap()," MB"); assertNotNull(processMemoryTotal); String processMemoryUtilPercent = formatPercent(getMeasuredValue(SystemWatchID.JVM_MEMORY, cru)); assertNotNull(processMemoryUtilPercent); } |
### Question:
SystemCapabilities implements SystemCapabilitiesLoader { public MeasurableCapability[] getMeasurableCapabilities(Configuration config) { if(config==null) throw new IllegalArgumentException("config is null"); List<MeasurableCapability> measurables = new ArrayList<>(); MeasurableCapability memory = new Memory(config); if(memory.isEnabled()) measurables.add(memory); MeasurableCapability systemMemory = new SystemMemory(config); if(systemMemory.isEnabled()) measurables.add(systemMemory); try { MeasurableCapability[] pools = (MeasurableCapability[])config.getEntry(COMPONENT+".memory.pool", "memoryPools", MeasurableCapability[].class, null, config); if(pools!=null) measurables.addAll(Arrays.asList(pools)); } catch(ConfigurationException e) { logger.warn("Loading CPU MeasurableCapability", e); } MeasurableCapability cpu = new CPU(config); if(cpu.isEnabled()) measurables.add(cpu); MeasurableCapability jvmCpu = new CPU(config, SystemWatchID.PROC_CPU, true); if(jvmCpu.isEnabled()) measurables.add(jvmCpu); MeasurableCapability diskSpace = getDiskSpace(config); if(diskSpace.isEnabled()) measurables.add(diskSpace); try { MeasurableCapability[] mCaps = (MeasurableCapability[])config.getEntry(COMPONENT, "measurableCapabilities", MeasurableCapability[].class, null); if(mCaps!=null) { measurables.addAll(Arrays.asList(mCaps)); } } catch (ConfigurationException e) { logger.warn("Loading MeasurableCapability array", e); } return measurables.toArray(new MeasurableCapability[0]); } MeasurableCapability[] getMeasurableCapabilities(Configuration config); PlatformCapability[] getPlatformCapabilities(Configuration config); Map<String, String> getPlatformCapabilityNameTable(); String getPlatformConfigurationDirectory(Configuration config); static final String COMPONENT; static final String CAPABILITY; static final String NATIVE_LIBS; static final String PROCESSOR; static final String OPSYS; static final String TCPIP; static final String J2SE; static final String MEMORY; static final String SYSTEM_MEMORY; static final String STORAGE; static final String NATIVE_LIB_CLASS; static final String RIO; }### Answer:
@Test public void testGetMeasurableCapabilities() throws Exception { MeasurableCapability[] mCaps = systemCapabilities.getMeasurableCapabilities(new DynamicConfiguration()); int expected = 5; for(MeasurableCapability m : mCaps) System.out.println("===> "+m.getId()); Assert.assertEquals("Expected "+expected, expected, mCaps.length); org.rioproject.impl.system.measurable.memory.Memory memory = getCapability(org.rioproject.impl.system.measurable.memory.Memory.class, mCaps); Assert.assertNotNull(memory); log(memory); CPU cpu = getCapability(CPU.class, "CPU", mCaps); Assert.assertNotNull(cpu); log(cpu); CPU cpuProc = getCapability(CPU.class, "CPU (Proc)", mCaps); Assert.assertNotNull(cpuProc); log(cpuProc); DiskSpace diskSpace = getCapability(DiskSpace.class, mCaps); Assert.assertNotNull(diskSpace); log(diskSpace); } |
### Question:
Jetty implements WebsterService { public int getPort() { if (server == null) { return port; } return ((ServerConnector)server.getConnectors()[0]).getLocalPort(); } Jetty(); Jetty(File jettyConfig); Jetty(Configuration config); Jetty setRoots(String... roots); Jetty setPort(int port); Jetty setMinThreads(int minThreads); Jetty setMaxThreads(int maxThreads); Jetty setPutDir(String putDir); @Override void start(); @Override void startSecure(); @Override void terminate(); @Override URI getURI(); int getPort(); String getAddress(); void join(); static void main(String[] args); }### Answer:
@Test public void testStartWithConfig() throws Exception { DynamicConfiguration config = new DynamicConfiguration(); config.setEntry(Jetty.COMPONENT,"port", int.class,9020); config.setEntry(Jetty.COMPONENT,"roots", String[].class, new String[]{ System.getProperty("user.dir") + "/build/classes", System.getProperty("user.dir") + "/build/libs" }); Jetty jetty = new Jetty(config); assertEquals(9020, jetty.getPort()); }
@Test public void testStartWithGroovyConfig() throws Exception { String projectDir = System.getProperty("projectDir"); String resources = new File(projectDir+"/src/test/resources").getPath(); File config = new File(resources +"/jetty.groovy"); Jetty jetty = new Jetty(config); assertEquals(9029, jetty.getPort()); } |
### Question:
GenericCostModel implements ResourceCostModel { public GenericCostModel(double value) { this(value, null, DEFAULT_DESCRIPTION); } GenericCostModel(double value); GenericCostModel(double value, TimeBoundary[] timeBoundaries); GenericCostModel(double value,
TimeBoundary[] timeBoundaries,
String description); double getCostPerUnit(long duration); void addTimeBoundary(TimeBoundary timeBoundary); String getDescription(); }### Answer:
@Test public void testGenericCostModel() { GenericCostModel gcm = new GenericCostModel(0.01); gcm.addTimeBoundary(new ResourceCostModel.TimeBoundary(5, 10, ResourceCostModel.TimeBoundary.SECONDS)); gcm.addTimeBoundary(new ResourceCostModel.TimeBoundary(5, 100, ResourceCostModel.TimeBoundary.MINUTES)); System.out.println("Testing " + gcm.getClass().getName() + "\n"); System.out.println(gcm.getDescription()); Assert.assertTrue("Cost per unit for 2 seconds should be 0.01", gcm.getCostPerUnit(twoSeconds)==0.01); Assert.assertTrue("Cost per unit for 6 minutes should be 1.0", gcm.getCostPerUnit(sixMinutes) == 1.0); Assert.assertTrue("Cost per unit for 2 hours should be 1.0", gcm.getCostPerUnit(twoHours) == 1.0); } |
### Question:
BasicEventConsumer implements EventConsumer, ServerProxyTrust { public boolean register(final RemoteServiceEventListener listener) { return (register(listener, null)); } BasicEventConsumer(final EventDescriptor edTemplate); BasicEventConsumer(final RemoteServiceEventListener<?> listener); BasicEventConsumer(final EventDescriptor edTemplate, final RemoteServiceEventListener<?> listener); BasicEventConsumer(final EventDescriptor edTemplate,
final RemoteServiceEventListener<?> listener,
final Configuration config); BasicEventConsumer(final EventDescriptor edTemplate,
final RemoteServiceEventListener<?> listener,
final MarshalledObject<?> handback,
final Configuration config); void terminate(); boolean register(final RemoteServiceEventListener listener); boolean register(final RemoteServiceEventListener listener, final MarshalledObject handback); boolean deregister(final RemoteServiceEventListener listener); Watch createWatch(final WatchDataSourceRegistry watchRegistry); void destroyWatch(); Watch getWatch(); EventRegistration register(final ServiceItem item); EventRegistration register(final EventProducer eventProducer,
final EventDescriptor eventDesc,
final ServiceID serviceID); Object getEventRegistrationSource(final long eventID); void deregister(final ServiceID serviceID); void deregister(final ServiceID serviceID, final boolean disconnect); void notify(final RemoteEvent rEvent); TrustVerifier getProxyVerifier(); static final String RESPONSE_WATCH; }### Answer:
@Test public void testRegisteringAnEventProducerAndFiringAnEvent() throws Exception { BasicEventConsumer consumer = new BasicEventConsumer(getEventDescriptor()); Listener listener = new Listener(); consumer.register(listener); Producer p = new Producer(); p.createDEH(); ServiceItem serviceItem = createServiceItem(p); EventRegistration eventRegistration = consumer.register(serviceItem); Assert.assertNotNull(eventRegistration); p.fire(); listener.countDown.await(5, TimeUnit.SECONDS); Assert.assertTrue("Expected listener count to be > 0, found: " + listener.counter.get(), listener.counter.get() > 0); }
@Test public void testRegisteringAnEventProducerAndFiringAnEventWithLeaseBeingDropped() throws Exception { BasicEventConsumer consumer = new BasicEventConsumer(getEventDescriptor()); Listener listener = new Listener(); consumer.register(listener); Producer p = new Producer(); p.setLeaseTime(3 * 1000); p.createDEH(); ServiceItem serviceItem = createServiceItem(p); EventRegistration eventRegistration = consumer.register(serviceItem); Assert.assertNotNull(eventRegistration); System.err.println("Waiting 5 seconds for lease to timeout..."); int i = 1; while (i < 50) { Thread.sleep(100); i++; } p.fire(); assertEquals("Should have not been notified, but got: " + listener.counter.get(), 0, listener.counter.get()); }
@Test public void testRegisteringAnEventProducerAndFiringEventsUsingRoundRobin() throws Exception { Producer p = new Producer(); p.createRoundRobin(); ServiceItem serviceItem = createServiceItem(p); BasicEventConsumer consumer1 = new BasicEventConsumer(getEventDescriptor()); Listener listener1 = new Listener(2); consumer1.register(listener1); BasicEventConsumer consumer2 = new BasicEventConsumer(getEventDescriptor()); Listener listener2 = new Listener(2); consumer2.register(listener2); BasicEventConsumer consumer3 = new BasicEventConsumer(getEventDescriptor()); Listener listener3 = new Listener(2); consumer3.register(listener3); Assert.assertNotNull(consumer1.register(serviceItem)); Assert.assertNotNull(consumer2.register(serviceItem)); Assert.assertNotNull(consumer3.register(serviceItem)); for(int i=0; i<6; i++) p.fire(); assertTrue("Should have gotten 2, got " + listener1.counter.get(), listener1.countDown.await(5, TimeUnit.SECONDS)); assertTrue("Should have gotten 2, got " + listener2.counter.get(), listener2.countDown.await(5, TimeUnit.SECONDS)); assertTrue("Should have gotten 2, got " + listener3.counter.get(), listener3.countDown.await(5, TimeUnit.SECONDS)); } |
### Question:
EventDescriptorFactory { public static List<EventDescriptor> createEventDescriptors(String classpath, String... classNames) throws MalformedURLException, ResolverException, ClassNotFoundException, URISyntaxException { if(classNames==null) throw new IllegalArgumentException("classNames must not be null"); if(classNames.length==0) throw new IllegalArgumentException("classNames must not be empty"); final List<EventDescriptor> eventDescriptors = new ArrayList<EventDescriptor>(); if (classpath != null) { ClassAnnotator annotator = null; String[] classPath; if (Artifact.isArtifact(classpath)) { ArtifactURLConfiguration artifactURLConfiguration = new ArtifactURLConfiguration(classpath); StringBuilder artifactBuilder = new StringBuilder(); artifactBuilder.append("artifact:").append(artifactURLConfiguration.getArtifact()); annotator = new ClassAnnotator(new URL[]{new URL(artifactBuilder.toString())}); String[] cp = ResolverHelper.getResolver().getClassPathFor(classpath); classPath = new String[cp.length]; for (int i = 0; i < classPath.length; i++) { String s = cp[i].startsWith("file:") ? cp[i] : "file:" + cp[i]; classPath[i] = ResolverHelper.handleWindows(s); } } else { classPath = StringUtil.toArray(classpath, " ,"); } URL[] urls = new URL[classPath.length]; for (int i = 0; i < classPath.length; i++) { urls[i] = new URL(classPath[i]); } URLClassLoader loader; if(annotator!=null) { loader = new ServiceClassLoader(ServiceClassLoader.getURIs(urls), annotator, Thread.currentThread().getContextClassLoader()); } else { loader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader()); } for (String className : classNames) { Class<?> cl = loader.loadClass(className); eventDescriptors.add(new EventDescriptor(cl, getID(cl))); } } else { for (String className : classNames) { Class<?> cl = Thread.currentThread().getContextClassLoader().loadClass(className); eventDescriptors.add(new EventDescriptor(cl, getID(cl))); } } return eventDescriptors; } private EventDescriptorFactory(); static List<EventDescriptor> createEventDescriptors(String classpath,
String... classNames); }### Answer:
@Test public void testCreateEventDescriptors() throws Exception { List<EventDescriptor> list = EventDescriptorFactory.createEventDescriptors(null, "org.rioproject.sla.SLAThresholdEvent"); Assert.assertNotNull(list); Assert.assertEquals(1, list.size()); }
@Test public void testCreateEventDescriptorsMulti() throws Exception { List<EventDescriptor> list = EventDescriptorFactory.createEventDescriptors (null, "org.rioproject.sla.SLAThresholdEvent", "org.rioproject.watch.ThresholdEvent"); Assert.assertNotNull(list); Assert.assertEquals(2, list.size()); }
@Test(expected = IllegalArgumentException.class) public void testCreateEventDescriptorsNullClassNames() throws Exception { EventDescriptorFactory.createEventDescriptors (null); }
@Test(expected = MalformedURLException.class) public void testCreateEventDescriptorsBadClassPath() throws Exception { EventDescriptorFactory.createEventDescriptors ("foo", ""); } |
### Question:
Version { public boolean isRange() { return version.contains(","); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testIsRange() throws Exception { Version v = new Version("1,2"); Assert.assertTrue(v.isRange()); Version v1 = new Version("1.2"); Assert.assertFalse(v1.isRange()); } |
### Question:
Version { public String getVersion() { if (minorVersionSupport() || majorVersionSupport()) { return version.substring(0, version.length()-1).trim(); } return version.trim(); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testGetVersion() throws Exception { Version v = new Version("1,2"); Assert.assertNotNull(v.getVersion()); } |
### Question:
Version { public String getStartRange() { String[] parts = version.split(",", 2); return parts[0].trim(); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testGetStartRange() throws Exception { Version v = new Version("1,2"); Assert.assertNotNull(v.getStartRange()); Assert.assertEquals("1", v.getStartRange()); Version v1 = new Version("1.2"); Assert.assertNotNull(v1.getStartRange()); } |
### Question:
Version { public String getEndRange() { if (!isRange()) return getVersion(); String[] parts = version.split(",", 2); return parts[1].trim(); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testGetEndRange() throws Exception { Version v = new Version("1,2"); Assert.assertNotNull(v.getEndRange()); Assert.assertEquals("2", v.getEndRange()); Version v1 = new Version("1.2"); Assert.assertNotNull(v1.getEndRange()); } |
### Question:
Version { public boolean minorVersionSupport() { return version.endsWith("*"); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testMinorVersionSupport() throws Exception { Version v = new Version("1.1*"); Assert.assertTrue(v.minorVersionSupport()); Version v1 = new Version("1.2"); Assert.assertFalse(v1.minorVersionSupport()); } |
### Question:
Jetty implements WebsterService { @Override public void start() throws Exception { createServer(); ServerConnector connector = new ServerConnector(server); connector.setPort(port); String address = HostUtil.getHostAddressFromProperty("java.rmi.server.hostname"); connector.setHost(address); server.setConnectors(new Connector[] { connector }); server.setHandler(handlers); server.start(); setProperty(); } Jetty(); Jetty(File jettyConfig); Jetty(Configuration config); Jetty setRoots(String... roots); Jetty setPort(int port); Jetty setMinThreads(int minThreads); Jetty setMaxThreads(int maxThreads); Jetty setPutDir(String putDir); @Override void start(); @Override void startSecure(); @Override void terminate(); @Override URI getURI(); int getPort(); String getAddress(); void join(); static void main(String[] args); }### Answer:
@Test public void testStart() throws Exception { String projectDir = System.getProperty("projectDir"); String resources = new File(projectDir+"/src/test/resources").getPath(); File fileDir = new File(projectDir+"/build/files-2"); if(fileDir.mkdirs()) System.out.println("Created "+fileDir.getPath()); Jetty jetty = new Jetty().setRoots(resources).setPutDir(fileDir.getPath()); jetty.startSecure(); int count = 5; CyclicBarrier gate = new CyclicBarrier(count+1); CountDownLatch filesWritten = new CountDownLatch(count); List<Fetcher> fetchers = new ArrayList<>(); for (int i = 0; i < count; i++) { String file = String.format("file%s.txt", (i % 2 == 0 ? 1 : 2)); String fileURL = String.format("%s%s", jetty.getURI().toASCIIString(), file); Fetcher fetcher = new Fetcher(gate, new URL(fileURL), fileDir, filesWritten, i); fetchers.add(fetcher); new Thread(fetcher).start(); } gate.await(); filesWritten.await(); int totalFailed = 0; for (Fetcher f : fetchers) { if (f.failed > 0) { totalFailed++; System.out.println("Fetcher ["+f.index+"] failed "+f.failed+" time(s)"); } } System.out.println("Total failed Fetchers: "+totalFailed); } |
### Question:
Version { public boolean majorVersionSupport() { return version.endsWith("+"); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testMajorVersionSupport() throws Exception { Version v = new Version("1+"); Assert.assertTrue(v.majorVersionSupport()); Version v1 = new Version("1.2"); Assert.assertFalse(v1.majorVersionSupport()); } |
### Question:
Version { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Version version1 = (Version) o; return version.equals(version1.version); } Version(final String version); boolean isRange(); String getVersion(); String getStartRange(); String getEndRange(); boolean minorVersionSupport(); boolean majorVersionSupport(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testEquals() throws Exception { Version v = new Version("1.2"); Version v1 = new Version("1.2"); Assert.assertTrue(v.equals(v1)); } |
### Question:
RioProperties { public static void load() { File rioEnv; String rioEnvFileName = System.getProperty(Constants.ENV_PROPERTY_NAME, System.getenv(Constants.ENV_PROPERTY_NAME)); if(rioEnvFileName==null) { File rioRoot = new File(System.getProperty("user.home"), ".rio"); rioEnv = new File(rioRoot, "rio.env"); if(rioEnv.exists()) { loadAndSetProperties(rioEnv); } else { String rioHome = System.getProperty("rio.home", System.getenv("RIO_HOME")); if(rioHome!=null) { rioEnv = new File(rioHome, "config/rio.env"); if(rioEnv.exists()) { loadAndSetProperties(rioEnv); } else { System.err.println(rioEnv.getPath()+" not found, skipping"); } } else { System.err.println("RIO_HOME environment not set"); } } } else { rioEnv = new File(rioEnvFileName); if(rioEnv.exists()) { loadAndSetProperties(rioEnv); } } } private RioProperties(); static void load(); }### Answer:
@Test public void testLoadFromEnv() { try { System.setProperty(Constants.ENV_PROPERTY_NAME, System.getProperty("user.dir") + "/src/test/resources/config/rio.env"); RioProperties.load(); String locators = System.getProperty(Constants.LOCATOR_PROPERTY_NAME); Assert.assertNotNull(locators); } finally { System.clearProperty(Constants.ENV_PROPERTY_NAME); } }
@Test public void testLoadFromRioHome() { String oldRioHome = System.getProperty("rio.home"); try { System.setProperty("rio.home", System.getProperty("user.dir") + "/src/test/resources"); RioProperties.load(); String locators = System.getProperty(Constants.LOCATOR_PROPERTY_NAME); Assert.assertNotNull(locators); } finally { if (oldRioHome == null) System.clearProperty("RIO_HOME"); else System.setProperty("rio.home", oldRioHome); } } |
### Question:
InstantiatorResource { boolean meetsGeneralRequirements(final ProvisionRequest provisionRequest) { ServiceElement sElem = provisionRequest.getServiceElement(); String[] machineCluster = sElem.getCluster(); if (machineCluster != null && machineCluster.length > 0) { logger.debug("ServiceBean [{}] has a cluster requirement", LoggingUtil.getLoggingName(sElem)); boolean found = false; for (String aMachineCluster : machineCluster) { if (aMachineCluster.equals(resourceCapability.getAddress()) || aMachineCluster.equalsIgnoreCase(resourceCapability.getHostName())) found = true; } if (!found) { StringBuilder builder = new StringBuilder(); for (String m : machineCluster) { if (builder.length()>0) builder.append(", "); builder.append(m); } String failureReason = String.format("%s not found in cluster requirement [%s] for [%s]", getName(), builder.toString(), LoggingUtil.getLoggingName(sElem)); provisionRequest.addFailureReason(failureReason); logger.debug(failureReason); return false; } } return true; } InstantiatorResource(MarshalledObject<ServiceBeanInstantiator> wrappedServiceBeanInstantiator,
ServiceBeanInstantiator instantiator,
String instantiatorName,
Uuid instantiatorUuid,
MarshalledObject<?> handback,
ResourceCapability resourceCapability,
int serviceLimit); void addDeployedService(DeployedService newDeployedService); String getName(); Uuid getInstantiatorUuid(); int getServiceElementCount(ServiceElement sElem); int getServiceElementCount(); ServiceBeanInstantiator getInstantiator(); int getServiceCount(); MarshalledObject<?> getHandback(); ResourceCapability getResourceCapability(); int getServiceLimit(); void incrementProvisionCounter(ServiceElement sElem); synchronized void decrementProvisionCounter(ServiceElement sElem); int getInProcessCounter(); int getInProcessCounter(ServiceElement sElem); String getHostAddress(); void addUninstantiable(ServiceElement serviceElement); boolean isUninstantiable(ServiceElement serviceElement); void removeUninstantiable(ServiceElement serviceElement); void setDynamicEnabledOn(); boolean getDynamicEnabled(); boolean canProvision(final ProvisionRequest provisionRequest); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testMeetsGeneralRequirements() { ProvisionRequest request = createProvisionRequest(); assertTrue(instantiatorResource.meetsGeneralRequirements(request)); } |
### Question:
SettingsUtil { public static Settings getSettings() throws SettingsBuildingException { DefaultSettingsBuilder defaultSettingsBuilder = new DefaultSettingsBuilder(); DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); File userSettingsFile = new File(System.getProperty("user.home"), ".m2" + File.separator + "settings.xml"); request.setUserSettingsFile(userSettingsFile); defaultSettingsBuilder.setSettingsWriter(new DefaultSettingsWriter()); defaultSettingsBuilder.setSettingsReader(new DefaultSettingsReader()); defaultSettingsBuilder.setSettingsValidator(new DefaultSettingsValidator()); SettingsBuildingResult build = defaultSettingsBuilder.build(request); return build.getEffectiveSettings(); } private SettingsUtil(); static Settings getSettings(); static String getLocalRepositoryLocation(final Settings settings); }### Answer:
@Test public void testGetSettings() throws Exception { Settings settings = SettingsUtil.getSettings(); Assert.assertNotNull(settings); } |
### Question:
NettyAllocatorMetricSet implements MetricSet { @Override public Map<String, Metric> getMetrics() { Map<String, Metric> gauges = new HashMap<>(); gauges.put(name(namespace, "usedDirectMemory"), (Gauge<Long>) metric::usedDirectMemory); gauges.put(name(namespace, "usedHeapMemory"), (Gauge<Long>) metric::usedHeapMemory); return copyOf(gauges); } NettyAllocatorMetricSet(String namespace, ByteBufAllocatorMetric metric); @Override Map<String, Metric> getMetrics(); }### Answer:
@Test public void gaugeReportsDirectMemoryUsageValue() throws Exception { when(metricUnderTest.usedDirectMemory()).thenReturn(1L); NettyAllocatorMetricSet metricSet = new NettyAllocatorMetricSet("test-metric", metricUnderTest); Gauge<Long> metric = (Gauge<Long>) metricSet.getMetrics().get("test-metric.usedDirectMemory"); assertThat(metric.getValue(), is(1L)); }
@Test public void gaugeReportsHeapMemoryUsageValue() throws Exception { when(metricUnderTest.usedHeapMemory()).thenReturn(1L); NettyAllocatorMetricSet metricSet = new NettyAllocatorMetricSet("test-metric", metricUnderTest); Gauge<Long> metric = (Gauge<Long>) metricSet.getMetrics().get("test-metric.usedHeapMemory"); assertThat(metric.getValue(), is(1L)); } |
### Question:
StartupConfig { public static StartupConfig load() { String styxHome = System.getProperty(STYX_HOME_VAR_NAME); checkArgument(styxHome != null, "No system property %s has been defined.", STYX_HOME_VAR_NAME); checkArgument(isReadable(Paths.get(styxHome)), "%s=%s is not a readable configuration path.", STYX_HOME_VAR_NAME, styxHome); String configFileLocation = System.getProperty(CONFIG_FILE_LOCATION_VAR_NAME); if (configFileLocation == null) { configFileLocation = Paths.get(styxHome).resolve("conf/default.yml").toString(); } String logbackConfigLocation = System.getProperty(LOGBACK_CONFIG_LOCATION_VAR_NAME); if (logbackConfigLocation == null) { logbackConfigLocation = Paths.get(styxHome).resolve("conf/logback.xml").toString(); } return new Builder() .styxHome(styxHome) .configFileLocation(configFileLocation) .logbackConfigLocation(logbackConfigLocation) .build(); } private StartupConfig(Builder builder); static StartupConfig load(); static Builder newStartupConfigBuilder(); Path styxHome(); Resource logConfigLocation(); Resource configFileLocation(); @Override String toString(); }### Answer:
@Test public void configurationLoadingFailsIfStyxHomeIsNotSpecified() { Exception e = assertThrows(IllegalArgumentException.class, () -> StartupConfig.load()); assertEquals("No system property STYX_HOME has been defined.", e.getMessage()); }
@Test public void configurationLoadingFailsIfStyxHomeDoesNotPointToReadableLocation() { setProperty(STYX_HOME_VAR_NAME, "/undefined"); Exception e = assertThrows(IllegalArgumentException.class, () -> StartupConfig.load()); assertEquals("STYX_HOME=/undefined is not a readable configuration path.", e.getMessage()); } |
### Question:
JsonTreeTraversal { public static <T extends JsonTreeVisitor> T traverseJsonTree(JsonNode node, T visitor) { traverseJsonTree(node, null, new ArrayList<>(), visitor); return visitor; } static T traverseJsonTree(JsonNode node, T visitor); }### Answer:
@Test public void canTraverseValueNodesInOrder() throws IOException { String yaml = "" + "object:\n" + " field1: 234\n" + " field2: value2\n" + " arrayField:\n" + " - arrayValue1\n" + " - 757\n" + " - arrayObjectValue: 1234\n"; JsonNode rootNode = new ObjectMapper(new YAMLFactory()).readTree(yaml); List<Call> calls = new ArrayList<>(); traverseJsonTree(rootNode, (node, parent, path) -> calls.add(new Call(node, parent, path))); MatcherAssert.assertThat(calls.get(0).path, contains(pathElements("object", "field1"))); assertThat(calls.get(0).node, is(instanceOf(IntNode.class))); assertThat(calls.get(0).node.intValue(), is(234)); MatcherAssert.assertThat(calls.get(0).parent, IsOptional.matches(instanceOf(ObjectNode.class))); MatcherAssert.assertThat(calls.get(1).path, contains(pathElements("object", "field2"))); assertThat(calls.get(1).node, is(instanceOf(TextNode.class))); assertThat(calls.get(1).node.textValue(), is("value2")); MatcherAssert.assertThat(calls.get(1).parent, IsOptional.matches(instanceOf(ObjectNode.class))); MatcherAssert.assertThat(calls.get(2).path, contains(pathElements("object", "arrayField", 0))); assertThat(calls.get(2).node, is(instanceOf(TextNode.class))); assertThat(calls.get(2).node.textValue(), is("arrayValue1")); MatcherAssert.assertThat(calls.get(2).parent, IsOptional.matches(instanceOf(ArrayNode.class))); MatcherAssert.assertThat(calls.get(3).path, contains(pathElements("object", "arrayField", 1))); assertThat(calls.get(3).node, is(instanceOf(IntNode.class))); assertThat(calls.get(3).node.intValue(), is(757)); MatcherAssert.assertThat(calls.get(3).parent, IsOptional.matches(instanceOf(ArrayNode.class))); MatcherAssert.assertThat(calls.get(4).path, contains(pathElements("object", "arrayField", 2, "arrayObjectValue"))); assertThat(calls.get(4).node, is(instanceOf(IntNode.class))); assertThat(calls.get(4).node.intValue(), is(1234)); MatcherAssert.assertThat(calls.get(4).parent, IsOptional.matches(instanceOf(ObjectNode.class))); } |
### Question:
YamlConfigurationFormat implements ConfigurationFormat<YamlConfiguration> { @Override public String resolvePlaceholdersInText(String text, Map<String, String> overrides) { List<PlaceholderResolver.Placeholder> placeholders = extractPlaceholders(text); String resolvedText = text; for (PlaceholderResolver.Placeholder placeholder : placeholders) { resolvedText = resolvePlaceholderInText(resolvedText, placeholder, overrides); } return resolvedText; } private YamlConfigurationFormat(); @Override YamlConfiguration deserialise(String string); @Override YamlConfiguration deserialise(Resource resource); @Override String resolvePlaceholdersInText(String text, Map<String, String> overrides); @Override String toString(); static final YamlConfigurationFormat YAML; }### Answer:
@Test public void canResolvePlaceholdersInInclude() throws IOException { Map<String, String> overrides = ImmutableMap.of("CONFIG_LOCATION", "some_location"); String yaml = "${CONFIG_LOCATION:classpath:}/conf/environment/default.yaml"; String resolved = YamlConfigurationFormat.YAML.resolvePlaceholdersInText(yaml, overrides); assertThat(resolved, is("some_location/conf/environment/default.yaml")); } |
### Question:
PlaceholderResolver { @VisibleForTesting static List<String> extractPlaceholderStrings(String value) { Matcher matcher = PLACEHOLDER_REGEX_CAPTURE_ALL.matcher(value); List<String> placeholders = new ArrayList<>(); while (matcher.find()) { placeholders.add(matcher.group()); } return placeholders; } PlaceholderResolver(ObjectNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Properties properties); Collection<UnresolvedPlaceholder> resolve(); @VisibleForTesting static String replacePlaceholder(String originalString, String placeholderName, String placeholderValue); @VisibleForTesting static List<Placeholder> extractPlaceholders(String value); }### Answer:
@Test public void extractsPlaceholders() { String valueWithPlaceholders = "foo ${with.default:defaultValue} bar ${without.default} ${configLocation:classpath:}foo"; List<String> placeholders = PlaceholderResolver.extractPlaceholderStrings(valueWithPlaceholders); assertThat(placeholders, contains("${with.default:defaultValue}", "${without.default}", "${configLocation:classpath:}")); }
@Test public void extractsPlaceholdersWithEmptyDefaults() { String valueWithPlaceholders = "foo: \"${FOO:}\""; List<String> placeholders = PlaceholderResolver.extractPlaceholderStrings(valueWithPlaceholders); assertThat(placeholders, contains("${FOO:}")); } |
### Question:
PlaceholderResolver { @VisibleForTesting public static List<Placeholder> extractPlaceholders(String value) { List<Placeholder> namesAndDefaults = new ArrayList<>(); for (String placeholder : extractPlaceholderStrings(value)) { Matcher placeholderMatcher = PLACEHOLDER_REGEX_CAPTURE_NAME_AND_DEFAULT.matcher(placeholder); if (placeholderMatcher.matches()) { namesAndDefaults.add(new Placeholder(placeholderMatcher.group(1), placeholderMatcher.group(2))); } } return namesAndDefaults; } PlaceholderResolver(ObjectNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Properties properties); Collection<UnresolvedPlaceholder> resolve(); @VisibleForTesting static String replacePlaceholder(String originalString, String placeholderName, String placeholderValue); @VisibleForTesting static List<Placeholder> extractPlaceholders(String value); }### Answer:
@Test public void extractsPlaceholderNamesAndDefaults() { String valueWithPlaceholders = "foo ${with.default:defaultValue} bar ${without.default} ${configLocation:classpath:}foo"; List<Placeholder> placeholders = PlaceholderResolver.extractPlaceholders(valueWithPlaceholders); List<Placeholder> expected = ImmutableList.of( new Placeholder("with.default", "defaultValue"), new Placeholder("without.default"), new Placeholder("configLocation", "classpath:")); assertThat(placeholders, is(expected)); }
@Test public void extractsPlaceholderNamesAndEmptyDefaults() { String valueWithPlaceholders = "${FOO:}"; List<Placeholder> placeholders = PlaceholderResolver.extractPlaceholders(valueWithPlaceholders); assertThat(placeholders, is(singletonList(new Placeholder("FOO", "")))); } |
### Question:
PlaceholderResolver { @VisibleForTesting public static String replacePlaceholder(String originalString, String placeholderName, String placeholderValue) { return originalString.replaceAll("\\$\\{" + quote(placeholderName) + "(?:\\:[^\\}]*?)?\\}", placeholderValue); } PlaceholderResolver(ObjectNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Map<String, String> externalProperties); static Collection<UnresolvedPlaceholder> resolvePlaceholders(JsonNode rootNode, Properties properties); Collection<UnresolvedPlaceholder> resolve(); @VisibleForTesting static String replacePlaceholder(String originalString, String placeholderName, String placeholderValue); @VisibleForTesting static List<Placeholder> extractPlaceholders(String value); }### Answer:
@Test public void replacesPlaceholder() { String original = "foo ${with.default:defaultValue} bar ${without.default}"; assertThat(PlaceholderResolver.replacePlaceholder(original, "with.default", "replacement"), is("foo replacement bar ${without.default}")); assertThat(PlaceholderResolver.replacePlaceholder(original, "without.default", "replacement"), is("foo ${with.default:defaultValue} bar replacement")); } |
### Question:
NodePath { public Optional<JsonNode> findMatchingDescendant(JsonNode rootNode) { JsonNode current = rootNode; for (PathElement element : elements) { current = element.child(current); if (current == null) { return Optional.empty(); } } return Optional.ofNullable(current); } NodePath(String path); NodePath(List<PathElement> elements); List<PathElement> elements(); PathElement lastElement(); Optional<JsonNode> findMatchingDescendant(JsonNode rootNode); boolean override(JsonNode rootNode, JsonNode leaf); boolean override(JsonNode rootNode, String value); @Override String toString(); }### Answer:
@Test public void canGetTopLevelProperty() { assertThat(new NodePath("text").findMatchingDescendant(root), matches(isTextNode("abc"))); }
@Test public void canGetArrayElements() { assertThat(new NodePath("array[0]").findMatchingDescendant(root), matches(isTextNode("alpha"))); assertThat(new NodePath("array[1]").findMatchingDescendant(root), matches(isTextNode("beta"))); assertThat(new NodePath("array[2]").findMatchingDescendant(root), matches(isTextNode("gamma"))); }
@Test public void canGetObjectField() { assertThat(new NodePath("object.field1").findMatchingDescendant(root), matches(isTextNode("foo"))); assertThat(new NodePath("object.field2").findMatchingDescendant(root), matches(isTextNode("bar"))); }
@Test public void canGetFieldsWithinArrayElementObjects() { assertThat(new NodePath("array2[0].arrayObjectField1").findMatchingDescendant(root), matches(isTextNode("abc"))); assertThat(new NodePath("array2[0].arrayObjectField2").findMatchingDescendant(root), matches(isTextNode("def"))); } |
### Question:
JsonNodeConfig implements Configuration { @Override public Optional<String> get(String key) { return get(key, String.class); } JsonNodeConfig(JsonNode rootNode); protected JsonNodeConfig(JsonNode rootNode, ObjectMapper mapper); @Override Optional<String> get(String key); @Override Optional<T> get(String property, Class<T> tClass); @Override X as(Class<X> type); @Override String toString(); }### Answer:
@Test public void extractsDefaultStringTypeConfigurationFromJsonNode() { JsonNode rootNode = jsonNode("{\"text\":\"foo\"}"); JsonNodeConfig config = new JsonNodeConfig(rootNode); assertThat(config.get("text"), isValue("foo")); assertThat(config.get("nonExistent"), isAbsent()); }
@Test public void extractsSpecifiedTypeConfigurationFromJsonNode() { JsonNode rootNode = jsonNode("{\"text\":\"foo\",\"number\":123}"); JsonNodeConfig config = new JsonNodeConfig(rootNode); assertThat(config.get("text", String.class), isValue("foo")); assertThat(config.get("nonExistent", String.class), isAbsent()); assertThat(config.get("number", Integer.class), isValue(123)); assertThat(config.get("nonExistent", Integer.class), isAbsent()); } |
### Question:
ConfigurationParser { public C parse(ConfigurationSource provider) { LOGGER.debug("Parsing configuration in format={} from source={}", format, provider); C configuration = doParse(provider).withOverrides(overrides); PlaceholderResolutionResult<C> resolved = configuration.resolvePlaceholders(overrides); if (!resolved.unresolvedPlaceholders().isEmpty()) { throw new IllegalStateException(format("Unresolved placeholders: %s", resolved.unresolvedPlaceholders())); } return resolved.resolvedConfiguration(); } private ConfigurationParser(Builder<C> builder); C parse(ConfigurationSource provider); }### Answer:
@Test public void providesConfig() { createStubConfig("/fake/simple-config.yml", ImmutableMap.of( "foo", 123, "bar", "abc")); ConfigurationParser<StubConfiguration> parser = new ConfigurationParser.Builder<StubConfiguration>() .format(format) .build(); StubConfiguration parsedConfiguration = parser.parse(configSource(newResource("/fake/simple-config.yml"))); assertThat(parsedConfiguration.get("bar"), isValue("abc")); assertThat(parsedConfiguration.get("foo", Integer.class), isValue(123)); }
@Test public void includesParent() { ConfigurationParser<StubConfiguration> parser = new ConfigurationParser.Builder<StubConfiguration>() .format(format) .build(); StubConfiguration parsedConfiguration = parser.parse(configSource(newResource("/fake/base-config.yml"))); assertThat(parsedConfiguration.get("string"), isValue("abc")); assertThat(parsedConfiguration.get("stringFromParent"), isValue("DEF")); assertThat(parsedConfiguration.get("numberFromParent", Integer.class), isValue(999)); }
@Test public void includedValuesCanBeOverridden() { ConfigurationParser<StubConfiguration> parser = new ConfigurationParser.Builder<StubConfiguration>() .format(format) .build(); StubConfiguration parsedConfiguration = parser.parse(configSource(newResource("/fake/base-config.yml"))); assertThat(parsedConfiguration.get("string"), isValue("abc")); assertThat(parsedConfiguration.get("stringFromParent"), isValue("DEF")); assertThat(parsedConfiguration.get("numberFromParent", Integer.class), isValue(999)); }
@Test public void resolvesPlaceholdersInConfig() { ConfigurationParser<StubConfiguration> parser = new ConfigurationParser.Builder<StubConfiguration>() .format(format) .build(); StubConfiguration parsedConfiguration = parser.parse(configSource(newResource("/fake/base-config.yml"))); assertThat(parsedConfiguration.get("hasPlaceholder"), isValue("abc")); }
@Test public void appliesOverrides() { ConfigurationParser<StubConfiguration> parser = new ConfigurationParser.Builder<StubConfiguration>() .format(format) .overrides(ImmutableMap.of("string", "overridden")) .build(); StubConfiguration parsedConfiguration = parser.parse(configSource(newResource("/fake/base-config.yml"))); assertThat(parsedConfiguration.get("string"), isValue("overridden")); }
@Test public void includeValueCanContainPlaceholder() { createStubConfig("/test/base-config.yml", ImmutableMap.of( "include", "${include-placeholder}", "number", 123, "string", "abc", "numberFromParent", 999, "hasPlaceholder", "${string}" )); createStubConfig("/test/parent-config.yml", ImmutableMap.of( "numberFromParent", 111, "stringFromParent", "DEF")); ConfigurationParser<StubConfiguration> parser = new ConfigurationParser.Builder<StubConfiguration>() .format(format) .overrides(ImmutableMap.of("include-placeholder", "/test/parent-config.yml")) .build(); StubConfiguration parsedConfiguration = parser.parse(configSource(newResource("/test/base-config.yml"))); assertThat(parsedConfiguration.get("stringFromParent"), isValue("DEF")); }
@Test public void childCanReplaceParentPlaceholders() { createStubConfig("/test/base-config.yml", ImmutableMap.of( "include", "/test/parent-config.yml", "childString", "abc" )); createStubConfig("/test/parent-config.yml", ImmutableMap.of( "parentString", "${childString}" )); ConfigurationParser<StubConfiguration> parser = new ConfigurationParser.Builder<StubConfiguration>() .format(format) .build(); StubConfiguration parsedConfiguration = parser.parse(configSource(newResource("/test/base-config.yml"))); assertThat(parsedConfiguration.get("parentString"), isValue("abc")); } |
### Question:
GraphiteReporter extends ScheduledReporter { @VisibleForTesting void initConnection() { tryTimes( MAX_RETRIES, graphite::connect, (e) -> attemptErrorHandling(graphite::close) ); } private GraphiteReporter(MetricRegistry registry,
GraphiteSender graphite,
Clock clock,
String prefix,
TimeUnit rateUnit,
TimeUnit durationUnit,
MetricFilter filter); static Builder forRegistry(MetricRegistry registry); @Override void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String, Timer> timers); @Override void stop(); }### Answer:
@Test public void initConnectionRetriesOnFailure() throws Exception { doThrow(new UnknownHostException("UNKNOWN-HOST")).when(graphite).connect(); try { reporter.initConnection(); fail("Should have thrown an exception"); } catch (UncheckedIOException e) { verify(graphite, times(MAX_RETRIES)).connect(); } } |
### Question:
MemoryBackedRegistry extends AbstractRegistry<T> { public void add(T t) { resources.put(t.id(), t); if (autoReload) { reload(); } } MemoryBackedRegistry(); private MemoryBackedRegistry(boolean autoReload); void add(T t); void removeById(Id id); void reset(); @Override CompletableFuture<ReloadResult> reload(); }### Answer:
@Test public void addsResources() { BackendService landing = backendService("landing", 9091); BackendService shopping = backendService("shopping", 9090); MemoryBackedRegistry<BackendService> registry = new MemoryBackedRegistry<>(); registry.add(landing); registry.addListener(listener); registry.add(shopping); assertThat(registry.get(), containsInAnyOrder(landing, shopping)); verify(listener).onChange(eq(added(shopping))); }
@Test public void updatesResources() { BackendService landing = backendService("landing", 9091); MemoryBackedRegistry<BackendService> registry = new MemoryBackedRegistry<>(); registry.add(backendService("shopping", 9090)); registry.add(landing); registry.addListener(listener); BackendService shopping = backendService("shopping", 9091); registry.add(shopping); assertThat(registry.get(), containsInAnyOrder(landing, shopping)); verify(listener).onChange(eq(updated(shopping))); } |
### Question:
ExceptionConverter extends ClassicConverter { @Override public String convert(final ILoggingEvent loggingEvent) { return Optional.ofNullable(loggingEvent) .map(this::getExceptionData) .orElse(NO_MSG); } @Override String convert(final ILoggingEvent loggingEvent); static final String TARGET_CLASSES_PROPERTY_NAME; }### Answer:
@Test public void extractsTheExceptionClassMethodAndCreatesAUniqueExceptionId() throws Exception { ExceptionConverter converter = newExceptionConverter(); assertThat(converter.convert(loggingEvent).trim(), endsWith("[exceptionClass=com.hotels.styx.infrastructure.logging.ExceptionConverterTest, exceptionMethod=<init>, exceptionID=10d7182c]")); }
@Test public void gracefullyHandlesExceptionInstancesWithoutStackTrace() throws Exception { ExceptionConverter converter = newExceptionConverter(); ILoggingEvent errorEvent = newErrorLoggingEvent(new NoStackException()); assertThat(converter.convert(errorEvent), endsWith("")); }
@Test public void prioritizeTargetClassStackTraceElementsOverTheRootOnes() throws Exception { ExceptionConverter converter = newExceptionConverter(); converter.getContext() .putProperty(TARGET_CLASSES_PROPERTY_NAME, "TargetClass"); ILoggingEvent loggingEvent = newErrorLoggingEvent(new TargetClass().blow()); assertThat(converter.convert(loggingEvent).trim(), endsWith("[exceptionClass=com.hotels.styx.infrastructure.logging.ExceptionConverterTest$TargetClass, exceptionMethod=blow, exceptionID=8b93d529]")); }
@Test public void errorsIfTargetClassPropertyIsEmpty() throws Exception { ContextBase contextBase = new ContextBase(); StatusManager statusManager = mock(StatusManager.class); contextBase.setStatusManager(statusManager); ExceptionConverter converter = newExceptionConverter(contextBase); converter.getContext() .putProperty(TARGET_CLASSES_PROPERTY_NAME, ""); ILoggingEvent loggingEvent = newErrorLoggingEvent(new TargetClass().blow()); converter.convert(loggingEvent); verify(statusManager).add(any(ErrorStatus.class)); } |
### Question:
LOGBackConfigurer { public static void initLogging(String logConfigLocation, boolean installJULBridge) { try { String location = resolvePlaceholders(logConfigLocation); if (location.indexOf("${") >= 0) { throw new IllegalStateException("unable to resolve certain placeholders: " + sanitise(location)); } location = location.replaceAll("\\\\", "/"); String notice = "If you are watching the console output, it may stop after this point, if configured to only write to file."; Logger.getLogger(LOGBackConfigurer.class.getName()).info("Initializing LOGBack from [" + sanitise(location) + "]. " + notice); initLogging(getURL(location), installJULBridge); } catch (FileNotFoundException ex) { throw new IllegalArgumentException("invalid '" + sanitise(logConfigLocation) + "' parameter: " + ex.getMessage()); } } private LOGBackConfigurer(); static void initLogging(String logConfigLocation, boolean installJULBridge); static void initLogging(URL url, boolean installJULBridge); static void shutdownLogging(boolean uninstallJULBridge); }### Answer:
@Test public void canConfigureLoggingFromClasspath() { initLogging("classpath:conf/logback.xml", false); }
@Test public void canConfigureLoggingFromURL() { initLogging(LOGBackConfigurerTest.class.getResource("/conf/logback.xml"), false); }
@Test public void resolvesPlaceholdersBeforeInitializing() { System.setProperty("CONFIG_LOCATION", "classpath:"); initLogging("${CONFIG_LOCATION}conf/logback.xml", false); }
@Test public void failsForInvalidLogbackPath() { assertThrows(IllegalArgumentException.class, () -> initLogging(NON_EXISTENT_LOGBACK, false)); } |
### Question:
StyxConfig implements Configuration { public ProxyServerConfig proxyServerConfig() { return proxyServerConfig; } StyxConfig(); StyxConfig(Configuration configuration); @Override Optional<T> get(String key, Class<T> tClass); @Override X as(Class<X> type); @Override Optional<String> get(String key); StyxHeaderConfig styxHeaderConfig(); ProxyServerConfig proxyServerConfig(); AdminServerConfig adminServerConfig(); int port(); Optional<String> applicationsConfigurationPath(); Iterable<Resource> versionFiles(StartupConfig startupConfig); static StyxConfig fromYaml(String yamlText); static StyxConfig fromYaml(String yamlText, boolean validateConfiguration); static StyxConfig defaultConfig(); @Override String toString(); static final String NO_JVM_ROUTE_SET; }### Answer:
@Test public void readsTheDefaultValueForBossThreadsCountIfNotConfigured() { assertThat(styxConfig.proxyServerConfig().bossThreadsCount(), is(HALF_OF_AVAILABLE_PROCESSORS)); }
@Test public void readsTheDefaultValueForClientWorkerThreadsCountIfNotConfigured() { assertThat(styxConfig.proxyServerConfig().clientWorkerThreadsCount(), is(HALF_OF_AVAILABLE_PROCESSORS)); } |
### Question:
YamlApplicationsProvider { public static YamlApplicationsProvider loadFromPath(String path) { return new YamlApplicationsProvider(newResource(path)); } private YamlApplicationsProvider(String yamlText); YamlApplicationsProvider(Resource resource); static YamlApplicationsProvider loadFromPath(String path); static YamlApplicationsProvider loadFromText(String yamlText); static BackendServices loadApplicationsFrom(String path); BackendServices get(); }### Answer:
@Test public void stickySessionIsDisabledByDefault() { YamlApplicationsProvider config = loadFromPath("classpath:conf/origins/origins-for-configtest.yml"); BackendService app = applicationFor(config, "shopping"); assertThat(app.stickySessionConfig().stickySessionEnabled(), CoreMatchers.is(false)); }
@Test public void stickySessionEnabledWhenYamlStickySessionEnabledIsTrue() { YamlApplicationsProvider config = loadFromPath("classpath:conf/origins/origins-for-configtest.yml"); BackendService app = applicationFor(config, "webapp"); assertThat(app.stickySessionConfig().stickySessionEnabled(), CoreMatchers.is(true)); }
@Test public void cannotLoadWithNoApplications() throws IOException { Exception e = assertThrows(Exception.class, () -> loadFromPath("classpath:/conf/origins/empty-origins-for-configtest.yml")); assertThat(e.getMessage(), matchesPattern("Invalid YAML from classpath:conf/origins/empty-origins-for-configtest.yml: No content to map due to end-of-input\n at \\[Source: .*\\]")); }
@Test public void doesNotLoadIfFileDoesNotExist() { Exception e = assertThrows(RuntimeException.class, () -> loadFromPath("/sadiusadasd")); assertThat(e.getMessage(), matchesPattern("Unable to load YAML from.*")); }
@Test public void cannotLoadWithSyntaxErrors() throws IOException { Exception e = assertThrows(RuntimeException.class, () -> loadFromPath("classpath:/conf/origins/origins-with-syntax-error-for-configtest.yml")); assertThat(e.getMessage(), matchesPattern("Invalid YAML from classpath:conf/origins/origins-with-syntax-error-for-configtest.yml: Cannot deserialize instance of `java.util.ArrayList<com.hotels.styx.api.extension.service.BackendService>` out of VALUE_STRING token\n at \\[Source: .*\\]")); } |
### Question:
ServiceProvision { public static <E extends RetryPolicy> Optional<E> loadRetryPolicy( Configuration configuration, Environment environment, String key, Class<? extends E> serviceClass) { return configuration .get(key, ServiceFactoryConfig.class) .map(factoryConfig -> { RetryPolicyFactory factory = newInstance(factoryConfig.factory(), RetryPolicyFactory.class); JsonNodeConfig config = factoryConfig.config(); return serviceClass.cast(factory.create(environment, config)); }); } private ServiceProvision(); static Optional<E> loadLoadBalancer(
Configuration configuration,
Environment environment,
String key,
Class<? extends E> serviceClass,
ActiveOrigins activeOrigins); static Optional<E> loadRetryPolicy(
Configuration configuration,
Environment environment,
String key,
Class<? extends E> serviceClass); static Map<String, T> loadServices(Configuration configuration, Environment environment, String key, Class<? extends T> serviceClass); }### Answer:
@Test public void serviceReturnsCorrectlyFromCall() { assertThat(loadRetryPolicy(environment.configuration(), environment, "myRetry.factory", RetryPolicy.class).get(), is(instanceOf(RetryPolicy.class))); }
@Test public void serviceReturnsEmptyWhenFactoryKeyDoesNotExist() { assertThat(loadRetryPolicy(environment.configuration(), environment, "invalid.key", RetryPolicy.class), isAbsent()); }
@Test public void throwsExceptionWhenClassDoesNotExist() { Exception e = assertThrows(Exception.class, () -> loadRetryPolicy(environment.configuration(), environment, "not.real", RetryPolicy.class)); assertThat(e.getMessage(), matchesPattern("(?s).*No such class 'my.FakeClass'.*")); } |
### Question:
ServiceProvision { public static <T> Map<String, T> loadServices(Configuration configuration, Environment environment, String key, Class<? extends T> serviceClass) { return configuration.get(key, JsonNode.class) .<Map<String, T>>map(node -> servicesMap(node, environment, serviceClass)) .orElse(emptyMap()); } private ServiceProvision(); static Optional<E> loadLoadBalancer(
Configuration configuration,
Environment environment,
String key,
Class<? extends E> serviceClass,
ActiveOrigins activeOrigins); static Optional<E> loadRetryPolicy(
Configuration configuration,
Environment environment,
String key,
Class<? extends E> serviceClass); static Map<String, T> loadServices(Configuration configuration, Environment environment, String key, Class<? extends T> serviceClass); }### Answer:
@Test public void servicesReturnCorrectlyFromCall() { Map<String, String> services = loadServices(environment.configuration(), environment, "multi", String.class); assertThat(services, isMap(ImmutableMap.of( "one", "valueNumber1", "two", "valueNumber2", "three", "valueNumber3" ))); }
@Test public void isInstanceWorks() { Environment env = environmentWithConfig(yamlForServices); Map<String, StyxService> services = loadServices(env.configuration(), env, "multi", StyxService.class); assertThat(services.get("backendProvider"), instanceOf(BackendServiceProvider.class)); assertThat(services.get("routingProvider"), instanceOf(RoutingObjectProvider.class)); }
@Test public void loadsNewConfigurationFormat() { Environment env = environmentWithConfig(yamlForServiceFactories); Map<String, StyxService> services = loadServices(env.configuration(), env, "multi", StyxService.class); assertThat(services.get("backendProvider"), instanceOf(BackendServiceProvider.class)); assertThat(services.get("routingProvider"), instanceOf(RoutingObjectProvider.class)); }
@Test public void loadsFromMixedConfigFormat() { Environment env = environmentWithConfig(yamlForMixedServiceFactories); Map<String, StyxService> services = loadServices(env.configuration(), env, "multi", StyxService.class); assertThat(services.get("backendProvider"), instanceOf(BackendServiceProvider.class)); assertThat(services.get("routingProvider"), instanceOf(RoutingObjectProvider.class)); }
@Test public void ignoresDisabledServices() { Environment env = environmentWithConfig(mixedDisabledServices); Map<String, StyxService> services = loadServices(env.configuration(), env, "multi", StyxService.class); assertThat(services.isEmpty(), is(true)); }
@Test public void servicesReturnEmptyWhenFactoryKeyDoesNotExist() { Map<String, String> services = loadServices(environment.configuration(), environment, "invalid.key", String.class); assertThat(services, isMap(emptyMap())); }
@Test public void throwsExceptionForInvalidServiceFactoryConfig() { String config = "" + "multi:\n" + " factories:\n" + " backendProvider:\n" + " enabled: false\n" + " config:\n" + " stringValue: valueNumber1\n"; Environment env = environmentWithConfig(config); Exception e = assertThrows(ConfigurationException.class, () -> loadServices(env.configuration(), env, "multi", StyxService.class)); assertThat(e.getMessage(), matchesPattern("Unexpected configuration object 'services.factories.backendProvider', Configuration.*'")); }
@Test public void throwsExceptionForInvalidSpiExtensionFactory() { String config = "" + "multi:\n" + " factories:\n" + " backendProvider:\n" + " enabled: false\n" + " factory:\n" + " classPath: /path/to/jar\n" + " config:\n" + " attribute: x\n"; Environment env = environmentWithConfig(config); Exception e = assertThrows(ConfigurationException.class, () -> loadServices(env.configuration(), env, "multi", StyxService.class)); assertThat(e.getMessage(), matchesPattern("Unexpected configuration object 'services.factories.backendProvider', Configuration.*'")); } |
### Question:
StyxServer extends AbstractService { public InetSocketAddress proxyHttpAddress() { return Optional.ofNullable(httpServer) .map(InetServer::inetAddress) .orElse(null); } StyxServer(StyxServerComponents config); StyxServer(StyxServerComponents components, Stopwatch stopwatch); static void main(String[] args); InetSocketAddress serverAddress(String name); InetSocketAddress proxyHttpAddress(); InetSocketAddress proxyHttpsAddress(); InetSocketAddress adminHttpAddress(); }### Answer:
@Test public void serverDoesNotStartUntilPluginsAreStarted() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); StyxServer styxServer = styxServerWithPlugins(ImmutableMap.of( "slowlyStartingPlugin", new Plugin() { @Override public void styxStarting() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request1, Chain chain) { return Eventual.of(response(OK).build()); } } )); try { styxServer.startAsync(); Thread.sleep(10); assertThat(styxServer.proxyHttpAddress(), nullValue()); latch.countDown(); eventually(() -> assertThat(styxServer.proxyHttpAddress().getPort(), is(greaterThan(0)))); } finally { stopIfRunning(styxServer); } } |
### Question:
StyxServer extends AbstractService { public static void main(String[] args) { try { StyxServer styxServer = createStyxServer(args); getRuntime().addShutdownHook(new Thread(() -> styxServer.stopAsync().awaitTerminated())); styxServer.startAsync().awaitRunning(); } catch (SchemaValidationException cause) { LOG.error(cause.getMessage()); System.exit(2); } catch (Throwable cause) { LOG.error("Error in Styx server startup.", cause); System.exit(1); } } StyxServer(StyxServerComponents config); StyxServer(StyxServerComponents components, Stopwatch stopwatch); static void main(String[] args); InetSocketAddress serverAddress(String name); InetSocketAddress proxyHttpAddress(); InetSocketAddress proxyHttpsAddress(); InetSocketAddress adminHttpAddress(); }### Answer:
@Test public void startsFromMain() { try { setProperty("STYX_HOME", fixturesHome()); StyxServer.main(new String[0]); eventually(() -> assertThat(log.log(), hasItem(loggingEvent(INFO, "Started Styx server in \\d+ ms")))); } finally { clearProperty("STYX_HOME"); } } |
### Question:
ResponseInfoFormat { public String format(LiveHttpRequest request) { return String.format(format, request == null ? "" : request.id()); } ResponseInfoFormat(Environment environment); String format(LiveHttpRequest request); }### Answer:
@Test public void defaultFormatDoesNotIncludeVersion() { String info = new ResponseInfoFormat(defaultEnvironment()).format(request); assertThat(info, is("noJvmRouteSet;" + request.id())); }
@Test public void canConfigureCustomHeaderFormatWithVersion() { StyxHeaderConfig styxHeaderConfig = new StyxHeaderConfig( new StyxHeaderConfig.StyxHeader( null, "{VERSION};{REQUEST_ID};{INSTANCE}"), null, null); Environment environment = environment(new MapBackedConfiguration() .set("styxHeaders", styxHeaderConfig)); String info = new ResponseInfoFormat(environment).format(request); assertThat(info, is("STYX-dev.0.0;" + request.id() + ";noJvmRouteSet")); } |
### Question:
SpiExtension { public JsonNode config() { return config; } @JsonCreator SpiExtension(@JsonProperty("factory") SpiExtensionFactory factory,
@JsonProperty("config") JsonNode config,
@JsonProperty("enabled") Boolean enabled); SpiExtensionFactory factory(); JsonNode config(); boolean enabled(); T config(Class<T> configClass); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void getsConfigAsClass() throws IOException { JsonNode configNode = MAPPER.readTree("foo: bar"); SpiExtension metadata = new SpiExtension(new SpiExtensionFactory("factoryClass", "classPath"), configNode, null); TestObject config = metadata.config(TestObject.class); assertThat(config.foo, is("bar")); } |
### Question:
ExtensionObjectFactory { public <T> T newInstance(SpiExtensionFactory extensionFactory, Class<T> type) throws ExtensionLoadingException { try { Class<?> extensionClass = loadClass(extensionFactory); Object instance = extensionClass.newInstance(); return type.cast(instance); } catch (ExtensionLoadingException e) { throw e; } catch (Exception e) { throw new ExtensionLoadingException("error instantiating class=" + extensionFactory.factoryClass(), e); } } private ExtensionObjectFactory(); @VisibleForTesting ExtensionObjectFactory(Function<SpiExtensionFactory, ClassSource> extensionLocator); T newInstance(SpiExtensionFactory extensionFactory, Class<T> type); static final ExtensionObjectFactory EXTENSION_OBJECT_FACTORY; }### Answer:
@Test public void throwsAppropriateExceptionIfClassNotFound() { ExtensionObjectFactory factory = new ExtensionObjectFactory(extensionFactory -> name -> { throw new ClassNotFoundException(); }); Exception e = assertThrows(ExtensionLoadingException.class, () -> factory.newInstance(new SpiExtensionFactory("some.FakeClass", "/fake/class/path"), Object.class)); assertEquals("no class=some.FakeClass is found in the specified classpath=/fake/class/path", e.getMessage()); }
@Test public void throwsAppropriateExceptionIfObjectCannotBeInstantiated() { ExtensionObjectFactory factory = new ExtensionObjectFactory(extensionFactory -> DEFAULT_CLASS_LOADER); String className = CannotInstantiate.class.getName(); try { factory.newInstance(new SpiExtensionFactory(className, "/fake/class/path"), Object.class); fail("No exception thrown"); } catch (ExtensionLoadingException e) { assertThat(e.getMessage(), is("error instantiating class=" + className)); assertThat(e.getCause(), is(instanceOf(IllegalAccessException.class))); } }
@Test public void instantiatesObjects() { ExtensionObjectFactory factory = new ExtensionObjectFactory(extensionFactory -> DEFAULT_CLASS_LOADER); String className = String.class.getName(); Object object = factory.newInstance(new SpiExtensionFactory(className, "/fake/class/path"), Object.class); assertThat(object, is(instanceOf(String.class))); } |
### Question:
PluginListHandler implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { Stream<NamedPlugin> enabled = plugins.stream().filter(NamedPlugin::enabled); Stream<NamedPlugin> disabled = plugins.stream().filter(plugin -> !plugin.enabled()); boolean needsIncludeDisabledPlugins = existDisabledPlugins(); String output = section(needsIncludeDisabledPlugins ? "Enabled" : "Loaded", enabled) + (needsIncludeDisabledPlugins ? section("Disabled", disabled) : ""); return Eventual.of(response(OK) .body(output, UTF_8) .addHeader(CONTENT_TYPE, HTML_UTF_8.toString()) .build()); } PluginListHandler(List<NamedPlugin> plugins); @Override Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context); }### Answer:
@Test public void showsEnabledAndDisabledPlugins() { NamedPlugin one = namedPlugin("one", PASS_THROUGH); NamedPlugin two = namedPlugin("two", PASS_THROUGH); NamedPlugin three = namedPlugin("three", PASS_THROUGH); NamedPlugin four = namedPlugin("four", PASS_THROUGH); two.setEnabled(false); three.setEnabled(false); List<NamedPlugin> plugins = asList(one, two, three, four); PluginListHandler handler = new PluginListHandler(plugins); HttpResponse response = Mono.from(handler.handle(get("/").build(), requestContext())).block(); assertThat(response.status(), is(OK)); assertThat(response.bodyAs(UTF_8), is("" + "<h3>Enabled</h3>" + "<a href='/admin/plugins/one'>one</a><br />" + "<a href='/admin/plugins/four'>four</a><br />" + "<h3>Disabled</h3>" + "<a href='/admin/plugins/two'>two</a><br />" + "<a href='/admin/plugins/three'>three</a><br />")); }
@Test public void showsLoadedPlugins() { NamedPlugin one = namedPlugin("one", PASS_THROUGH); NamedPlugin two = namedPlugin("two", PASS_THROUGH); List<NamedPlugin> plugins = asList(one, two); PluginListHandler handler = new PluginListHandler(plugins); HttpResponse response = Mono.from( handler.handle(get("/").build(), requestContext())).block(); assertThat(response.status(), is(OK)); assertThat(response.bodyAs(UTF_8), is("" + "<h3>Loaded</h3>" + "<a href='/admin/plugins/one'>one</a><br />" + "<a href='/admin/plugins/two'>two</a><br />")); } |
### Question:
JsonReformatter { public static String reformat(String json) { try { return reformat0(json); } catch (IOException e) { throw new RuntimeException(e); } } private JsonReformatter(); static String reformat(String json); }### Answer:
@Test public void splitsUpDotsIfTheyAreCommonBetweenKeysInSameObject() { String before = "{\"foo.one\":1, \"foo.two\":2}"; String after = JsonReformatter.reformat(before); String actual = removeWhiteSpace(after); assertThat(actual, is("{\"foo\":{\"one\":1,\"two\":2}}")); }
@Test public void splitsUpDotsIfTheyAreCommonBetweenKeysInSameObjectWhenThereIsAnotherRootValue() { String before = "{\"foo.one\":1, \"foo.two\":2, \"bar\":3}"; String after = JsonReformatter.reformat(before); String actual = removeWhiteSpace(after); assertThat(actual, is("{\"bar\":3,\"foo\":{\"one\":1,\"two\":2}}")); }
@Test public void doesNotSplitUpDotsIfTheyAreNotCommonBetweenKeysInSameObject() { String before = "{\"foo.one\":1, \"bar.two\":2}"; String after = JsonReformatter.reformat(before); String actual = removeWhiteSpace(after); assertThat(actual, is("{\"bar.two\":2,\"foo.one\":1}")); }
@Test public void doesNotSplitUpDotsIfTheyAreNotCommonBetweenKeysInSameObjectWhenThereIsAnotherRootValue() { String before = "{\"foo.one\":1, \"bar.two\":2, \"baz\":3}"; String after = JsonReformatter.reformat(before); String actual = removeWhiteSpace(after); assertThat(actual, is("{\"bar.two\":2,\"baz\":3,\"foo.one\":1}")); }
@Test public void createsMetricsJsonCorrectly() throws JsonProcessingException { MetricRegistry registry = new MetricRegistry(); registry.counter("styx.origins.status.200").inc(); registry.counter("styx.origins.status.500").inc(2); registry.counter("styx.error").inc(3); registry.counter("foo.bar").inc(4); registry.register("styx.mygauge", (Gauge<Integer>) () -> 123); String before = new ObjectMapper() .registerModule(new MetricsModule(SECONDS, MILLISECONDS, false)) .writeValueAsString(registry); String after = JsonReformatter.reformat(before); assertThat(after, matchesRegex(quote("{\n" + " \"counters\":{\n" + " \"foo.bar.count\":4,\n" + " \"styx\":{\n" + " \"error.count\":3,\n" + " \"origins.status\":{\n" + " \"200.count\":1,\n" + " \"500.count\":2\n" + " }\n" + " }\n" + " },\n" + " \"gauges.styx.mygauge.value\":123,\n" + " \"histograms\":{\n" + "\n" + " },\n" + " \"meters\":{\n" + "\n" + " },\n" + " \"timers\":{\n" + "\n" + " },\n" + " \"version\":\"") + "\\d+\\.\\d+\\.\\d+" + quote("\"\n" + "}"))); } |
### Question:
ServiceProviderHandler implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { return urlRouter.handle(request, context); } ServiceProviderHandler(StyxObjectStore<StyxObjectRecord<StyxService>> providerDatabase); @Override Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context); static ObjectMapper yamlMapper(); }### Answer:
@Test public void returnsAllProviders() throws IOException { StyxObjectStore<StyxObjectRecord<StyxService>> store = createTestStore(); ServiceProviderHandler handler = new ServiceProviderHandler(store); HttpRequest request = HttpRequest.get("/admin/service/providers").build(); HttpResponse response = Mono.from(handler.handle(request, requestContext())).block(); assertThat(response.status(), equalTo(OK)); List<StyxObjectDefinition> actualProviders = extractProviders(response.bodyAs(UTF_8)); assertThat(actualProviders.size(), equalTo(store.entrySet().size())); for (StyxObjectDefinition actual : actualProviders) { Optional<StyxObjectRecord<StyxService>> rec = store.get(actual.name()); assertTrue(rec.isPresent()); validateProvider(actual, rec.get()); } }
@Test public void returnsNoContentStatusWhenNoProvidersAvailable() { StyxObjectStore<StyxObjectRecord<StyxService>> empty = new StyxObjectStore<>(); ServiceProviderHandler handler = new ServiceProviderHandler(empty); HttpRequest request = HttpRequest.get("/admin/service/providers").build(); HttpResponse response = Mono.from(handler.handle(request, requestContext())).block(); assertThat(response.status(), equalTo(NO_CONTENT)); assertFalse(response.contentLength().isPresent()); }
@Test public void returnsNamedProvider() throws IOException { StyxObjectStore<StyxObjectRecord<StyxService>> store = createTestStore(); ServiceProviderHandler handler = new ServiceProviderHandler(store); HttpRequest request = HttpRequest.get("/admin/service/provider/object2").build(); HttpResponse response = Mono.from(handler.handle(request, requestContext())).block(); assertThat(response.status(), equalTo(OK)); StyxObjectDefinition actualProvider = deserialiseProvider(response.bodyAs(UTF_8)); assertThat(actualProvider, notNullValue()); assertThat(actualProvider.name(), equalTo("object2")); validateProvider(actualProvider, store.get("object2").get()); }
@Test public void returnsNotFoundStatusWhenNamedProviderNotFound() throws IOException { StyxObjectStore<StyxObjectRecord<StyxService>> store = createTestStore(); ServiceProviderHandler handler = new ServiceProviderHandler(store); HttpRequest request = HttpRequest.get("/admin/service/provider/nonexistent").build(); HttpResponse response = Mono.from(handler.handle(request, requestContext())).block(); assertThat(response.status(), equalTo(NOT_FOUND)); }
@Test public void returnsNotFoundStatusWithNonHandledUrl() { StyxObjectStore<StyxObjectRecord<StyxService>> empty = new StyxObjectStore<>(); ServiceProviderHandler handler = new ServiceProviderHandler(empty); HttpRequest request = HttpRequest.get("/not/my/url").build(); HttpResponse response = Mono.from(handler.handle(request, requestContext())).block(); assertThat(response.status(), equalTo(NOT_FOUND)); } |
### Question:
MetricsHandler implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { return this.urlMatcher.handle(request, context); } MetricsHandler(MetricRegistry metricRegistry, Optional<Duration> cacheExpiration); @Override Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context); }### Answer:
@Test public void respondsToRequestWithJsonResponse() { HttpResponse response = Mono.from(handler.handle(get("/admin/metrics").build(), requestContext())).block(); assertThat(response.status(), is(OK)); assertThat(response.contentType().get(), is(JSON_UTF_8.toString())); }
@Test public void exposesRegisteredMetrics() { metricRegistry.counter("foo").inc(); HttpResponse response = Mono.from(handler.handle(get("/admin/metrics").build(), requestContext())).block(); assertThat(response.bodyAs(UTF_8), matchesRegex(quote("{\"version\":\"") + "\\d+\\.\\d+\\.\\d+" + quote("\",\"gauges\":{},\"counters\":{\"foo\":{\"count\":1}},\"histograms\":{},\"meters\":{},\"timers\":{}}"))); }
@Test public void canRequestMetricsBeginningWithPrefix() { metricRegistry.counter("foo.bar").inc(1); metricRegistry.counter("foo.bar.baz").inc(1); metricRegistry.counter("foo.barx").inc(1); HttpResponse response = Mono.from(handler.handle(get("/admin/metrics/foo.bar").build(), requestContext())).block(); assertThat(response.bodyAs(UTF_8), is("{\"foo.bar\":{\"count\":1},\"foo.bar.baz\":{\"count\":1}}")); }
@Test public void ifNoMetricsMatchNameThen404NotFoundIsReturned() { HttpResponse response = Mono.from(handler.handle(get("/admin/metrics/foo.bar").build(), requestContext())).block(); assertThat(response.status(), is(NOT_FOUND)); }
@Test public void canSearchForTermWithinMetricName() { metricRegistry.counter("foo.bar.a").inc(1); metricRegistry.counter("foo.bar.b").inc(1); metricRegistry.counter("baz.bar.foo").inc(1); metricRegistry.counter("foo.baz.a").inc(1); HttpResponse response = Mono.from(handler.handle(get("/admin/metrics/?filter=bar").build(), requestContext())).block(); assertThat(response.status(), is(OK)); assertThat(response.bodyAs(UTF_8), is("{" + "\"baz.bar.foo\":{\"count\":1}," + "\"foo.bar.a\":{\"count\":1}," + "\"foo.bar.b\":{\"count\":1}" + "}")); }
@Test public void canRequestMetricsBeginningWithPrefixAndSearchForTermTogether() { metricRegistry.counter("foo.bar.a").inc(1); metricRegistry.counter("foo.bar.b").inc(1); metricRegistry.counter("baz.bar.foo").inc(1); metricRegistry.counter("foo.baz.a").inc(1); metricRegistry.counter("foo.baz.a.bar").inc(1); HttpResponse response = Mono.from(handler.handle(get("/admin/metrics/foo?filter=bar").build(), requestContext())).block(); assertThat(response.status(), is(OK)); assertThat(response.bodyAs(UTF_8), is("{" + "\"foo.bar.a\":{\"count\":1}," + "\"foo.bar.b\":{\"count\":1}," + "\"foo.baz.a.bar\":{\"count\":1}" + "}")); }
@Test public void searchReturnsEmptyJsonObjectWhenThereAreNoResults() { metricRegistry.counter("foo.bar.a").inc(1); metricRegistry.counter("foo.bar.b").inc(1); HttpResponse response = Mono.from(handler.handle(get("/admin/metrics/?filter=notpresent").build(), requestContext())).block(); assertThat(response.status(), is(OK)); assertThat(response.bodyAs(UTF_8), is("{}")); } |
### Question:
ProviderListHandler implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { String providerList = providerDb.entrySet().stream() .map(entry -> htmlForProvider(entry.getKey(), entry.getValue())) .collect(joining()); String html = String.format(HTML_TEMPLATE, TITLE, h2(TITLE) + providerList); return Eventual.of(response(OK) .body(html, UTF_8) .addHeader(CONTENT_TYPE, HTML_UTF_8.toString()) .build()); } ProviderListHandler(ObjectStore<? extends StyxObjectRecord<? extends StyxService>> providerDb); @Override Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context); }### Answer:
@Test public void showsEndpointsForAllConfiguredProviders() throws JsonProcessingException { JsonNode config = new ObjectMapper().readTree("{\"setting1\" : \"A\", \"setting2\" : \"A\"}"); StyxObjectStore<StyxObjectRecord<StyxService>> store = new StyxObjectStore<>(); store.insert("Service-A1", new StyxObjectRecord<>("ServiceA", new HashSet<>(), config, new SampleServiceA("Service-A-1"))); store.insert("Service-A2", new StyxObjectRecord<>("ServiceA", new HashSet<>(), config, new SampleServiceA("Service-A-2"))); store.insert("Service-B", new StyxObjectRecord<>("ServiceB", new HashSet<>(), config, new SampleServiceB("Service-B"))); ProviderListHandler handler = new ProviderListHandler(store); HttpResponse response = Mono.from(handler.handle(get("/").build(), requestContext())).block(); assertThat(response.status(), equalTo(OK)); assertThat(response.bodyAs(UTF_8), stringContainsInOrder( "Service-A1 (ServiceA)", "<a href=\"/admin/providers/Service-A1/status\">/admin/providers/Service-A1/status</a>", "Service-A2 (ServiceA)", "<a href=\"/admin/providers/Service-A2/status\">/admin/providers/Service-A2/status</a>", "Service-B (ServiceB)", "<a href=\"/admin/providers/Service-B/withslash/\">/admin/providers/Service-B/withslash/</a>", "<a href=\"/admin/providers/Service-B/noslash\">/admin/providers/Service-B/noslash</a>", "<a href=\"/admin/providers/Service-B/\">/admin/providers/Service-B/</a>" )); } |
### Question:
LoggingConfigurationHandler implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { return Eventual.of(generateResponse()); } LoggingConfigurationHandler(Resource logConfigLocation); @Override Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context); }### Answer:
@Test public void showsErrorMessageInContentIfLogConfigFileDoesNotExist() { StartupConfig startupConfig = newStartupConfigBuilder() .logbackConfigLocation("/foo/bar") .build(); LoggingConfigurationHandler handler = new LoggingConfigurationHandler(startupConfig.logConfigLocation()); HttpResponse response = Mono.from(handler.handle(get("/").build(), requestContext())).block(); assertThat(response.status(), is(OK)); assertThat(response.bodyAs(UTF_8), matchesRegex("Could not load resource=.*foo[\\\\/]bar'")); }
@Test public void showsLogConfigContent() throws IOException { StartupConfig startupConfig = newStartupConfigBuilder() .logbackConfigLocation(fixturesHome() + "/conf/environment/styx-config-test.yml") .build(); LoggingConfigurationHandler handler = new LoggingConfigurationHandler(startupConfig.logConfigLocation()); HttpResponse response = Mono.from(handler.handle(get("/").build(), requestContext())).block(); String expected = Resources.load(new ClasspathResource("conf/environment/styx-config-test.yml", LoggingConfigurationHandlerTest.class)); assertThat(response.status(), is(OK)); assertThat(response.bodyAs(UTF_8), is(expected)); } |
### Question:
OriginsReloadCommandHandler implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { return new Eventual<>(Flux.create(this::reload) .subscribeOn(Schedulers.fromExecutor(executor))); } OriginsReloadCommandHandler(Registry<BackendService> backendServicesRegistry); @Override Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context); }### Answer:
@Test public void returnsWithConfirmationWhenChangesArePerformed() { mockRegistryReload(completedFuture(reloaded("ok"))); HttpResponse response = Mono.from(handler.handle(get("/").build(), mock(HttpInterceptor.Context.class))).block(); assertThat(response.status(), is(OK)); assertThat(response.bodyAs(UTF_8), is("Origins reloaded successfully.\n")); }
@Test public void returnsWithInformationWhenChangesAreUnnecessary() { mockRegistryReload(completedFuture(unchanged("this test returns 'no meaningful changes'"))); HttpResponse response = Mono.from(handler.handle(get("/").build(), mock(HttpInterceptor.Context.class))).block(); assertThat(response.status(), is(OK)); assertThat(response.bodyAs(UTF_8), is("Origins were not reloaded because this test returns 'no meaningful changes'.\n")); }
@Test public void returnsWithInformationWhenJsonErrorOccursDuringReload() { mockRegistryReload(failedFuture(new RuntimeException(new JsonMappingException("simulated error")))); HttpResponse response = Mono.from(handler.handle(get("/").build(), mock(HttpInterceptor.Context.class))).block(); assertThat(response.status(), is(BAD_REQUEST)); assertThat(response.bodyAs(UTF_8), is(matchesRegex("There was an error processing your request. It has been logged \\(ID [0-9a-f-]+\\)\\.\n"))); }
@Test public void returnsWithInformationWhenErrorDuringReload() { mockRegistryReload(failedFuture(new RuntimeException(new RuntimeException("simulated error")))); HttpResponse response = Mono.from(handler.handle(get("/").build(), mock(HttpInterceptor.Context.class))).block(); assertThat(response.status(), is(INTERNAL_SERVER_ERROR)); assertThat(response.bodyAs(UTF_8), is(matchesRegex("There was an error processing your request. It has been logged \\(ID [0-9a-f-]+\\)\\.\n"))); } |
### Question:
DashboardData { @JsonProperty("server") public Server server() { return server; } DashboardData(MetricRegistry metrics, Registry<BackendService> backendServicesRegistry, String serverId, Version version, EventBus eventBus); @JsonProperty("server") Server server(); @JsonProperty("downstream") Downstream downstream(); @JsonProperty("publishTime") long publishTime(); }### Answer:
@Test public void providesServerId() { DashboardData dashboardData = newDashboardData("styx-prod1-presentation-01", "releaseTag", backendServicesRegistry); assertThat(dashboardData.server().id(), is("styx-prod1-presentation-01")); }
@Test public void providesVersion() { DashboardData dashboardData = newDashboardData("serverId", "STYX.0.4.283", backendServicesRegistry); assertThat(dashboardData.server().version(), is("0.4.283")); }
@Test public void providesUptime() { metricRegistry.register("jvm.uptime.formatted", gauge("1d 3h 2m")); assertThat(newDashboardData().server().uptime(), is("1d 3h 2m")); }
@Test public void providesStyxErrorResponseCodes() { metricRegistry.counter("styx.response.status.500").inc(111); metricRegistry.counter("styx.response.status.502").inc(222); Map<String, Integer> responses = newDashboardData().server().responses(); assertThat(responses.get("500"), is(111)); assertThat(responses.get("502"), is(222)); assertThat(responses.get("5xx"), is(333)); } |
### Question:
DashboardData { void unregister() { this.downstream.unregister(); } DashboardData(MetricRegistry metrics, Registry<BackendService> backendServicesRegistry, String serverId, Version version, EventBus eventBus); @JsonProperty("server") Server server(); @JsonProperty("downstream") Downstream downstream(); @JsonProperty("publishTime") long publishTime(); }### Answer:
@Test public void unsubscribesFromEventBus() { EventBus eventBus = mock(EventBus.class); MemoryBackedRegistry<BackendService> backendServicesRegistry = new MemoryBackedRegistry<>(); backendServicesRegistry.add(application("app", origin("app-01", "localhost", 9090))); backendServicesRegistry.add(application("test", origin("test-01", "localhost", 9090))); DashboardData dashbaord = new DashboardData(metricRegistry, backendServicesRegistry, "styx-prod1-presentation-01", new Version("releaseTag"), eventBus); verify(eventBus, times(4)).register(any(DashboardData.Origin.class)); dashbaord.unregister(); verify(eventBus, times(4)).unregister(any(DashboardData.Origin.class)); } |
### Question:
DashboardDataSupplier implements Supplier<DashboardData>, Registry.ChangeListener<BackendService> { @Override public DashboardData get() { return data; } DashboardDataSupplier(Registry<BackendService> backendServicesRegistry, Environment environment, StyxConfig styxConfig); @Override void onChange(Registry.Changes<BackendService> changes); @Override DashboardData get(); }### Answer:
@Test public void receivesBackendUpdates() { MemoryBackedRegistry<BackendService> registry = new MemoryBackedRegistry<>(); DashboardDataSupplier supplier = new DashboardDataSupplier(registry, environment, styxConfig); registry.add(backend("foo", origin("foo1"))); assertThat(supplier.get().downstream().firstBackend().id(), is("STYXPRES-foo")); registry.add(backend("bar", origin("bar1"))); assertThat(supplier.get().downstream().backendIds(), containsInAnyOrder("STYXPRES-foo", "STYXPRES-bar")); }
@Test public void originsHaveStatuses() throws JsonProcessingException { MemoryBackedRegistry<BackendService> registry = new MemoryBackedRegistry<>(); DashboardDataSupplier supplier = new DashboardDataSupplier(registry, environment, styxConfig); Origin foo1 = origin("foo1"); Origin foo2 = origin("foo2"); registry.add(backend("foo", foo1, foo2)); registry.add(backend("bar", origin("bar1"))); environment.eventBus().post(new OriginsSnapshot(id("foo"), pools(foo1), pools(foo2), pools())); DashboardData.Downstream downstream = supplier.get().downstream(); DashboardData.Backend fooBackend = downstream.backend("STYXPRES-foo"); assertThat(downstream.backendIds(), containsInAnyOrder("STYXPRES-foo", "STYXPRES-bar")); assertThat(fooBackend.statusesByOriginId(), is(equalTo(ImmutableMap.of("foo1", "active", "foo2", "inactive")))); assertThat(fooBackend.origin("foo1").status(), is("active")); environment.eventBus().post(new OriginsSnapshot(id("foo"), pools(), pools(foo1), pools(foo2))); fooBackend = supplier.get().downstream().backend("STYXPRES-foo"); assertThat(fooBackend.statusesByOriginId(), is(equalTo(ImmutableMap.of("foo1", "inactive", "foo2", "disabled")))); assertThat(fooBackend.origin("foo1").status(), is("inactive")); } |
### Question:
SimpleConverter implements Converter { @Override public <T> T convert(Object source, Class<T> targetType) { if (source == null) { return null; } if (targetType == Boolean.class || targetType == Boolean.TYPE) { @SuppressWarnings("unchecked") T t = (T) Boolean.valueOf(source.toString()); return t; } @SuppressWarnings("unchecked") T t = (T) parse(source.toString(), targetType); return t; } @Override T convert(Object source, Class<T> targetType); }### Answer:
@Test public void convertsBooleanValue() { assertThat(converter.convert("true", Boolean.TYPE), is(true)); assertThat(converter.convert("false", Boolean.TYPE), is(false)); }
@Test public void convertsIntegerValues() { assertThat(converter.convert("9000", Integer.TYPE), is(9000)); }
@Test public void convertsStringValue() { assertThat(converter.convert("9000", String.class), is("9000")); }
@Test public void convertsEnumValues() { assertThat(converter.convert("CLOSE", Status.class), is(Status.CLOSE)); assertThat(converter.convert("OPEN", Status.class), is(Status.OPEN)); }
@Test public void convertsArrayOfPrimitives() { String[] locales = converter.convert("UK,US,IT", String[].class); assertThat(asList(locales), contains("UK", "US", "IT")); }
@Test public void failsForUndefinedEnumValue() { assertThrows(ConversionException.class, () -> converter.convert("UDEFINED", Status.class)); }
@Test public void failsForUndefinedObject() { assertThrows(ConversionException.class, () -> converter.convert("UDEFINED", ConfigurationValue.class)); } |
### Question:
HttpHeaders implements Iterable<HttpHeader> { public Set<String> names() { return ImmutableSet.copyOf(nettyHeaders.names()); } private HttpHeaders(Builder builder); Set<String> names(); Optional<String> get(CharSequence name); List<String> getAll(CharSequence name); boolean contains(CharSequence name); @Override Iterator<HttpHeader> iterator(); void forEach(BiConsumer<String, String> consumer); Builder newBuilder(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void emptyHeadersHasEmptyNames() { HttpHeaders httpHeaders = new HttpHeaders.Builder().build(); assertThat(httpHeaders.names(), is(emptyIterable())); } |
### Question:
HttpHeaders implements Iterable<HttpHeader> { public boolean contains(CharSequence name) { return nettyHeaders.contains(name); } private HttpHeaders(Builder builder); Set<String> names(); Optional<String> get(CharSequence name); List<String> getAll(CharSequence name); boolean contains(CharSequence name); @Override Iterator<HttpHeader> iterator(); void forEach(BiConsumer<String, String> consumer); Builder newBuilder(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void checksWhetherHeadersExist() { assertThat(headers.contains("header1"), is(true)); assertThat(headers.contains("header2"), is(true)); assertThat(headers.contains("nonExistent"), is(false)); }
@Test public void setsHeaders() { HttpHeaders newHeaders = new HttpHeaders.Builder() .add("foo", "bar") .build(); HttpHeaders headers = new HttpHeaders.Builder(newHeaders) .build(); assertThat(headers, contains(header("foo", "bar"))); }
@Test public void removesNullValues() { HttpHeaders headers = new Builder() .add("header1", asList("val1", null, "val2")) .build(); assertThat(headers, contains(header("header1", "val1"), header("header1", "val2"))); } |
### Question:
HttpHeaders implements Iterable<HttpHeader> { public Optional<String> get(CharSequence name) { return Optional.ofNullable(nettyHeaders.get(name)); } private HttpHeaders(Builder builder); Set<String> names(); Optional<String> get(CharSequence name); List<String> getAll(CharSequence name); boolean contains(CharSequence name); @Override Iterator<HttpHeader> iterator(); void forEach(BiConsumer<String, String> consumer); Builder newBuilder(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void providesSingleHeaderValue() { assertThat(headers.get("header1").get(), is("val1")); }
@Test public void providesFirstHeaderValueWhenSeveralExist() { assertThat(headers.get("header2").get(), is("val2a")); }
@Test public void providesOptionalAbsentWhenNoSuchHeaderExists() { assertThat(headers.get("nonExistent"), isAbsent()); }
@Test public void setsDateHeaders() { Instant time = ZonedDateTime.of(2015, 9, 10, 12, 2, 28, 0, UTC).toInstant(); HttpHeaders headers = new HttpHeaders.Builder() .set("foo", time) .build(); assertThat(headers.get("foo"), isValue("Thu, 10 Sep 2015 12:02:28 GMT")); } |
### Question:
HttpHeaders implements Iterable<HttpHeader> { @Override public String toString() { return Iterables.toString(nettyHeaders); } private HttpHeaders(Builder builder); Set<String> names(); Optional<String> get(CharSequence name); List<String> getAll(CharSequence name); boolean contains(CharSequence name); @Override Iterator<HttpHeader> iterator(); void forEach(BiConsumer<String, String> consumer); Builder newBuilder(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void convertsHeadersToString() { assertThat(headers.toString(), is("[header1=val1, header2=val2a, header2=val2b]")); } |
### Question:
LiveHttpResponse implements LiveHttpMessage { public static Builder response() { return new Builder(); } LiveHttpResponse(Builder builder); static Builder response(); static Builder response(HttpResponseStatus status); static Builder response(HttpResponseStatus status, ByteStream body); @Override HttpHeaders headers(); @Override ByteStream body(); @Override HttpVersion version(); Transformer newBuilder(); HttpResponseStatus status(); boolean isRedirect(); Eventual<HttpResponse> aggregate(int maxContentBytes); Set<ResponseCookie> cookies(); Optional<ResponseCookie> cookie(String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void supportsCaseInsensitiveHeaderNames() { LiveHttpResponse response = response(OK).header("Content-Type", "text/plain").build(); assertThat(response.header("content-type"), isValue("text/plain")); }
@Test public void headerValuesAreCaseSensitive() { LiveHttpResponse response = response(OK).header("Content-Type", "TEXT/PLAIN").build(); assertThat(response.header("content-type"), not(isValue("text/plain"))); }
@Test public void shouldCreateAChunkedResponse() { assertThat(response().build().chunked(), is(false)); assertThat(response().setChunked().build().chunked(), is(true)); }
@Test public void rejectsMultipleContentLengthInSingleHeader() { assertThrows(IllegalArgumentException.class, () -> response() .addHeader(CONTENT_LENGTH, "15, 16") .ensureContentLengthIsValid() .build()); }
@Test public void rejectsMultipleContentLength() { assertThrows(IllegalArgumentException.class, () -> response() .addHeader(CONTENT_LENGTH, "15") .addHeader(CONTENT_LENGTH, "16") .ensureContentLengthIsValid() .build()); }
@Test public void rejectsInvalidContentLength() { assertThrows(IllegalArgumentException.class, () -> response() .addHeader(CONTENT_LENGTH, "foo") .ensureContentLengthIsValid() .build()); }
@Test public void ensuresContentLengthIsPositive() { Exception e = assertThrows(IllegalArgumentException.class, () -> response(OK) .header("Content-Length", -3) .build()); assertEquals("Invalid Content-Length found. -3", e.getMessage()); } |
### Question:
ServerCookieEncoder extends CookieEncoder { String encode(String name, String value) { return encode(new DefaultCookie(name, value)); } private ServerCookieEncoder(boolean strict); }### Answer:
@Test public void removesMaxAgeInFavourOfExpireIfDateIsInThePast() { String cookieValue = "hp_pos=\"\"; Domain=.dev-hotels.com; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/"; Cookie cookie = ClientCookieDecoder.LAX.decode(cookieValue); String encodedCookieValue = ServerCookieEncoder.LAX.encode(cookie); assertThat(encodedCookieValue, not(containsString("Max-Age=0"))); assertThat(encodedCookieValue, containsString("Expires=Thu, 01 Jan 1970 00:00")); }
@Test public void willNotModifyMaxAgeIfPositive() { String cookieValue = "hp_pos=\"\"; Domain=.dev-hotels.com; Max-Age=50; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/"; Cookie cookie = ClientCookieDecoder.LAX.decode(cookieValue); assertThat(cookie.maxAge(), is(50L)); assertThat(ServerCookieEncoder.LAX.encode(cookie), containsString("Max-Age=50")); }
@Test public void setValidSameSite() { DefaultCookie cookie = new DefaultCookie("key", "value"); cookie.setSameSite(SameSite.Lax); cookie.setDomain(".domain.com"); cookie.setMaxAge(50); assertThat(ServerCookieEncoder.LAX.encode(cookie), containsString("Lax")); } |
### Question:
ResponseCookie { private ResponseCookie(Builder builder) { if (builder.name == null || builder.name.isEmpty()) { throw new IllegalArgumentException(); } this.name = builder.name; this.value = builder.value; this.domain = builder.domain; this.maxAge = builder.maxAge; this.path = builder.path; this.httpOnly = builder.httpOnly; this.secure = builder.secure; this.sameSite = builder.sameSite; this.hashCode = hash(name, value, domain, maxAge, path, secure, httpOnly, sameSite); } private ResponseCookie(Builder builder); static ResponseCookie.Builder responseCookie(String name, String value); static Set<ResponseCookie> decode(List<String> headerValues); String name(); String value(); Optional<Long> maxAge(); Optional<String> path(); boolean httpOnly(); Optional<String> domain(); boolean secure(); Optional<SameSite> sameSite(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void acceptsOnlyNonEmptyName() { assertThrows(IllegalArgumentException.class, () -> responseCookie("", "value").build()); }
@Test public void acceptsOnlyNonNullName() { assertThrows(NullPointerException.class, () -> responseCookie(null, "value").build()); }
@Test public void acceptsOnlyNonNullValue() { assertThrows(NullPointerException.class, () -> responseCookie("name", null).build()); } |
### Question:
HttpHeader { public static HttpHeader header(String name, String... values) { if (values.length <= 0) { throw new IllegalArgumentException("must give at least one value"); } return new HttpHeader(requireNonNull(name), ImmutableList.copyOf(values)); } private HttpHeader(String name, List<String> values); static HttpHeader header(String name, String... values); String name(); String value(); Iterable<String> values(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); }### Answer:
@Test public void rejectsEmptyValuesList() { assertThrows(IllegalArgumentException.class, () -> header("name", new String[0])); }
@Test public void valuesCannotBeNull() { assertThrows(NullPointerException.class, () -> header("name", "value1", null, "value2")); } |
### Question:
Eventual implements Publisher<T> { public static <T> Eventual<T> from(CompletionStage<T> completionStage) { return fromMono(Mono.fromCompletionStage(completionStage)); } Eventual(Publisher<T> publisher); static Eventual<T> of(T value); static Eventual<T> from(CompletionStage<T> completionStage); static Eventual<T> error(Throwable error); Eventual<R> map(Function<? super T, ? extends R> transformation); Eventual<R> flatMap(Function<? super T, ? extends Eventual<? extends R>> transformation); Eventual<T> onError(Function<Throwable, ? extends Eventual<? extends T>> errorHandler); @Override void subscribe(Subscriber<? super T> subscriber); }### Answer:
@Test public void createFromPublisher() { String value = Mono.from(new Eventual<>(Flux.just("hello"))).block(); assertEquals(value, "hello"); }
@Test public void createFromCompletionStage() { CompletableFuture<String> future = new CompletableFuture<>(); Eventual<String> eventual = Eventual.from(future); StepVerifier.create(eventual) .thenRequest(1) .expectNextCount(0) .then(() -> future.complete("hello")) .expectNext("hello") .verifyComplete(); } |
### Question:
Eventual implements Publisher<T> { public static <T> Eventual<T> of(T value) { return fromMono(Mono.just(value)); } Eventual(Publisher<T> publisher); static Eventual<T> of(T value); static Eventual<T> from(CompletionStage<T> completionStage); static Eventual<T> error(Throwable error); Eventual<R> map(Function<? super T, ? extends R> transformation); Eventual<R> flatMap(Function<? super T, ? extends Eventual<? extends R>> transformation); Eventual<T> onError(Function<Throwable, ? extends Eventual<? extends T>> errorHandler); @Override void subscribe(Subscriber<? super T> subscriber); }### Answer:
@Test public void createFromValue() { StepVerifier.create(Eventual.of("x")) .expectNext("x") .verifyComplete(); } |
### Question:
Eventual implements Publisher<T> { public static <T> Eventual<T> error(Throwable error) { return fromMono(Mono.error(error)); } Eventual(Publisher<T> publisher); static Eventual<T> of(T value); static Eventual<T> from(CompletionStage<T> completionStage); static Eventual<T> error(Throwable error); Eventual<R> map(Function<? super T, ? extends R> transformation); Eventual<R> flatMap(Function<? super T, ? extends Eventual<? extends R>> transformation); Eventual<T> onError(Function<Throwable, ? extends Eventual<? extends T>> errorHandler); @Override void subscribe(Subscriber<? super T> subscriber); }### Answer:
@Test public void createFromError() { Eventual<String> eventual = Eventual.error(new JustATestException()); StepVerifier.create(eventual) .expectError(RuntimeException.class) .verify(); } |
### Question:
IoRetry { public static void tryTimes(int times, IOAction task, Consumer<IOException> errorHandler) throws UncheckedIOException, IllegalArgumentException { if (times < 1) { throw new IllegalArgumentException("The number of retries should be a positive integer. It was " + times); } int retries = 0; while (true) { try { task.run(); return; } catch (IOException e) { onError(errorHandler, e); if (++retries == times) { throw new UncheckedIOException( format("Operation failed after %d retries: %s", times, e.getMessage()), e); } } } } private IoRetry(); static void tryTimes(int times, IOAction task, Consumer<IOException> errorHandler); }### Answer:
@Test public void runOnceIfNoErrors() throws IOException { tryTimes(2, task, null); verify(task).run(); }
@Test public void retryUpToMaxTimesForIoException() throws IOException { doThrow(new IOException("Could not connect")).when(task).run(); try { tryTimes(3, task, (e) -> assertThat(e, is(instanceOf(IOException.class)))); fail("An exception should have been thrown"); } catch (UncheckedIOException e) { assertThat(e.getMessage(), is("Operation failed after 3 retries: Could not connect")); } verify(task, times(3)).run(); }
@Test public void retryOnlyOnceIfSingleError() throws IOException { doThrow(new IOException()).doNothing().when(task).run(); tryTimes(3, task, (e) -> assertThat(e, is(instanceOf(IOException.class)))); verify(task, times(2)).run(); }
@Test public void noRetriesForOtherExceptions() throws IOException { doThrow(new NullPointerException()).doNothing().when(task).run(); try { tryTimes(3, task, null); fail("An exception should have been thrown"); } catch (NullPointerException e) { verify(task, times(1)).run(); } }
@Test public void illegalArgumentExceptionAndNoAttemptsForInvalidArgument() throws IOException { doNothing().when(task).run(); try { tryTimes(0, task, null); fail("An exception should have been thrown"); } catch (IllegalArgumentException e) { verify(task, times(0)).run(); } } |
### Question:
Eventual implements Publisher<T> { public <R> Eventual<R> map(Function<? super T, ? extends R> transformation) { return fromMono(Mono.from(publisher).map(transformation)); } Eventual(Publisher<T> publisher); static Eventual<T> of(T value); static Eventual<T> from(CompletionStage<T> completionStage); static Eventual<T> error(Throwable error); Eventual<R> map(Function<? super T, ? extends R> transformation); Eventual<R> flatMap(Function<? super T, ? extends Eventual<? extends R>> transformation); Eventual<T> onError(Function<Throwable, ? extends Eventual<? extends T>> errorHandler); @Override void subscribe(Subscriber<? super T> subscriber); }### Answer:
@Test public void mapsValues() { StepVerifier.create(new Eventual<>(Flux.just("hello")).map(String::toUpperCase)) .expectNext("HELLO") .verifyComplete(); } |
### Question:
HttpMessageSupport { public static boolean chunked(HttpHeaders headers) { for (String value : headers.getAll(TRANSFER_ENCODING)) { if (value.equalsIgnoreCase(CHUNKED.toString())) { return true; } } return false; } private HttpMessageSupport(); static boolean chunked(HttpHeaders headers); static boolean keepAlive(HttpHeaders headers, HttpVersion version); }### Answer:
@Test public void chunkedReturnsTrueWhenChunkedTransferEncodingIsSet() { HttpHeaders headers = requestBuilder() .header(TRANSFER_ENCODING, CHUNKED) .build() .headers(); assertThat(chunked(headers), is(true)); HttpHeaders headers2 = requestBuilder() .header(TRANSFER_ENCODING, "foo") .addHeader(TRANSFER_ENCODING, CHUNKED) .addHeader(TRANSFER_ENCODING, "bar") .build() .headers(); assertThat(chunked(headers2), is(true)); }
@Test public void chunkedReturnsFalseWhenChunkedTransferEncodingIsNotSet() { HttpHeaders headers = requestBuilder() .header(TRANSFER_ENCODING, "foo") .build() .headers(); assertThat(chunked(headers), is(false)); }
@Test public void chunkedReturnsTrueWhenChunkedTransferEncodingIsAbsent() { HttpHeaders headers = requestBuilder().build().headers(); assertThat(chunked(headers), is(false)); } |
### Question:
HttpMessageSupport { public static boolean keepAlive(HttpHeaders headers, HttpVersion version) { Optional<String> connection = headers.get(CONNECTION); if (connection.isPresent()) { if (CLOSE.toString().equalsIgnoreCase(connection.get())) { return false; } if (KEEP_ALIVE.toString().equalsIgnoreCase(connection.get())) { return true; } } return version.isKeepAliveDefault(); } private HttpMessageSupport(); static boolean chunked(HttpHeaders headers); static boolean keepAlive(HttpHeaders headers, HttpVersion version); }### Answer:
@Test public void keepAliveReturnsTrueWhenHttpConnectionMustBeKeptAlive() { HttpHeaders connectionHeaderAbsent = requestBuilder().build().headers(); HttpHeaders connectionHeaderClose = requestBuilder() .header(CONNECTION, CLOSE) .build() .headers(); HttpHeaders connectionHeaderKeepAlive = requestBuilder() .header(CONNECTION, KEEP_ALIVE) .build() .headers(); assertThat(keepAlive(connectionHeaderAbsent, HTTP_1_0), is(false)); assertThat(keepAlive(connectionHeaderAbsent, HTTP_1_1), is(true)); assertThat(keepAlive(connectionHeaderClose, HTTP_1_0), is(false)); assertThat(keepAlive(connectionHeaderClose, HTTP_1_1), is(false)); assertThat(keepAlive(connectionHeaderKeepAlive, HTTP_1_0), is(true)); assertThat(keepAlive(connectionHeaderKeepAlive, HTTP_1_1), is(true)); } |
### Question:
LiveHttpRequest implements LiveHttpMessage { public static Builder get(String uri) { return new Builder(GET, uri); } LiveHttpRequest(Builder builder); static Builder get(String uri); static Builder head(String uri); static Builder post(String uri); static Builder delete(String uri); static Builder put(String uri); static Builder patch(String uri); static Builder post(String uri, ByteStream body); static Builder put(String uri, ByteStream body); static Builder patch(String uri, ByteStream body); @Override HttpVersion version(); @Override HttpHeaders headers(); @Override List<String> headers(CharSequence name); @Override ByteStream body(); Object id(); HttpMethod method(); Url url(); String path(); boolean keepAlive(); Optional<String> queryParam(String name); Iterable<String> queryParams(String name); Map<String, List<String>> queryParams(); Iterable<String> queryParamNames(); Transformer newBuilder(); Eventual<HttpRequest> aggregate(int maxContentBytes); Set<RequestCookie> cookies(); Optional<RequestCookie> cookie(String name); @Override String toString(); }### Answer:
@Test public void rejectsMultipleContentLengthInSingleHeader() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "15, 16") .build()); }
@Test public void rejectsMultipleContentLengthHeaders() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "15") .addHeader(CONTENT_LENGTH, "16") .build()); }
@Test public void rejectsInvalidContentLength() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "foo") .build()); }
@Test public void setsHostHeaderFromAuthorityIfSet() { LiveHttpRequest request = get("http: assertThat(request.header(HOST), isValue("www.hotels.com")); } |
### Question:
LiveHttpRequest implements LiveHttpMessage { public static Builder post(String uri) { return new Builder(POST, uri); } LiveHttpRequest(Builder builder); static Builder get(String uri); static Builder head(String uri); static Builder post(String uri); static Builder delete(String uri); static Builder put(String uri); static Builder patch(String uri); static Builder post(String uri, ByteStream body); static Builder put(String uri, ByteStream body); static Builder patch(String uri, ByteStream body); @Override HttpVersion version(); @Override HttpHeaders headers(); @Override List<String> headers(CharSequence name); @Override ByteStream body(); Object id(); HttpMethod method(); Url url(); String path(); boolean keepAlive(); Optional<String> queryParam(String name); Iterable<String> queryParams(String name); Map<String, List<String>> queryParams(); Iterable<String> queryParamNames(); Transformer newBuilder(); Eventual<HttpRequest> aggregate(int maxContentBytes); Set<RequestCookie> cookies(); Optional<RequestCookie> cookie(String name); @Override String toString(); }### Answer:
@Test public void ensuresContentLengthIsPositive() { Exception e = assertThrows(IllegalArgumentException.class, () -> LiveHttpRequest.post("/y") .header("Content-Length", -3) .build()); assertEquals("Invalid Content-Length found. -3", e.getMessage()); } |
### Question:
HttpRequest implements HttpMessage { public static Builder get(String uri) { return new Builder(GET, uri); } HttpRequest(Builder builder); static Builder get(String uri); static Builder head(String uri); static Builder post(String uri); static Builder delete(String uri); static Builder put(String uri); static Builder patch(String uri); @Override HttpVersion version(); @Override HttpHeaders headers(); @Override List<String> headers(CharSequence name); @Override byte[] body(); @Override String bodyAs(Charset charset); Object id(); HttpMethod method(); Url url(); String path(); boolean keepAlive(); Optional<String> queryParam(String name); Iterable<String> queryParams(String name); Map<String, List<String>> queryParams(); Iterable<String> queryParamNames(); Builder newBuilder(); LiveHttpRequest stream(); Set<RequestCookie> cookies(); Optional<RequestCookie> cookie(String name); @Override String toString(); }### Answer:
@Test public void rejectsMultipleContentLengthInSingleHeader() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "15, 16") .build()); }
@Test public void rejectsMultipleContentLengthHeaders() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "15") .addHeader(CONTENT_LENGTH, "16") .build()); }
@Test public void rejectsInvalidContentLength() { assertThrows(IllegalArgumentException.class, () -> get("/foo") .addHeader(CONTENT_LENGTH, "foo") .build()); }
@Test public void setsHostHeaderFromAuthorityIfSet() { HttpRequest request = get("http: assertThat(request.header(HOST), isValue("www.hotels.com")); } |
### Question:
HttpRequest implements HttpMessage { public static Builder post(String uri) { return new Builder(POST, uri); } HttpRequest(Builder builder); static Builder get(String uri); static Builder head(String uri); static Builder post(String uri); static Builder delete(String uri); static Builder put(String uri); static Builder patch(String uri); @Override HttpVersion version(); @Override HttpHeaders headers(); @Override List<String> headers(CharSequence name); @Override byte[] body(); @Override String bodyAs(Charset charset); Object id(); HttpMethod method(); Url url(); String path(); boolean keepAlive(); Optional<String> queryParam(String name); Iterable<String> queryParams(String name); Map<String, List<String>> queryParams(); Iterable<String> queryParamNames(); Builder newBuilder(); LiveHttpRequest stream(); Set<RequestCookie> cookies(); Optional<RequestCookie> cookie(String name); @Override String toString(); }### Answer:
@Test public void ensuresContentLengthIsPositive() { Exception e = assertThrows(IllegalArgumentException.class, () -> HttpRequest.post("/y") .header("Content-Length", -3) .build()); assertEquals("Invalid Content-Length found. -3", e.getMessage()); } |
### Question:
RewriteConfig implements RewriteRule { @Override public Optional<String> rewrite(String originalUri) { Matcher matcher = compiledUrlPattern.matcher(originalUri); if (matcher.matches()) { return Optional.of(preprocessedReplacement.substitute(matcher)); } return Optional.empty(); } RewriteConfig(String urlPattern, String replacement); String urlPattern(); String replacement(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override Optional<String> rewrite(String originalUri); }### Answer:
@Test public void testSubstitutions() { String urlPattern = "\\/foo\\/(a|b|c)(\\/.*)?"; RewriteConfig config = new RewriteConfig(urlPattern, "/bar/$1$2"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("/bar/b/something")); config = new RewriteConfig(urlPattern, "/bar/$1/x$2"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("/bar/b/x/something")); config = new RewriteConfig(urlPattern, "/bar/$1/x$2/y"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("/bar/b/x/something/y")); config = new RewriteConfig(urlPattern, "$1/x$2/y"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("b/x/something/y")); config = new RewriteConfig(urlPattern, "$1$2/y"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("b/something/y")); config = new RewriteConfig(urlPattern, "$1$2"); assertThat(config.rewrite("/foo/b/something").get(), CoreMatchers.equalTo("b/something")); } |
### Question:
AbstractStyxService implements StyxService { @Override public Map<String, HttpHandler> adminInterfaceHandlers() { return ImmutableMap.of("status", (request, context) -> Eventual.of( response(OK) .addHeader(CONTENT_TYPE, APPLICATION_JSON) .body(format("{ name: \"%s\" status: \"%s\" }", name, status), UTF_8) .build() .stream())); } AbstractStyxService(String name); StyxServiceStatus status(); @Override CompletableFuture<Void> start(); @Override CompletableFuture<Void> stop(); @Override Map<String, HttpHandler> adminInterfaceHandlers(); String serviceName(); }### Answer:
@Test public void exposesNameAndStatusViaAdminInterface() throws ExecutionException, InterruptedException { DerivedStyxService service = new DerivedStyxService("derived-service", new CompletableFuture<>()); HttpResponse response = Mono.from(service.adminInterfaceHandlers().get("status").handle(get, MOCK_CONTEXT) .flatMap(r -> r.aggregate(1024))).block(); assertThat(response.bodyAs(UTF_8), is("{ name: \"derived-service\" status: \"CREATED\" }")); } |
### Question:
HttpResponse implements HttpMessage { public static Builder response() { return new Builder(); } private HttpResponse(Builder builder); static Builder response(); static Builder response(HttpResponseStatus status); @Override Optional<String> header(CharSequence name); @Override List<String> headers(CharSequence name); @Override HttpHeaders headers(); @Override byte[] body(); @Override String bodyAs(Charset charset); @Override HttpVersion version(); Builder newBuilder(); HttpResponseStatus status(); boolean isRedirect(); LiveHttpResponse stream(); Set<ResponseCookie> cookies(); Optional<ResponseCookie> cookie(String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldCreateAChunkedResponse() { assertThat(HttpResponse.response().build().chunked(), is(false)); assertThat(HttpResponse.response().setChunked().build().chunked(), is(true)); }
@Test public void rejectsMultipleContentLengthInSingleHeader() { assertThrows(IllegalArgumentException.class, () -> HttpResponse.response() .addHeader(CONTENT_LENGTH, "15, 16") .ensureContentLengthIsValid() .build()); }
@Test public void rejectsMultipleContentLength() { assertThrows(IllegalArgumentException.class, () -> HttpResponse.response() .addHeader(CONTENT_LENGTH, "15") .addHeader(CONTENT_LENGTH, "16") .ensureContentLengthIsValid() .build()); }
@Test public void rejectsInvalidContentLength() { assertThrows(IllegalArgumentException.class, () -> HttpResponse.response() .addHeader(CONTENT_LENGTH, "foo") .ensureContentLengthIsValid() .build()); } |
### Question:
GraphiteReporter extends ScheduledReporter { @Override public void stop() { try { super.stop(); } finally { try { graphite.close(); } catch (IOException e) { LOGGER.debug("Error disconnecting from Graphite", e); } } } private GraphiteReporter(MetricRegistry registry,
GraphiteSender graphite,
Clock clock,
String prefix,
TimeUnit rateUnit,
TimeUnit durationUnit,
MetricFilter filter); static Builder forRegistry(MetricRegistry registry); @Override void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String, Timer> timers); @Override void stop(); }### Answer:
@Test public void closesConnectionOnReporterStop() throws Exception { reporter.stop(); verify(graphite).close(); verifyNoMoreInteractions(graphite); } |
### Question:
UrlQuery { String encodedQuery() { return encodedQuery; } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void providesEncodedQuery() { assertThat(query.encodedQuery(), is("foo=alpha&bar=beta&foo=gamma")); } |
### Question:
UrlQuery { Iterable<String> parameterNames() { return parameters().stream().map(Parameter::key).distinct().collect(toList()); } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void providesParameterNames() { assertThat(query.parameterNames(), contains("foo", "bar")); } |
### Question:
UrlQuery { Optional<String> parameterValue(String name) { return stream(parameterValues(name).spliterator(), false).findFirst(); } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void providesValueByKey() { assertThat(query.parameterValue("foo"), isValue("alpha")); assertThat(query.parameterValue("bar"), isValue("beta")); assertThat(query.parameterValue("no_such_key"), isAbsent()); } |
### Question:
UrlQuery { Iterable<String> parameterValues(String name) { return parameters().stream() .filter(parameter -> parameter.key.equals(name)) .map(Parameter::value) .collect(toList()); } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void providesValuesByKey() { assertThat(query.parameterValues("foo"), contains("alpha", "gamma")); assertThat(query.parameterValues("bar"), contains("beta")); assertThat(query.parameterValues("no_such_key"), is(emptyIterable())); } |
### Question:
UrlQuery { List<Parameter> parameters() { return parameters; } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void providesFullParameters() { assertThat(query.parameters(), contains( new Parameter("foo", "alpha"), new Parameter("bar", "beta"), new Parameter("foo", "gamma") )); } |
### Question:
UrlQuery { Builder newBuilder() { return new Builder(this); } private UrlQuery(List<Parameter> parameters); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void buildsNewQueryFromExistingQuery() { assertThat(query.newBuilder().build(), equalTo(query)); } |
### Question:
RequestCookie { private RequestCookie(String name, String value) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("name cannot be null or empty"); } requireNonNull(value, "value cannot be null"); this.name = name; this.value = value; this.hashCode = Objects.hash(name, value); } private RequestCookie(String name, String value); static RequestCookie requestCookie(String name, String value); static Set<RequestCookie> decode(String headerValue); static String encode(Collection<RequestCookie> cookies); String name(); String value(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void acceptsOnlyNonEmptyName() { assertThrows(IllegalArgumentException.class, () -> requestCookie("", "value")); }
@Test public void acceptsOnlyNonNullName() { assertThrows(IllegalArgumentException.class, () -> requestCookie(null, "value")); }
@Test public void acceptsOnlyNonNullValue() { assertThrows(NullPointerException.class, () -> requestCookie("name", null)); } |
### Question:
RouteHandlerAdapter implements RoutingObject { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { return router.route(request, context) .map(handler -> handler.handle(request, context)) .orElseGet(() -> Eventual.error(new NoServiceConfiguredException(request.path()))); } RouteHandlerAdapter(HttpRouter router); @Override Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context); }### Answer:
@Test public void injectsToPipelineWhenRouteFound() { HttpHandler pipeline = mock(HttpHandler.class); when(pipeline.handle(any(LiveHttpRequest.class), any(HttpInterceptor.Context.class))).thenReturn(Eventual.of(respOk)); HttpRouter router = mock(HttpRouter.class); when(router.route(any(LiveHttpRequest.class), any(HttpInterceptor.Context.class))).thenReturn(Optional.of(pipeline)); LiveHttpResponse response = Mono.from(new RouteHandlerAdapter(router).handle(request, requestContext())).block(); assertThat(response.status(), is(OK)); } |
### Question:
Url implements Comparable<Url> { private Url(Builder builder) { this.scheme = builder.scheme; this.authority = builder.authority; this.path = builder.path; this.query = Optional.ofNullable(builder.queryBuilder).map(UrlQuery.Builder::build); this.fragment = builder.fragment; } private Url(Builder builder); String scheme(); String path(); Optional<String> fragment(); Optional<Authority> authority(); Optional<String> host(); boolean isSecure(); boolean isFullyQualified(); boolean isAbsolute(); boolean isRelative(); URL toURL(); URI toURI(); Optional<String> queryParam(String name); Iterable<String> queryParams(String name); Map<String, List<String>> queryParams(); Iterable<String> queryParamNames(); String encodedUri(); @Override String toString(); @Override int compareTo(Url other); @Override int hashCode(); @Override boolean equals(Object obj); Builder newBuilder(); }### Answer:
@Test public void unwiseCharsAreNotAccepted() throws Exception { String urlWithUnwiseChars = "/search.do?foo={&srsReport=Landing|AutoS|HOTEL|Hotel%20Il%20Duca%20D%27Este|0|0|0|2|1|2|284128&srsr=Landing|AutoS|HOTEL|Hotel%20Il%20Duca%20D%27Este|0|0|0|2|1|2|284128"; assertThrows(IllegalArgumentException.class, () -> url(urlWithUnwiseChars).build()); } |
### Question:
Requests { public static LiveHttpRequest doFinally(LiveHttpRequest request, Consumer<Optional<Throwable>> action) { return request.newBuilder() .body(it -> it.doOnEnd(action)) .build(); } private Requests(); static LiveHttpRequest doFinally(LiveHttpRequest request, Consumer<Optional<Throwable>> action); static LiveHttpResponse doFinally(LiveHttpResponse response, Consumer<Optional<Throwable>> action); static LiveHttpRequest doOnComplete(LiveHttpRequest request, Runnable action); static LiveHttpResponse doOnComplete(LiveHttpResponse response, Runnable action); static LiveHttpRequest doOnError(LiveHttpRequest request, Consumer<Throwable> action); static LiveHttpResponse doOnError(LiveHttpResponse response, Consumer<Throwable> action); static LiveHttpRequest doOnCancel(LiveHttpRequest request, Runnable action); static LiveHttpResponse doOnCancel(LiveHttpResponse response, Runnable action); }### Answer:
@Test public void requestDoFinallyActivatesWhenSuccessfullyCompleted() { Requests.doFinally(request, completed::set) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.complete(); assertThat(completed.get(), is(Optional.empty())); }
@Test public void responseDoFinallyActivatesWhenSuccessfullyCompleted() { Requests.doFinally(response, completed::set) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.complete(); assertThat(completed.get(), is(Optional.empty())); }
@Test public void requestDoFinallyActivatesWhenErrors() { RuntimeException cause = new RuntimeException("help!!"); Requests.doFinally(request, completed::set) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.error(cause); assertThat(completed.get(), is(Optional.of(cause))); }
@Test public void responseDoFinallyActivatesWhenErrors() { RuntimeException cause = new RuntimeException("help!!"); Requests.doFinally(response, completed::set) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.error(cause); assertThat(completed.get(), is(Optional.of(cause))); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.