method2testcases
stringlengths
118
6.63k
### Question: SensorInstanceProvider implements InsertSensorOfferingListener { public SensorConfigurationRepository getSensorConfigurationRepository() { return sensorConfigurationRepository; } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer: @Test public void testGetSensorConfigurationRepository() throws InternalServiceException { SensorInstanceProvider provider = new SensorInstanceProvider(); assertNull(provider.getSensorConfigurationRepository()); setEmptyInMemoryRepositories(provider); assertNotNull(provider.getSensorConfigurationRepository()); }
### Question: XmlValidationDelegate implements RequestDelegationHandler { protected void validateRequiredVersionParameter(XmlObject requestDocument) throws OwsException { XmlCursor xmlCursor = requestDocument.newCursor(); xmlCursor.toFirstChild(); if (moveToAttribute(xmlCursor, "version")) { service.validateVersionParameter(xmlCursor.getTextValue()); } } XmlValidationDelegate(XmlDelegate toDecorate); XmlObject delegate(); }### Answer: @Test(expected = MissingParameterValueException.class) public void testMissingVersionParameterInRequest() throws Exception { XmlObject submitDocument = getRequest(REQUEST_MISSING_VERSION); validatingDelegate.validateRequiredVersionParameter(submitDocument); } @Test(expected = InvalidParameterValueException.class) public void testInvalidVersionParameterInRequest() throws Exception { XmlObject submitDocument = getRequest(REQUEST_INVALID_VERSION); validatingDelegate.validateRequiredVersionParameter(submitDocument); }
### Question: SensorInstanceProvider implements InsertSensorOfferingListener { public void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository) throws InternalServiceException { this.sensorConfigurationRepository = sensorConfigurationRepository; } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer: @Test public void testSetSensorConfigurationRepository() throws InternalServiceException { SensorInstanceProvider provider = new SensorInstanceProvider(); SensorConfigurationRepository repository = new InMemorySensorConfigurationRepository(); provider.setSensorConfigurationRepository(repository); assertEquals(repository, provider.getSensorConfigurationRepository()); }
### Question: SensorInstanceProvider implements InsertSensorOfferingListener { public SensorTaskRepository getSensorTaskRepository() { return sensorTaskRepository; } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer: @Test public void testGetSensorTaskRepository() throws InternalServiceException { SensorInstanceProvider provider = new SensorInstanceProvider(); assertNull(provider.getSensorTaskRepository()); setEmptyInMemoryRepositories(provider); assertNotNull(provider.getSensorTaskRepository()); }
### Question: SensorInstanceProvider implements InsertSensorOfferingListener { public void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository) { this.sensorTaskRepository = sensorTaskRepository; } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer: @Test public void testSetSensorTaskRepository() { SensorInstanceProvider provider = new SensorInstanceProvider(); SensorTaskRepository repository = new InMemorySensorTaskRepository(); provider.setSensorTaskRepository(repository); assertEquals(repository, provider.getSensorTaskRepository()); }
### Question: SensorInstanceProvider implements InsertSensorOfferingListener { public void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent) throws InternalServiceException { InsertSensorOfferingDocument insertSensorOfferingDocument = insertSensorOfferingEvent.getInsertSensorOffering(); InsertSensorOffering insertSensorOffering = insertSensorOfferingDocument.getInsertSensorOffering(); SensorOfferingType sensorOffering = createFromInsertSensorOffering(insertSensorOffering); SensorConfiguration sensorConfiguration = createSensorConfiguration(insertSensorOffering, sensorOffering); if (isSensorExisting(insertSensorOffering.getSensorInstanceData())) { SensorPlugin sensorPlugin = getSensorForProcedure(sensorOffering.getProcedure()); sensorPlugin.mergeSensorConfigurations(sensorConfiguration); sensorConfigurationRepository.saveOrUpdateSensorConfiguration(sensorConfiguration); } else { checkMandatoryContentForNewSensorOffering(insertSensorOffering); sensorInstances.add(initSensorInstance(sensorConfiguration)); sensorConfigurationRepository.storeNewSensorConfiguration(sensorConfiguration); } } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer: @Test public void testHandleInsertSensorOffering() throws InternalServiceException { InsertSensorOfferingEvent event = new InsertSensorOfferingEvent(insertSensorOffering); assertCorrectInsertOfferingHandling(event); assertCorrectSensorConfigurationHandling(); }
### Question: SpsOperator { protected SensorTask getSensorTask(String sensorTaskId) throws OwsException { if (!sensorInstanceProvider.containsTaskWith(sensorTaskId)) { handleInvalidParameter("task", sensorTaskId); } return sensorInstanceProvider.getTaskForTaskId(sensorTaskId); } SensorPlugin getSensorInstance(String procedure); SensorInstanceProvider getSensorInstanceProvider(); void setSensorInstanceProvider(SensorInstanceProvider sensorInstanceProvider); abstract boolean isSupportingExtensions(); }### Answer: @Test public void testGetSensorTask() { try { for (String taskId : tasks) { if (operatorUnderTest.getSensorTask(taskId) == null) { fail("null was returned instead of throwing IVPE!"); } } } catch (OwsException e) { fail("could not get sensor task"); } } @Test public void testGetSensorTaskThrowingException() { try { operatorUnderTest.getSensorTask(INVALID_TASK); fail("Invalid task id returnd valid non null task instance!"); } catch (InvalidParameterValueException e) { } catch (OwsException e) { fail("Invalid task id returnd valid non null task instance!"); } }
### Question: SpsOperator { public SensorPlugin getSensorInstance(String procedure) throws OwsException { if (!sensorInstanceProvider.containsSensorWith(procedure)) { handleInvalidParameter("procedure", procedure); } SensorPlugin sensorPlugin = sensorInstanceProvider.getSensorForProcedure(procedure); return NonBlockingTaskingDecorator.enableNonBlockingTasking(sensorPlugin); } SensorPlugin getSensorInstance(String procedure); SensorInstanceProvider getSensorInstanceProvider(); void setSensorInstanceProvider(SensorInstanceProvider sensorInstanceProvider); abstract boolean isSupportingExtensions(); }### Answer: @Test public void testGetSensorInstanceFor() { try { for (String procedure : procedures) { if (operatorUnderTest.getSensorInstance(procedure) == null) { fail("null was returned instead of throwing IVPE!"); } } } catch (OwsException e) { fail("Procedure was unknown!"); } } @Test public void testGetSensorInstanceForThrowingException() { try { operatorUnderTest.getSensorInstance(INVALID_PROCEDURE); fail("Invalid procedure returnd valid non null instance!"); } catch (InvalidParameterValueException e) { } catch (OwsException e) { } }
### Question: XmlValidationDelegate implements RequestDelegationHandler { protected boolean isGetCapabilitiesRequest(XmlObject request) { XmlCursor xmlCursor = request.newCursor(); xmlCursor.toFirstChild(); String operationName = xmlCursor.getName().getLocalPart(); return operationName.equalsIgnoreCase("GetCapabilities"); } XmlValidationDelegate(XmlDelegate toDecorate); XmlObject delegate(); }### Answer: @Test public void testIsGetCapabilitiesRequest() throws XmlException, IOException { XmlObject getCapabilities = getRequest(REQUEST_GET_CAPABILITIES); assertTrue(validatingDelegate.isGetCapabilitiesRequest(getCapabilities)); }
### Question: XmlValidationDelegate implements RequestDelegationHandler { protected void assureCorrectServiceAndVersionRequestParameters(XmlObject request) throws OwsException { if (!isGetCapabilitiesRequest(request)) { validateRequiredServiceParameter(request); validateRequiredVersionParameter(request); } else { service.validateGetCapabilitiesParameters((GetCapabilitiesDocument) request); } } XmlValidationDelegate(XmlDelegate toDecorate); XmlObject delegate(); }### Answer: @Test(expected = MissingParameterValueException.class) public void testMissingServiceInGetCapabilitiesRequest() throws XmlException, IOException, OwsException { XmlObject getCapabilities = getRequest(REQUEST_GET_CAPABILITIES_MISSING_SERVICE); validatingDelegate.assureCorrectServiceAndVersionRequestParameters(getCapabilities); }
### Question: SensorTask { public String getTaskStatusAsString() { return taskStatus != null ? taskStatus.toString() : null; } SensorTask(); SensorTask(String taskId, String procedure); String getTaskId(); Calendar getCalendarInstance(); void setUpdateTime(Calendar calendar); Calendar getUpdateTime(); String getFormattedUpdateTime(DateFormat formatter); String getUpdateTimeFormattedAsIso8601(); void setRequestStatus(TaskingRequestStatus requestStatus); void setRequestStatusAsString(String requestStatus); TaskingRequestStatus getRequestStatus(); String getRequestStatusAsString(); Calendar getEstimatedToC(); void setEstimatedToC(Calendar estimatedToC); double getPercentCompletion(); void setPercentCompletion(double percentCompletion); String getProcedure(); void clearStatusMessages(); void addStatusMessage(String message); void setStatusMessages(List<String> statusMessages); List<String> getStatusMessages(); void setTaskStatus(SensorTaskStatus taskStatus); void setTaskStatusAsString(String taskStatus); String getFormattedEstimatedToC(DateFormat formatter); String getEstimatedToCFormattedAsIso8601(); SensorTaskStatus getTaskStatus(); String getTaskStatusAsString(); ParameterDataType getParameterData(); String getParameterDataAsString(); void setParameterData(ParameterDataType parameterData); void setParameterDataAsString(String parameterData); String getEvent(); TaskType getTask(); @Deprecated StatusReportType generateStatusReport(); boolean isExpired(); boolean isFinished(); boolean isAccepted(); boolean isExecuting(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testGetTaskStatusAsString() { validTask.setTaskStatus(SensorTaskStatus.INEXECUTION); assertEquals(SensorTaskStatus.INEXECUTION.toString(), validTask.getTaskStatusAsString()); }
### Question: StatusReportGenerator { public static StatusReportGenerator createFor(SensorTask sensorTask) { return new StatusReportGenerator(sensorTask); } private StatusReportGenerator(SensorTask sensorTask); static StatusReportGenerator createFor(SensorTask sensorTask); StatusReportType generateWithTaskingParameters(); StatusReportType generateWithoutTaskingParameters(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testIllegalCreation() { StatusReportGenerator.createFor(null); }
### Question: DynamicClassFactory { private Class<?> createClass(ClassPair classPair) { String className = generateClassName(classPair); String classStr = className.replaceAll("\\.", "/"); String keyClassType = Type.getDescriptor(classPair.keyClass); String valueClassType = Type.getDescriptor(classPair.valueClass); ClassWriter cw = new ClassWriter(0); cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, className, null, "java/lang/Object", new String[]{interfaceName}); AnnotationVisitor anno = cw.visitAnnotation(Type.getDescriptor(JsonPropertyOrder.class), true); AnnotationVisitor aa = anno.visitArray("value"); aa.visit("", "key"); aa.visit("", "value"); aa.visitEnd(); anno.visitEnd(); FieldVisitor keyField = cw.visitField(ACC_PRIVATE, "key", keyClassType, null, null); keyField.visitEnd(); FieldVisitor valueField = cw.visitField(ACC_PRIVATE, "value", valueClassType, null, null); valueField.visitEnd(); MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitMaxs(2, 1); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false); mv.visitInsn(RETURN); mv.visitEnd(); addGetterSetter(classPair, className, classStr, keyClassType, valueClassType, cw); addKVPairMethods(classPair, className, classStr, keyClassType, valueClassType, cw); cw.visitEnd(); return defineClass(className, cw.toByteArray()); } private DynamicClassFactory(); synchronized Class<?> fetchOrCreatePairClass(ClassPair classPair); synchronized Class<?> fetchOrCreatePairClass(MapType mapType); void setKeyValue(Object obj, Object key, Object value); @SuppressWarnings({ "rawtypes", "unchecked" }) KeyValuePair getKeyValue(Object obj); static DynamicClassFactory INSTANCE; }### Answer: @Test public void testCreateClass() throws Exception { Class<?> c = DynamicClassFactory.INSTANCE.fetchOrCreatePairClass(new ClassPair(String.class, Date.class)); KVPair pair = (KVPair) c.newInstance(); assertEquals(1, c.getInterfaces().length); assertEquals(KVPair.class, c.getInterfaces()[0]); Annotation[] as = c.getAnnotations(); assertEquals(1, as.length); assertEquals(JsonPropertyOrder.class, as[0].annotationType()); assertEquals(String.class, c.getMethod("getKey").getReturnType()); assertEquals(Date.class, c.getMethod("getValue").getReturnType()); assertEquals(String.class, c.getMethod("setKey", String.class).getParameterTypes()[0]); assertEquals(Date.class, c.getMethod("setValue", Date.class).getParameterTypes()[0]); Date date = new Date(); pair.key("key"); pair.value(date); assertEquals("key", pair.key()); assertEquals(date, pair.value()); }
### Question: EnvironmentVariableConfigurationSource extends AbstractConfigurationSource { public EnvironmentVariableConfigurationSource(final int priority) { super(priority, "EnvironmentVariable"); } EnvironmentVariableConfigurationSource(final int priority); @Override Configuration configuration(); }### Answer: @Test public void testEnvironmentVariableConfigurationSource() { EnvironmentVariableConfigurationSource cs = new EnvironmentVariableConfigurationSource(0); assertEquals(cs.priority(), 0); }
### Question: EnvironmentVariableConfigurationSource extends AbstractConfigurationSource { @Override public Configuration configuration() { return _configuration; } EnvironmentVariableConfigurationSource(final int priority); @Override Configuration configuration(); }### Answer: @Test public void testConfiguration() { EnvironmentVariableConfigurationSource cs = new EnvironmentVariableConfigurationSource(0); assertNotNull(cs.configuration()); assertTrue(!Strings.isNullOrEmpty(cs.configuration().getPropertyValue("sun.management.compiler"))); }
### Question: DefaultProperty implements Property { @Override public String value() { return manager().getPropertyValue(key()); } DefaultProperty(ConfigurationManager manager, String key); @Override String key(); @Override String value(); @Override String toString(); }### Answer: @Test public void test() { MyConfigurationManager manager = new MyConfigurationManager(); MyProperty mp = (MyProperty) manager.getProperty(""); System.out.println(mp.value()); TypedProperty<Boolean> dbp = (DefaultTypedProperty<Boolean>) manager.getProperty("bool"); System.out.println(dbp.typedValue().booleanValue()); TypedProperty<Integer> dip = (DefaultTypedProperty<Integer>) manager.getProperty("int"); System.out.println(dip.typedValue().intValue()); TypedProperty<Long> dlp = (DefaultTypedProperty<Long>) manager.getProperty("long"); System.out.println(dlp.typedValue().longValue()); TypedProperty<List<String>> dlsp = (DefaultTypedProperty<List<String>>) manager.getProperty("list"); System.out.println(dlsp.typedValue()); TypedProperty<Map<String, String>> dmp = (DefaultTypedProperty<Map<String, String>>) manager.getProperty("map"); System.out.println(dmp.typedValue()); }
### Question: DefaultCachedProperty extends PropertyWrapper implements CachedProperty { @Override public String value() { return _value; } DefaultCachedProperty(Property property); @Override String value(); @Override void refresh(); }### Answer: @Test public void testValue() { MyProperty mp = new MyProperty("k1", "v1"); DefaultCachedProperty dcp = new DefaultCachedProperty(mp); assertEquals(dcp.value(), "v1"); }
### Question: DefaultCachedProperty extends PropertyWrapper implements CachedProperty { @Override public void refresh() { String before = value(); _value = super.value(); if (Objects.equal(before, _value)) return; if (_disableRefreshLog) return; _logger.info( String.format("Default cached property has been refreshed, key: %s, the value before refresh: %s, after refresh: %s", key(), before, _value)); } DefaultCachedProperty(Property property); @Override String value(); @Override void refresh(); }### Answer: @Test public void testRefresh() { MyProperty mp = new MyProperty("k1", "v1"); DefaultCachedProperty dcp = new DefaultCachedProperty(mp); dcp.refresh(); }
### Question: DefaultValues { public static boolean isDefault(Object value) { if (value == null) return true; if (value instanceof Number && ((Number)value).doubleValue() == 0.0) return true; return false; } private DefaultValues(); static boolean isDefault(Object value); }### Answer: @Test public void isDefaultTest() { Assert.assertTrue(DefaultValues.isDefault(0)); Assert.assertTrue(DefaultValues.isDefault(0.0)); Assert.assertTrue(DefaultValues.isDefault(null)); Assert.assertFalse(DefaultValues.isDefault(0.1)); Assert.assertFalse(DefaultValues.isDefault(1)); Assert.assertFalse(DefaultValues.isDefault(true)); Assert.assertFalse(DefaultValues.isDefault(false)); }
### Question: StringValues { public static String toString(Object value) { if (value == null) return null; return value.toString(); } private StringValues(); static String toString(Object value); static String toLowerCase(String value); static String toUpperCase(String value); static boolean isNullOrWhitespace(String value); static String intern(String value); static String trim(String s, char... chars); static String trimEnd(String s, char... chars); static String trimStart(String s, char... chars); static String trim(String s, String trimmed); static String trimStart(String s, String trimmed); static String trimEnd(String s, String trimmed); static String concatPathParts(String... pathParts); static KeyValuePair<String, String> toKeyValuePair(String s); static KeyValuePair<String, String> toKeyValuePair(String s, String separator); static String join(T[] data, char separator); static String join(T[] data, String separator); static String join(Collection<?> data, char separator); static String join(Collection<?> data, String separator); static boolean equals(String s1, String s2); static boolean equalsIgnoreCase(String s1, String s2); static final String EMPTY; static final String NULL; }### Answer: @Test public void toStringTest() { Object obj = null; String value = String.valueOf(obj); Assert.assertFalse(value == null); value = StringValues.toString(obj); Assert.assertTrue(value == null); }
### Question: PatternCorrector implements ValueCorrector<String> { @Override public String correct(String value) { if (Strings.isNullOrEmpty(value)) return null; Matcher matcher = _pattern.matcher(value); if (matcher.matches()) return value; else return null; } PatternCorrector(Pattern pattern); @Override String correct(String value); }### Answer: @Test public void ipTest() { PatternCorrector pc = new PatternCorrector(Patterns.IP_ADDRESS); assertNotNull(pc.correct("10.10.199.255")); assertNull(pc.correct("10.10.199.256")); assertNull(pc.correct("10.10.199.*")); assertNull(pc.correct("10.10.19")); assertNull(pc.correct("1.10.19.test")); assertNull(pc.correct(null)); assertNull(pc.correct("")); assertNull(pc.correct(" ")); } @Test public void mailTest() { PatternCorrector pc = new PatternCorrector(Patterns.MAIL_ADDRESS); assertNotNull(pc.correct("[email protected]")); assertNull(pc.correct("chennan")); assertNull(pc.correct("@")); assertNull(pc.correct("ctrip.com")); assertNull(pc.correct("@ctrip.com")); assertNull(pc.correct(null)); assertNull(pc.correct("")); assertNull(pc.correct(" ")); }
### Question: ServletContextConfigurationSource extends AbstractConfigurationSource { @Override public Configuration configuration() { return _configuration; } ServletContextConfigurationSource(final int priority, final ServletContext context); @Override Configuration configuration(); }### Answer: @Test public void testConfiguration() { ServletContextConfigurationSource sccs = new ServletContextConfigurationSource(1, new MyServletContext()); assertTrue(!Strings.isNullOrEmpty(sccs.configuration().getPropertyValue("env"))); }
### Question: DefaultConfigurationManager implements ConfigurationManager { protected void init(List<ConfigurationSource> sources) { if (CollectionValues.isNullOrEmpty(sources)) { _sources = EMPTY_CONFIGURATION_SOURCE_LIST; _logger.warn("sources is null or empty"); return; } _sources = new ArrayList<ConfigurationSource>(); for (ConfigurationSource source : sources) { if (source == null || source.configuration() == null) continue; _sources.add(source); } Collections.sort(_sources, ConfigurationSourceComparator.DEFAULT); StringBuffer sourcesInfo = new StringBuffer("The sorted sources info: { "); for (ConfigurationSource cs : sources()) { sourcesInfo.append(cs.sourceId()).append(": ").append(cs.priority()).append(", "); } sourcesInfo = new StringBuffer(sourcesInfo.substring(0, sourcesInfo.length() - 2)).append(" }"); _logger.info(sourcesInfo.toString()); } DefaultConfigurationManager(ConfigurationSource... sources); @Override String getPropertyValue(String key); @Override Property getProperty(String key); @Override Collection<ConfigurationSource> sources(); }### Answer: @Test public void testInit() { MyConfigurationSource mcs1 = new MyConfigurationSource(1); MyConfigurationSource mcs2 = new MyConfigurationSource(2); MyConfigurationSource mcs3 = new MyConfigurationSource(3); MyConfigurationSource mcs4 = new MyConfigurationSource(4); MyConfigurationSource mcs5 = new MyConfigurationSource(5); MyConfigurationSource[] testCSArray = {mcs4, mcs3, mcs5, mcs1, mcs2}; DefaultConfigurationManager manager = new DefaultConfigurationManager(testCSArray); for (ConfigurationSource cs : manager.sources()) { System.out.println("The source value: " + cs.configuration().getPropertyValue("key")); } System.out.println("The default first priority source value: " + manager.getPropertyValue("key")); }
### Question: ServletContextConfiguration implements Configuration { @Override public String getPropertyValue(String key) { if (StringValues.isNullOrWhitespace(key)) { _logger.warn("ServletContext key is null or empty!"); return null; } String value = _context.getInitParameter(key); return value; } ServletContextConfiguration(final ServletContext context); @Override String getPropertyValue(String key); }### Answer: @Test public void testGetPropertyValue() { ServletContextConfiguration scc = new ServletContextConfiguration(new MyServletContext()); assertEquals(scc.getPropertyValue("service-port"), "8090"); assertEquals(scc.getPropertyValue("env"), "fws"); }
### Question: DefaultLoadBalancer implements LoadBalancer { @Override public LoadBalancerRequestContext getRequestContext(LoadBalancerRequestConfig loadBalancerRequestConfig) { LoadBalancerRoute route = _loadBalancerContext.serverSourceFilter().getLoadBalancerRoute(loadBalancerRequestConfig); if (route == null) { LogUtil.error(_logger, "No matching route for \n" + loadBalancerRequestConfig, _loadBalancerContext.additionalInfo()); return null; } Server server = _loadBalancerContext.getLoadBalancerRule(route.getRouteId()).choose(route); return server == null ? null : new DefaultLoadBalancerRequestContext(server, _loadBalancerContext); } DefaultLoadBalancer(LoadBalancerContext loadBalancerContext); @Override LoadBalancerRequestContext getRequestContext(LoadBalancerRequestConfig loadBalancerRequestConfig); LoadBalancerContext getLoadBalancerContext(); }### Answer: @Test @Ignore public void loadBalancerTest () { final int serverCount = 10; final int threadCount = 4; final int repeatTimes = Integer.MAX_VALUE / (serverCount * threadCount) - (serverCount * threadCount); final String lbId = Thread.currentThread().getStackTrace()[1].getMethodName(); Assert.assertTrue(serverCount * repeatTimes * threadCount > Integer.MAX_VALUE / 2); final List<Server> servers = new ArrayList<>(); for (int i = 0; i < serverCount; i++) { servers.add(new Server.Builder().setServerId("server_" + i).build()); } final HashMap<Server, AtomicInteger> dataMap = new HashMap<>(); for (Server server : servers) { dataMap.put(server, new AtomicInteger(0)); } final DefaultDynamicServerSource serverSource = new DefaultDynamicServerSource(); LoadBalancerManager factory = LoadBalancerManager.getManager("soa", TestUtils.getLoadBalancerManagerConfig()); LoadBalancerConfig config = new LoadBalancerConfig.Builder().setServerSource(serverSource).build(); final LoadBalancer loadBalancer = factory.getLoadBalancer(lbId, config); serverSource.setServers(lbId, servers); Runnable runnable = new Runnable() { @Override public void run() { for (int i = 0; i < serverCount * repeatTimes; i++) { LoadBalancerRequestContext context = loadBalancer.getRequestContext(null); dataMap.get(context.getServer()).incrementAndGet(); } } }; Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { Thread thread = new Thread(runnable); thread.start(); threads[i] = thread; } Threads.wait(threads, 10); int average = threadCount * repeatTimes; int averageDelta = 10; for (int i = 0; i < serverCount; i++) { Server server = servers.get(i); int actual = dataMap.get(server).get(); System.out.println(server.toString() + " -> " + actual + ", " + average); } for (int i = 0; i < serverCount; i++) { int actual = dataMap.get(servers.get(i)).get(); Assert.assertTrue(servers.get(i).toString(), Math.abs(actual - average) < averageDelta); } }
### Question: RoundRobinRule implements LoadBalancerRule { public RoundRobinRule() { serverContexts = new ConcurrentHashMap<>(); roundRobinAlgorithm = new DefaultRoundRobinAlgorithm<>(); } RoundRobinRule(); @Override String getRuleId(); @Override String getDescription(); @Override Server choose(final LoadBalancerRoute route); }### Answer: @Test public void roundRobinRuleTest() { final int serverCount = 10; final int repeatTimes = 5; final int threadCount = 10; final String factoryId = "soa"; final String lbId = Thread.currentThread().getStackTrace()[1].getMethodName(); final LoadBalancerRequestConfig loadBalancerRequestConfig = new LoadBalancerRequestConfig(lbId); final List<Server> servers = new ArrayList<>(); final HashMap<Integer, AtomicInteger> indexCountMapping = new HashMap<>(); for (int i = 0; i < serverCount; i++) { HashMap<String, String> metadata = new HashMap<>(); metadata.put("Index", Integer.toString(i)); Server server = Server.newBuilder().setServerId("Server_" + i).setMetadata(metadata).build(); servers.add(server); indexCountMapping.put(i, new AtomicInteger(0)); } Ping ping = new Ping() { @Override public boolean isAlive(Server server) { return true; } }; LoadBalancerManager factory = LoadBalancerManager.getManager(factoryId, TestUtils.getLoadBalancerManagerConfig()); DefaultDynamicServerSource serverSource = DefaultDynamicServerSource.fromServers(lbId, servers); LoadBalancerConfig config = LoadBalancerConfig.newBuilder() .setPing(ping) .setRuleFactory(new Func<LoadBalancerRule>() { @Override public LoadBalancerRule execute() { return new RoundRobinRule(); } }) .setServerSource(serverSource) .build(); final LoadBalancer loadBalancer = factory.getLoadBalancer(lbId, config); Runnable runnable = new Runnable() { @Override public void run() { for (int i = 0; i < serverCount * repeatTimes; i++) { LoadBalancerRequestContext requestContext = loadBalancer.getRequestContext(loadBalancerRequestConfig); int index = Integer.parseInt(requestContext.getServer().getMetadata().get("Index")); indexCountMapping.get(index).incrementAndGet(); } } }; Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { Thread thread = new Thread(runnable); thread.start(); threads[i] = thread; } Threads.wait(threads, 200); int count = threadCount * repeatTimes; for (Server server : servers) { int index = Integer.parseInt(server.getMetadata().get("Index")); Assert.assertEquals(servers.toString(), count, indexCountMapping.get(index).intValue()); } }
### Question: SSJsonSerializer implements StreamSerializer, StringSerializer { @Override public <T> T deserialize(InputStream is, Class<T> clazz) { try { return _mapper.readValue(is, clazz); } catch (RuntimeException | Error ex) { throw ex; } catch (Exception ex) { throw new SerializationException(ex); } } SSJsonSerializer(); SSJsonSerializer(SSJsonSerializerConfig config); @Override String contentType(); @Override void serialize(OutputStream os, Object obj); @Override T deserialize(InputStream is, Class<T> clazz); @Override String serialize(Object obj); @Override T deserialize(String s, Class<T> clazz); static final SSJsonSerializer DEFAULT; }### Answer: @Test public void specificValueTest() { String specificJson = "{\"value\": \"abcd\1nefg\"}"; TestEntity testEntity = SSJsonSerializer.DEFAULT.deserialize(new ByteArrayInputStream(specificJson.getBytes()), TestEntity.class); assertNotNull(testEntity.getValue()); }
### Question: UnsafeIDGenerator { public static String timeBasedRandom(int length) { String date = DateValues.toString(new Date(), TIME_FORMAT, UTC_TIME_ZONE); if (length < TIME_BASED_RANDOM_MIN_LENGTH) length = TIME_BASED_RANDOM_MIN_LENGTH; return date + random(length - TIME_FORMAT.length()); } private UnsafeIDGenerator(); static String random(int length); static String timeBasedRandom(int length); static final int TIME_BASED_RANDOM_MIN_LENGTH; }### Answer: @Test public void timeBasedRandom() { int length = 20; String id = UnsafeIDGenerator.timeBasedRandom(length); Assert.assertEquals(id.length(), length); System.out.println(id); } @Test public void timeBasedRandomMinLength() { int length = 17; String id = UnsafeIDGenerator.timeBasedRandom(length); Assert.assertNotEquals(length, id.length()); Assert.assertEquals(UnsafeIDGenerator.TIME_BASED_RANDOM_MIN_LENGTH, id.length()); System.out.println(id); }
### Question: DefaultValueConfigurationSource extends AbstractConfigurationSource { public DefaultValueConfigurationSource(Map<String, String> keyValueMap) { super(Integer.MIN_VALUE, "DefaultValue"); _defaultValueConfiguration = new DefaultValueConfiguration(keyValueMap); } DefaultValueConfigurationSource(Map<String, String> keyValueMap); @Override DefaultValueConfiguration configuration(); }### Answer: @Test public void defaultValueConfigurationSourceTest() { DefaultValueConfigurationSource defaultValueConfigurationSource = getDefaultValueConfigurationSource(); MemoryConfigurationSource memoryConfigurationSource = getMemoryConfigurationSource(); ConfigurationManager manager = ConfigurationManagers.newManager(defaultValueConfigurationSource, memoryConfigurationSource); String planet = manager.getPropertyValue(planetKey); String country = manager.getPropertyValue(countryKey); String city = manager.getPropertyValue(cityKey); Assert.assertEquals(planetDefaultValue, planet); Assert.assertEquals(countryValue, country); Assert.assertEquals(cityValue, city); }
### Question: EnvironmentVariableConfiguration implements Configuration { @Override public String getPropertyValue(String key) { if (Strings.isNullOrEmpty(key)) { _logger.warn("ENV key is null or empty!"); return null; } String value = System.getProperty(key); return value; } @Override String getPropertyValue(String key); }### Answer: @Test public void testGetPropertyValue() { EnvironmentVariableConfiguration configuration = new EnvironmentVariableConfiguration(); assertNull(configuration.getPropertyValue(null)); assertNull(configuration.getPropertyValue("")); assertNull(configuration.getPropertyValue("test")); assertEquals("HotSpot 64-Bit Tiered Compilers", configuration.getPropertyValue("sun.management.compiler")); }
### Question: QueryResultDataPoint { public long getTimestamp() { return timestamp; } QueryResultDataPoint(); QueryResultDataPoint(long timestamp, double value); long getTimestamp(); void setTimestamp(long timestamp); double getValue(); void setValue(double value); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testGetTimestamp() throws Exception { QueryResultDataPoint subject = new QueryResultDataPoint(); Assert.assertEquals("Timestamp of uninitialized QueryResultDataPoint should be zero.", subject.getTimestamp(), 0); QueryResultDataPoint initializedSubject = new QueryResultDataPoint(initialTime, initialValue); Assert.assertEquals("Timestamp of initialized QueryResultDataPoint should match given value.", initializedSubject.getTimestamp(), initialTime); }
### Question: Utils { public static Map<String, Object> makeError(String errorMessage, String errorCause, String errorPart) { Map<String, Object> error = new HashMap<>(); error.put(ERROR_MESSAGE, errorMessage); error.put(ERROR_CAUSE, errorCause); error.put(ERROR_PART, errorPart); return error; } private Utils(); static Map<String, Object> makeError(String errorMessage, String errorCause, String errorPart); static Response getErrorResponse(String id, int status, String message, String context); static String createUuid(); static long parseDate(String value); static long parseDuration(String v); static String jsonStringFromObject(Object object); static ObjectMapper getObjectMapper(); static final String NOW; static final String DEFAULT_START_TIME; static final String DEFAULT_END_TIME; static final String NOT_SPECIFIED; static final String CLIENT_ID; static final String ERRORS; static final String ERROR_MESSAGE; static final String ERROR_CAUSE; static final String ERROR_PART; static final String START; static final String END; static final String COUNT; static final double DEFAULT_DOWNSAMPLE_MULTIPLIER; static final int DAYS_PER_YEAR; static final int DAYS_PER_WEEK; static final int HOURS_PER_DAY; static final int MINUTES_PER_HOUR; static final int SECONDS_PER_MINUTE; static final int SECONDS_PER_HOUR; static final int SECONDS_PER_DAY; static final int SECONDS_PER_WEEK; static final int SECONDS_PER_YEAR; }### Answer: @Test public void testMakeError() throws Exception { String errorMessageString = "Error String"; String errorCauseString = "Error Cause String"; String errorPartString = "Error Part String"; Map<String, Object> subject = Utils.makeError(errorMessageString, errorCauseString, errorPartString); Assert.assertEquals("Error Cause of created object should match input.", subject.get(Utils.ERROR_CAUSE), errorCauseString); Assert.assertEquals("Error Message of created object should match input.", subject.get(Utils.ERROR_MESSAGE), errorMessageString); Assert.assertEquals("Error Part of created object should match input.", subject.get(Utils.ERROR_PART), errorPartString); }
### Question: Utils { public static Response getErrorResponse(String id, int status, String message, String context) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.id = id; errorResponse.errorSource = context; errorResponse.errorMessage = message; String jsonErrorResponse = jsonStringFromObject(errorResponse); return Response.status(status) .entity(jsonErrorResponse) .build(); } private Utils(); static Map<String, Object> makeError(String errorMessage, String errorCause, String errorPart); static Response getErrorResponse(String id, int status, String message, String context); static String createUuid(); static long parseDate(String value); static long parseDuration(String v); static String jsonStringFromObject(Object object); static ObjectMapper getObjectMapper(); static final String NOW; static final String DEFAULT_START_TIME; static final String DEFAULT_END_TIME; static final String NOT_SPECIFIED; static final String CLIENT_ID; static final String ERRORS; static final String ERROR_MESSAGE; static final String ERROR_CAUSE; static final String ERROR_PART; static final String START; static final String END; static final String COUNT; static final double DEFAULT_DOWNSAMPLE_MULTIPLIER; static final int DAYS_PER_YEAR; static final int DAYS_PER_WEEK; static final int HOURS_PER_DAY; static final int MINUTES_PER_HOUR; static final int SECONDS_PER_MINUTE; static final int SECONDS_PER_HOUR; static final int SECONDS_PER_DAY; static final int SECONDS_PER_WEEK; static final int SECONDS_PER_YEAR; }### Answer: @Test public void testGetErrorResponse() throws Exception { String idString = "ID String"; int status = 404; String messageString = "Message String"; String contextString = "Context String"; Response subject = Utils.getErrorResponse(idString, status, messageString, contextString); Assert.assertEquals("Status of created response should match method argument", status, subject.getStatus()); String stringEntity = (String) subject.getEntity(); Assert.assertTrue("Error entity should contain message string.", stringEntity.contains(messageString)); Assert.assertTrue("Error entity should contain context string.", stringEntity.contains(contextString)); Assert.assertTrue("Error entity should contain ID string.", stringEntity.contains(idString)); }
### Question: Utils { public static String createUuid() { return UUID.randomUUID().toString(); } private Utils(); static Map<String, Object> makeError(String errorMessage, String errorCause, String errorPart); static Response getErrorResponse(String id, int status, String message, String context); static String createUuid(); static long parseDate(String value); static long parseDuration(String v); static String jsonStringFromObject(Object object); static ObjectMapper getObjectMapper(); static final String NOW; static final String DEFAULT_START_TIME; static final String DEFAULT_END_TIME; static final String NOT_SPECIFIED; static final String CLIENT_ID; static final String ERRORS; static final String ERROR_MESSAGE; static final String ERROR_CAUSE; static final String ERROR_PART; static final String START; static final String END; static final String COUNT; static final double DEFAULT_DOWNSAMPLE_MULTIPLIER; static final int DAYS_PER_YEAR; static final int DAYS_PER_WEEK; static final int HOURS_PER_DAY; static final int MINUTES_PER_HOUR; static final int SECONDS_PER_MINUTE; static final int SECONDS_PER_HOUR; static final int SECONDS_PER_DAY; static final int SECONDS_PER_WEEK; static final int SECONDS_PER_YEAR; }### Answer: @Test public void testCreateUuid() throws Exception { String subject = Utils.createUuid(); UUID testUUID = UUID.fromString(subject); String otherSubject = Utils.createUuid(); Assert.assertNotEquals("Two UUIDs generated by different calls should not be the same.", subject, otherSubject); }
### Question: Utils { public static long parseDuration(String v) { int idx; char last; if ((idx = v.indexOf('-')) > 0) { idx -= 1; last = v.charAt(idx); } else { idx = v.length() - 1; last = v.charAt(idx); } long period = 0; try { period = Long.parseLong(v.substring(0, idx)); } catch (NumberFormatException e) { return 0; } switch (last) { case 's': return period; case 'm': return period * SECONDS_PER_MINUTE; case 'h': return period * SECONDS_PER_HOUR; case 'd': return period * SECONDS_PER_DAY; case 'w': return period * SECONDS_PER_WEEK; case 'y': return period * SECONDS_PER_YEAR; } return 0; } private Utils(); static Map<String, Object> makeError(String errorMessage, String errorCause, String errorPart); static Response getErrorResponse(String id, int status, String message, String context); static String createUuid(); static long parseDate(String value); static long parseDuration(String v); static String jsonStringFromObject(Object object); static ObjectMapper getObjectMapper(); static final String NOW; static final String DEFAULT_START_TIME; static final String DEFAULT_END_TIME; static final String NOT_SPECIFIED; static final String CLIENT_ID; static final String ERRORS; static final String ERROR_MESSAGE; static final String ERROR_CAUSE; static final String ERROR_PART; static final String START; static final String END; static final String COUNT; static final double DEFAULT_DOWNSAMPLE_MULTIPLIER; static final int DAYS_PER_YEAR; static final int DAYS_PER_WEEK; static final int HOURS_PER_DAY; static final int MINUTES_PER_HOUR; static final int SECONDS_PER_MINUTE; static final int SECONDS_PER_HOUR; static final int SECONDS_PER_DAY; static final int SECONDS_PER_WEEK; static final int SECONDS_PER_YEAR; }### Answer: @Test public void testParseDuration() throws Exception { Assert.assertEquals(Utils.parseDuration("5s"), 5); Assert.assertEquals(Utils.parseDuration("5w"), 5 * Utils.SECONDS_PER_WEEK); Assert.assertEquals(Utils.parseDuration("2y"), 2 * Utils.SECONDS_PER_YEAR); Assert.assertEquals(Utils.parseDuration("5s-ago"), 5); Assert.assertEquals(Utils.parseDuration("5w-ago"), 5 * Utils.SECONDS_PER_WEEK); Assert.assertEquals(Utils.parseDuration("2y-ago"), 2 * Utils.SECONDS_PER_YEAR); Assert.assertEquals(Utils.parseDuration("arglefoo-ago"), 0); Assert.assertEquals(Utils.parseDuration("27t-ago"), 0); }
### Question: MetricResources { Optional<Map<String, List<String>>> getTags(Map<String, List<String>> tags) { if (configuration.isAuthEnabled()) { if (tags == null) { tags = Maps.newHashMap(); } String tenantId = getTenantId(); tags.put("zenoss_tenant_id", Lists.newArrayList(tenantId)); } return Optional.fromNullable(tags); } MetricResources(); MetricResources(AppConfiguration configuration, ZappSecurity security, MetricServiceAPI api); @POST @Timed @Consumes(MediaType.APPLICATION_JSON) Response query(PerformanceQuery query); @OPTIONS Response handleOptions(@HeaderParam("Access-Control-Request-Headers") String request); }### Answer: @Test public void testGetTagAuth() { when(configuration.isAuthEnabled()).thenReturn(true); Subject subject = mock( Subject.class); when(security.getSubject()).thenReturn( subject); PrincipalCollection collection = mock(PrincipalCollection.class); when(subject.getPrincipals()).thenReturn( collection); ZenossTenant tenant = ZenossTenant.get( "1"); when(collection.oneByType( ZenossTenant.class)).thenReturn(tenant); Map<String, List<String>> _tags = Maps.newHashMap(); _tags.put( "zenoss_tenant_id", Lists.newArrayList( "1")); Optional<Map<String, List<String>>> tags = Optional.fromNullable(_tags); assertEquals(tags, new MetricResources(configuration, security, api).getTags(null)); } @Test public void testGetTagNoAuth() { Optional<Map<String, List<String>>> tags = Optional.fromNullable(null); when(configuration.isAuthEnabled()).thenReturn(false); assertEquals(tags, new MetricResources(configuration, security, api).getTags(null)); }
### Question: MetricService implements MetricServiceAPI { public static List<MetricSpecification> metricFilter(List<? extends MetricSpecification> list) { List<MetricSpecification> result = new ArrayList<>(); if (list != null) { for (MetricSpecification spec : list) { if (spec.getMetric() != null) { result.add(spec); } else { log.debug("MetricFilter: filtering out metricSpecification {} - no metric value found.", spec.getNameOrMetric()); } } } return result; } MetricService(); static List<MetricSpecification> metricFilter(List<? extends MetricSpecification> list); static List<MetricSpecification> calculatedValueFilter( List<? extends MetricSpecification> list); SeriesQueryResult executeQuery(Optional<String> id, Optional<String> start, Optional<String> end, Optional<ReturnSet> returnset, Optional<Boolean> series, Optional<String> downsample, double downsampleMultiplier, Optional<Map<String, List<String>>> tags, List<MetricSpecification> metrics); @Override Response query(Optional<String> id, Optional<String> start, Optional<String> end, Optional<ReturnSet> returnset, Optional<Boolean> series, Optional<String> downsample, double downsampleMultiplier, Optional<Map<String, List<String>>> tags, List<MetricSpecification> metrics); @Override Response options(String request); static final String CLIENT_ID; static final String METRIC; static final String ID; static final String NOT_SPECIFIED; final ObjectMapper objectMapper; public JacksonResultsWriter jacksonResultsWriter; }### Answer: @Test public void testMetricFilter() throws Exception { MetricService victim = makeMetricService(); }
### Question: MetricService implements MetricServiceAPI { @Override public Response query(Optional<String> id, Optional<String> start, Optional<String> end, Optional<ReturnSet> returnset, Optional<Boolean> series, Optional<String> downsample, double downsampleMultiplier, Optional<Map<String, List<String>>> tags, List<MetricSpecification> metrics) { SeriesQueryResult queryResult = executeQuery(id, start, end, returnset, series, downsample, downsampleMultiplier, tags, metrics); return makeCORS(Response.ok().entity(queryResult), MediaType.APPLICATION_JSON); } MetricService(); static List<MetricSpecification> metricFilter(List<? extends MetricSpecification> list); static List<MetricSpecification> calculatedValueFilter( List<? extends MetricSpecification> list); SeriesQueryResult executeQuery(Optional<String> id, Optional<String> start, Optional<String> end, Optional<ReturnSet> returnset, Optional<Boolean> series, Optional<String> downsample, double downsampleMultiplier, Optional<Map<String, List<String>>> tags, List<MetricSpecification> metrics); @Override Response query(Optional<String> id, Optional<String> start, Optional<String> end, Optional<ReturnSet> returnset, Optional<Boolean> series, Optional<String> downsample, double downsampleMultiplier, Optional<Map<String, List<String>>> tags, List<MetricSpecification> metrics); @Override Response options(String request); static final String CLIENT_ID; static final String METRIC; static final String ID; static final String NOT_SPECIFIED; final ObjectMapper objectMapper; public JacksonResultsWriter jacksonResultsWriter; }### Answer: @Test public void testQuery() throws Exception { }
### Question: MetricService implements MetricServiceAPI { @Override public Response options(String request) { corsHeaders = request; return makeCORS(Response.ok(), request); } MetricService(); static List<MetricSpecification> metricFilter(List<? extends MetricSpecification> list); static List<MetricSpecification> calculatedValueFilter( List<? extends MetricSpecification> list); SeriesQueryResult executeQuery(Optional<String> id, Optional<String> start, Optional<String> end, Optional<ReturnSet> returnset, Optional<Boolean> series, Optional<String> downsample, double downsampleMultiplier, Optional<Map<String, List<String>>> tags, List<MetricSpecification> metrics); @Override Response query(Optional<String> id, Optional<String> start, Optional<String> end, Optional<ReturnSet> returnset, Optional<Boolean> series, Optional<String> downsample, double downsampleMultiplier, Optional<Map<String, List<String>>> tags, List<MetricSpecification> metrics); @Override Response options(String request); static final String CLIENT_ID; static final String METRIC; static final String ID; static final String NOT_SPECIFIED; final ObjectMapper objectMapper; public JacksonResultsWriter jacksonResultsWriter; }### Answer: @Test public void testOptions() throws Exception { }
### Question: QueryResultDataPoint { public void setTimestamp(long timestamp) { this.timestamp = timestamp; } QueryResultDataPoint(); QueryResultDataPoint(long timestamp, double value); long getTimestamp(); void setTimestamp(long timestamp); double getValue(); void setValue(double value); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testSetTimestamp() throws Exception { QueryResultDataPoint subject = new QueryResultDataPoint(); Assert.assertEquals("Timestamp of uninitialized QueryResultDataPoint should be zero.", subject.getTimestamp(), 0); subject.setTimestamp(initialTime); Assert.assertEquals("Timestamp of initialized QueryResultDataPoint should match given value.", subject.getTimestamp(), initialTime); }
### Question: MetricKey implements IHasShortcut { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetricKey metricKey = (MetricKey) o; if (metric != null ? !metric.equals(metricKey.metric) : metricKey.metric != null) return false; if (name != null ? !name.equals(metricKey.name) : metricKey.name != null) return false; if (tags != null ? !tags.equals(metricKey.tags) : metricKey.tags != null) return false; if (id != null ? !id.equals(metricKey.id) : metricKey.id != null) return false; return true; } @JsonProperty("id") String getId(); @JsonProperty("metric") String getMetric(); @JsonProperty("tags") Tags getTags(); @JsonProperty("name") String getName(); @Override boolean equals(Object o); @Override int hashCode(); static MetricKey fromValue(MetricSpecification spec); static MetricKey fromValue(String name, String metric, String tags); String toString(); @Override String getShortcut(); }### Answer: @Test public void testEquals() throws Exception { MetricKey victim = new MetricKey(); MetricKey other = new MetricKey(); assertTrue("Two newly created MetricKeys should be equal.", victim.equals(other)); assertFalse("Equal comparison with null should return false.", victim.equals(null)); assertFalse("Equal comparison with different class type should return false.", victim.equals(Integer.valueOf(3))); }
### Question: MetricKey implements IHasShortcut { @JsonProperty("metric") public String getMetric() { return metric; } @JsonProperty("id") String getId(); @JsonProperty("metric") String getMetric(); @JsonProperty("tags") Tags getTags(); @JsonProperty("name") String getName(); @Override boolean equals(Object o); @Override int hashCode(); static MetricKey fromValue(MetricSpecification spec); static MetricKey fromValue(String name, String metric, String tags); String toString(); @Override String getShortcut(); }### Answer: @Test public void testGetMetric() throws Exception { MetricKey victim = makeBasicMetricKey(); assertTrue("getMetric should return the metric value passed in.", Objects.equal(basicMetric, victim.getMetric())); }
### Question: MetricKey implements IHasShortcut { @JsonProperty("tags") public Tags getTags() { return tags; } @JsonProperty("id") String getId(); @JsonProperty("metric") String getMetric(); @JsonProperty("tags") Tags getTags(); @JsonProperty("name") String getName(); @Override boolean equals(Object o); @Override int hashCode(); static MetricKey fromValue(MetricSpecification spec); static MetricKey fromValue(String name, String metric, String tags); String toString(); @Override String getShortcut(); }### Answer: @Test public void testGetTags() throws Exception { String tagsValue = "Tag1=value1"; MetricKey victim = makeBasicMetricKey(); assertTrue("getTags should return the tag value passed in.", Objects.equal(basicTagValue, victim.getTags())); }
### Question: MetricKey implements IHasShortcut { @JsonProperty("name") public String getName() { return name; } @JsonProperty("id") String getId(); @JsonProperty("metric") String getMetric(); @JsonProperty("tags") Tags getTags(); @JsonProperty("name") String getName(); @Override boolean equals(Object o); @Override int hashCode(); static MetricKey fromValue(MetricSpecification spec); static MetricKey fromValue(String name, String metric, String tags); String toString(); @Override String getShortcut(); }### Answer: @Test public void testGetName() throws Exception { MetricKey victim = makeBasicMetricKey(); assertTrue("getName should return the metric value passed in.", Objects.equal(basicName, victim.getName())); }
### Question: MetricKey implements IHasShortcut { public static MetricKey fromValue(MetricSpecification spec) { MetricKey key = new MetricKey(); key.metric = spec.getMetricOrName(); key.name = spec.getNameOrMetric(); key.id = spec.getId(); if (spec.getTags() != null && spec.getTags().size() > 0) { key.tags = Tags.fromValue(spec.getTags()); } return key; } @JsonProperty("id") String getId(); @JsonProperty("metric") String getMetric(); @JsonProperty("tags") Tags getTags(); @JsonProperty("name") String getName(); @Override boolean equals(Object o); @Override int hashCode(); static MetricKey fromValue(MetricSpecification spec); static MetricKey fromValue(String name, String metric, String tags); String toString(); @Override String getShortcut(); }### Answer: @Test public void testFromValue() throws Exception { MetricKey victim = MetricKey.fromValue(basicName, basicMetric, basicTag); assertTrue("Name was not same as passed to fromValue().", Objects.equal(victim.getName(), basicName)); assertTrue("MetricName was not same as passed to fromValue().", Objects.equal(victim.getMetric(), basicMetric)); assertTrue("Tags value was not same as passed to fromValue().", Objects.equal(victim.getTags(), basicTagValue)); }
### Question: MetricKey implements IHasShortcut { public String toString() { return String.format("MetricKey=[metric=%s, name=%s, tags=%s, id=%s]", metric, name, tags, id); } @JsonProperty("id") String getId(); @JsonProperty("metric") String getMetric(); @JsonProperty("tags") Tags getTags(); @JsonProperty("name") String getName(); @Override boolean equals(Object o); @Override int hashCode(); static MetricKey fromValue(MetricSpecification spec); static MetricKey fromValue(String name, String metric, String tags); String toString(); @Override String getShortcut(); }### Answer: @Test public void testToString() throws Exception { }
### Question: DefaultResultProcessor implements ResultProcessor, ReferenceProvider { @Override public double lookup(String name, Closure closure) throws UnknownReferenceException { if (null == closure) { throw new NullPointerException("null closure passed to lookup() method."); } if ("time".equalsIgnoreCase(name)) { return closure.getTimeStamp(); } Value v = closure.getValueByShortcut(name); if (v == null) { throw new UnknownReferenceException(name); } return v.getValue(); } DefaultResultProcessor(Iterable<OpenTSDBQueryResult> results, List<MetricSpecification> queries, long bucketSize); @Override double lookup(String name, Closure closure); @Override Buckets<IHasShortcut> processResults(); }### Answer: @Test public void testLookup() throws Exception { Closure closure = mock(Closure.class); Value myValue = new Value(); myValue.add(1.0); when(closure.getValueByShortcut("name")).thenReturn(myValue); DefaultResultProcessor victim = new DefaultResultProcessor(null, null, Buckets.DEFAULT_BUCKET_SIZE); double foundValue = victim.lookup("name", closure); assertEquals("lookup should return correct value for series.", myValue.getValue(), foundValue, EPSILON); }
### Question: DefaultResultProcessor implements ResultProcessor, ReferenceProvider { @Override public Buckets<IHasShortcut> processResults() throws IOException, ClassNotFoundException, BadExpressionException { initialize(); for (MetricSpecification metricSpecification : queries) { preProcessQuerySpecifications(metricSpecification); } List<MetricSpecification> calculatedValues = MetricService.calculatedValueFilter(queries); long dataPointTimeStamp = 0l; Tags curTags = null; for (OpenTSDBQueryResult result : this.results) { curTags = Tags.fromOpenTsdbTags(result.tags); MetricKey key = keyCache.get(result.metric, result.metricSpecName, result.metricSpecId, curTags); QueryStatus status = result.getStatus(); log.debug(String.format("Adding QueryStatus %s for key %s (hashcode: %d)", status.getMessage(), key.toString(), key.hashCode())); buckets.addQueryStatus(key, status); for (Map.Entry<Long, Double> dataPointEntry : result.dps.entrySet()) { double dataPointValue = dataPointEntry.getValue(); dataPointTimeStamp = dataPointEntry.getKey(); buckets.add(key, dataPointTimeStamp, dataPointValue); } } interpolateValues(buckets); calculateValues(calculatedValues, buckets); return buckets; } DefaultResultProcessor(Iterable<OpenTSDBQueryResult> results, List<MetricSpecification> queries, long bucketSize); @Override double lookup(String name, Closure closure); @Override Buckets<IHasShortcut> processResults(); }### Answer: @Test public void testProcessResultsWithConstantSeries() throws Exception { Collection<OpenTSDBQueryResult> qResults = makeResults(); List<MetricSpecification> queries = makeQueries(); DefaultResultProcessor victim = new DefaultResultProcessor(qResults, queries, BUCKET_SIZE); Buckets<IHasShortcut> results = victim.processResults(); assertNotNull("Result of processing query should not be null", results); assertEquals("Seconds per bucket should match specified bucket size.", BUCKET_SIZE, results.getSecondsPerBucket()); for (Long timestamp : results.getTimestamps()) { Buckets.Bucket bucket = results.getBucket(timestamp); assertNotNull(String.format("Null bucket found at timestamp %d.", timestamp), bucket); for (MetricSpecification query : queries) { String nameOrMetric = query.getNameOrMetric(); Value value = bucket.getValueByShortcut(nameOrMetric); String pointDescriptor = String.format("series %s at timestamp %d", nameOrMetric, timestamp); assertNotNull(String.format("Missing value for %s.", pointDescriptor), value); if (query.getNameOrMetric().equals(CALCULATED_VALUE_SERIES_NAME)) { System.out.println(String.format("value of %s at %d is %f", nameOrMetric, timestamp, value.getValue())); assertEquals(String.format("Value of %s not correct.", pointDescriptor), CONST_VALUE + CONST_VALUE, value.getValue(), EPSILON); } } } } @Test public void testProcessResultsWithYEqualsXSeries() throws Exception { Collection<OpenTSDBQueryResult> qResults = makeYEqualsXResults(); List<MetricSpecification> queries = makeQueries(); DefaultResultProcessor victim = new DefaultResultProcessor(qResults, queries, BUCKET_SIZE); Buckets<IHasShortcut> results = victim.processResults(); assertNotNull("Result of processing query should not be null", results); assertEquals("Seconds per bucket should match specified bucket size.", BUCKET_SIZE, results.getSecondsPerBucket()); for (Long timestamp : results.getTimestamps()) { Buckets.Bucket bucket = results.getBucket(timestamp); assertNotNull(String.format("Null bucket found at timestamp %d.", timestamp), bucket); for (MetricSpecification query : queries) { String nameOrMetric = query.getNameOrMetric(); Value value = bucket.getValueByShortcut(nameOrMetric); String pointDescriptor = String.format("series %s at timestamp %d", nameOrMetric, timestamp); assertNotNull(String.format("Missing value for %s.", pointDescriptor), value); if (query.getNameOrMetric().equals(CALCULATED_VALUE_SERIES_NAME)) { System.out.println(String.format("value of %s at %d is %f", nameOrMetric, timestamp, value.getValue())); assertEquals(String.format("Value of %s not correct.", pointDescriptor), timestamp + timestamp, value.getValue(), EPSILON); } } } }
### Question: QueryResultDataPoint { public double getValue() { return value; } QueryResultDataPoint(); QueryResultDataPoint(long timestamp, double value); long getTimestamp(); void setTimestamp(long timestamp); double getValue(); void setValue(double value); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testGetValue() throws Exception { QueryResultDataPoint subject = new QueryResultDataPoint(); Assert.assertEquals("Value of uninitialized QueryResultDataPoint should be zero.", subject.getValue(), 0.0, EPSILON); QueryResultDataPoint initializedSubject = new QueryResultDataPoint(initialTime, initialValue); Assert.assertEquals("Value of initialized QueryResultDataPoint should match given value.", initializedSubject.getValue(), initialValue, EPSILON); }
### Question: OpenTSDBQueryResult { @JsonIgnore public SortedMap<Long, Double> getDataPoints() { if (null == dps) { dps = new TreeMap<>(); } return dps; } QueryStatus getStatus(); void setStatus(QueryStatus status); String debugString(); void addTags(Map<String, List<String>> tagsToAdd); void addDataPoint(long i, double pointValue); @JsonIgnore SortedMap<Long, Double> getDataPoints(); void setDataPoints(SortedMap<Long, Double> dps); public String metricSpecName; public String metricSpecId; public List<String> aggregateTags; public SortedMap<Long,Double> dps; public String metric; public Map<String, String> tags; public List<String> tsuids; }### Answer: @Test public void testDataPointsMapIsNotNullOnGet() { OpenTSDBQueryResult subject = new OpenTSDBQueryResult(); assertTrue("DataPoints list is non-null on initialization", null != subject.getDataPoints()); }
### Question: NewValue { public double getMean() { return (numDataValues > 0) ? newMean : Double.NaN; } void clear(); void push(double x); long getNumDataValues(); double getMean(); double getVariance(); double getStandardDeviation(); double getSum(); }### Answer: @Test public void testGetMean() { NewValue victim = new NewValue(); double test = victim.getMean(); assertTrue("getMean() on an uninitialized value should return NaN.", Double.isNaN(test)); double val1 = 1.1, val2 = 2.0; victim.push(val1); assertEquals("Value with one entry should return that entry for getMean", val1, victim.getMean(), EPSILON); victim.push(val2); double expectedResult = (val1 + val2) / 2.0; assertEquals("Value with two entries should return the average of the entries for getMean", expectedResult,victim.getMean(), EPSILON); Double [] testValues = new Double[] {1.0, -1.0, 2.0, 2.1, 0.0, 53.0, -27.5}; victim.clear(); for (double value : testValues) { victim.push(value); } double mean = getMean(testValues); assertEquals("Calculated variance should match variance from test object.", mean, victim.getMean(), EPSILON); }
### Question: NewValue { public double getSum() { return sum; } void clear(); void push(double x); long getNumDataValues(); double getMean(); double getVariance(); double getStandardDeviation(); double getSum(); }### Answer: @Test public void testGetSum() throws Exception { NewValue victim = new NewValue(); Double[] testValues = new Double[]{1.0, 1.1, 2.0, -23.4, 0.0, 1.0, 2.1}; double sum = 0.0; for (Double value : testValues) { victim.push(value); sum += value; } assertEquals(sum,victim.getSum(), EPSILON); }
### Question: NewValue { public double getVariance() { return ((numDataValues > 1) ? newS /(numDataValues - 1) : Double.NaN); } void clear(); void push(double x); long getNumDataValues(); double getMean(); double getVariance(); double getStandardDeviation(); double getSum(); }### Answer: @Test public void testGetVariance() { NewValue victim = new NewValue(); Double[] testValues = new Double[]{1.0, -1.0, 2.0, 2.1, 0.0, 53.0, -27.5}; for (double value : testValues) { victim.push(value); } double variance = getVariance(testValues); assertEquals("Calculated variance should match variance from test object.", variance, victim.getVariance(), EPSILON); assertEquals("Calculated standard deviation should match standard deviation from test object.", Math.sqrt(variance), victim.getStandardDeviation(), EPSILON); }
### Question: Buckets { public final void add(final P primaryKey, final long timestamp, final double value) { long ts = getBucketTimestamp(timestamp); Bucket b = bucketList.get(ts); if (b == null) { b = new Bucket(); bucketList.put(ts, b); } b.add(primaryKey, value); } Buckets(); Buckets(final long secondsPerBucket); Map<Long, Bucket> getBucketList(); void addQueryStatus(P key, QueryStatus status); QueryStatus getQueryStatus(P key); final void add(final P primaryKey, final long timestamp, final double value); final void addInterpolated(final P primaryKey, final long timestamp, final double value); final Buckets<P>.Bucket getBucket(long timestamp); final SortedSet<Long> getTimestamps(); final long getSecondsPerBucket(); final void dump(PrintStream ps); static final long DEFAULT_BUCKET_SIZE; }### Answer: @Test public void testAdd() throws Exception { Buckets<IHasShortcut> testSubject = makeTestBuckets(); testSubject.add(MetricKey.fromValue("", "", ""), 123, 1.234); testSubject.add(MetricKey.fromValue("My.Metric.Formal.Name", "MyMetric", "Foo=Bar"), 123, 4.567); Buckets.Bucket bucket = testSubject.getBucket(123); assertEquals("getValueByShortcut should return the value put in with that shortcut", bucket.getValueByShortcut("").getValue(), 1.234, EPSILON); assertEquals("getValueByShortcut should return the value put in with that shortcut", bucket.getValueByShortcut("My.Metric.Formal.Name").getValue(), 4.567, EPSILON); } @Test (expected = IllegalArgumentException.class) public void addWithNullKeyShouldThrowException() { Buckets<IHasShortcut> testSubject = makeTestBuckets(); testSubject.add(null,12345, 1.234); } @Test (expected = IllegalArgumentException.class) public void addWithEmptyKeyShouldThrowException() { Buckets<IHasShortcut> testSubject = makeTestBuckets(); MetricKey emptyKey = new MetricKey(); testSubject.add(emptyKey, 123, 1.234); } @Test (expected = IllegalArgumentException.class) public void addWithKeyHavingNullShortcutShouldThrowException() { Buckets<IHasShortcut> testSubject = makeTestBuckets(); MetricKey emptyKey = MetricKey.fromValue(null, "MyMetric", "Foo=Bar"); assertNull("getShortcut on this key should be null", emptyKey.getShortcut()); testSubject.add(emptyKey, 123, 1.234); }
### Question: Buckets { public final Buckets<P>.Bucket getBucket(long timestamp) { long bucketTimestamp = getBucketTimestamp(timestamp); return bucketList.get(bucketTimestamp); } Buckets(); Buckets(final long secondsPerBucket); Map<Long, Bucket> getBucketList(); void addQueryStatus(P key, QueryStatus status); QueryStatus getQueryStatus(P key); final void add(final P primaryKey, final long timestamp, final double value); final void addInterpolated(final P primaryKey, final long timestamp, final double value); final Buckets<P>.Bucket getBucket(long timestamp); final SortedSet<Long> getTimestamps(); final long getSecondsPerBucket(); final void dump(PrintStream ps); static final long DEFAULT_BUCKET_SIZE; }### Answer: @Test public void testGetBucket() throws Exception { Buckets<IHasShortcut> testSubject = makeTestBuckets(); MetricKey key = MetricKey.fromValue("My.Metric.Formal.Name", "MyMetric", "Foo=Bar"); testSubject.add(key, 123, 4.567); Buckets<IHasShortcut>.Bucket bucket = testSubject.getBucket(123); assertEquals("getValue should return the value put in with that key", bucket.getValue(key).getValue(), 4.567, EPSILON); assertEquals("getValueByShortcut should return the value put in with that shortcut", bucket.getValueByShortcut("My.Metric.Formal.Name").getValue(), 4.567, EPSILON); } @Test public void testGetValuePastEndOfDataReturnsNaN() { Buckets<IHasShortcut> testSubject = BucketTestUtilities.makeAndPopulateTestBuckets(); final Buckets<IHasShortcut>.Bucket bucket = testSubject.getBucket(1500); assertNull("get bucket outside of time series should return null.", bucket); } @Test public void testGetValueNotInDataReturnsNaNByShortcut() { Buckets<IHasShortcut> testSubject = BucketTestUtilities.makeAndPopulateTestBuckets(); final Buckets<IHasShortcut>.Bucket bucket = testSubject.getBucket(1000); assertNotNull("get bucket in time series should return a bucket.", bucket); double valueForNonexistentSeries = bucket.getValueByShortcut("nonexistentSeries").getValue(); assertEquals("Value for nonexistent series should be NaN", Double.NaN, valueForNonexistentSeries, EPSILON); } @Test public void testGetValueNotInDataReturnsNaNByMetricKey() { Buckets<IHasShortcut> testSubject = BucketTestUtilities.makeAndPopulateTestBuckets(); final Buckets<IHasShortcut>.Bucket bucket = testSubject.getBucket(1000); assertNotNull("get bucket in time series should return a bucket.", bucket); MetricKey nonexistentMetric = MetricKey.fromValue("NonexistentMetric", "Nonexistent Series", "device=dev1 Series=M1"); double valueForNonexistentSeries = bucket.getValue(nonexistentMetric).getValue(); assertEquals("Value for nonexistent series should be NaN", Double.NaN, valueForNonexistentSeries, EPSILON); } @Test(expected = IllegalArgumentException.class) public void getValueWithNullShouldThrowException() { Buckets<IHasShortcut> testSubject = BucketTestUtilities.makeAndPopulateTestBuckets(); final Buckets<IHasShortcut>.Bucket bucket = testSubject.getBucket(1000); bucket.getValue(null); } @Test(expected = IllegalArgumentException.class) public void getValueByShortcutWithNullShouldThrowException() { Buckets<IHasShortcut> testSubject = BucketTestUtilities.makeAndPopulateTestBuckets(); final Buckets<IHasShortcut>.Bucket bucket = testSubject.getBucket(1000); bucket.getValueByShortcut(null); }
### Question: Buckets { public final SortedSet<Long> getTimestamps() { SortedSet<Long> result = new TreeSet<>(bucketList.keySet()); return result; } Buckets(); Buckets(final long secondsPerBucket); Map<Long, Bucket> getBucketList(); void addQueryStatus(P key, QueryStatus status); QueryStatus getQueryStatus(P key); final void add(final P primaryKey, final long timestamp, final double value); final void addInterpolated(final P primaryKey, final long timestamp, final double value); final Buckets<P>.Bucket getBucket(long timestamp); final SortedSet<Long> getTimestamps(); final long getSecondsPerBucket(); final void dump(PrintStream ps); static final long DEFAULT_BUCKET_SIZE; }### Answer: @Test public void testGetTimestamps() throws Exception { Buckets<IHasShortcut> testSubject = makeTestBuckets(); assertTrue("GetTimestamps", null != testSubject.getTimestamps()); }
### Question: QueryResultDataPoint { public void setValue(double value) { this.value = value; } QueryResultDataPoint(); QueryResultDataPoint(long timestamp, double value); long getTimestamp(); void setTimestamp(long timestamp); double getValue(); void setValue(double value); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testSetValue() throws Exception { QueryResultDataPoint subject = new QueryResultDataPoint(); Assert.assertEquals("Value of uninitialized QueryResultDataPoint should be zero.", subject.getValue(), 0.0, EPSILON); subject.setValue(initialValue); Assert.assertEquals("Value of initialized QueryResultDataPoint should match given value.", subject.getValue(), initialValue, EPSILON); }
### Question: Buckets { public final long getSecondsPerBucket() { return secondsPerBucket; } Buckets(); Buckets(final long secondsPerBucket); Map<Long, Bucket> getBucketList(); void addQueryStatus(P key, QueryStatus status); QueryStatus getQueryStatus(P key); final void add(final P primaryKey, final long timestamp, final double value); final void addInterpolated(final P primaryKey, final long timestamp, final double value); final Buckets<P>.Bucket getBucket(long timestamp); final SortedSet<Long> getTimestamps(); final long getSecondsPerBucket(); final void dump(PrintStream ps); static final long DEFAULT_BUCKET_SIZE; }### Answer: @Test public void testGetSecondsPerBucket() throws Exception { Buckets<IHasShortcut> testSubject = makeTestBuckets(); assertTrue("Buckets should default to 300 seconds per bucket.", 300 == testSubject.getSecondsPerBucket()); Buckets<IHasShortcut> testSubject2 = new Buckets<>(123); assertTrue("Buckets created with specified seconds per bucket should have that value.", 123 == testSubject2.getSecondsPerBucket()); } @Test public void specifyingNegativeBucketSizeDefaultsValue() { Buckets<IHasShortcut> testSubject = new Buckets<>(-25l); assertEquals("If a negative bucket is specified, buckets should have default bucket size.", Buckets.DEFAULT_BUCKET_SIZE, testSubject.getSecondsPerBucket()); }
### Question: Buckets { public final void dump(PrintStream ps) { List<Long> keys = new ArrayList<>(bucketList.keySet()); Collections.sort(keys); for (long k : keys) { ps.format("BUCKET: %d (%d) (%s)%n", k, k * secondsPerBucket, new Date(k * secondsPerBucket * 1000)); for (P key : bucketList.get(k).values.keySet()) { Value value = bucketList.get(k).values.get(key); ps.format(" %-40s : %10.2f (%10.2f / %d)%n", key.toString(), value.getValue(), value.getSum(), value.getCount()); } } } Buckets(); Buckets(final long secondsPerBucket); Map<Long, Bucket> getBucketList(); void addQueryStatus(P key, QueryStatus status); QueryStatus getQueryStatus(P key); final void add(final P primaryKey, final long timestamp, final double value); final void addInterpolated(final P primaryKey, final long timestamp, final double value); final Buckets<P>.Bucket getBucket(long timestamp); final SortedSet<Long> getTimestamps(); final long getSecondsPerBucket(); final void dump(PrintStream ps); static final long DEFAULT_BUCKET_SIZE; }### Answer: @Test public void testDump() throws Exception { Buckets<IHasShortcut> testSubject = BucketTestUtilities.makeAndPopulateTestBuckets(); BucketTestUtilities.dumpBucketsToStdout(testSubject); }
### Question: Value { public final double getValue() { if (count != 0) { return sum / (double) count; } if (hasInterpolated) { return interpolated; } return Double.NaN; } final double getValue(); final double getSum(); final long getCount(); final void add(final double value); final void addInterpolated(final double value); final boolean valueIsInterpolated(); final void remove(final double value); }### Answer: @Test public void testGetValue() { Value victim = new Value(); double test = victim.getValue(); assertTrue("getValue() on an uninitialized value should return NaN.", Double.isNaN(test)); double val1 = 1.1, val2 = 2.0; victim.add(val1); assertEquals("Value with one entry should return that entry for getValue", val1, victim.getValue(), EPSILON); victim.add(val2); double expectedResult = (val1 + val2) / 2.0; assertEquals(String.format("Value with two entries should return the average of the entries for getValue (expected = %f, actual = %f", expectedResult, victim.getValue()), expectedResult,victim.getValue(), EPSILON); } @Test public void uninitializedValueShouldReturnNaNOnGet() { Value victim = new Value(); assertTrue("An Uninitialized Value should return NaN on getValue().", Double.isNaN(victim.getValue())); }
### Question: Value { public final double getSum() { return sum; } final double getValue(); final double getSum(); final long getCount(); final void add(final double value); final void addInterpolated(final double value); final boolean valueIsInterpolated(); final void remove(final double value); }### Answer: @Test public void testGetSum() throws Exception { Value victim = new Value(); Double[] testValues = new Double[]{1.0, 1.1, 2.0, -23.4, 0.0, 1.0, 2.1}; double sum = 0.0; for (Double value : testValues) { victim.add(value); sum += value; } assertEquals(sum,victim.getSum(), EPSILON); }
### Question: QueryStatus { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QueryStatus that = (QueryStatus) o; if (message != null ? !message.equals(that.message) : that.message != null) return false; if (status != that.status) return false; return true; } QueryStatus(); QueryStatus(QueryStatusEnum status, String message); @Override boolean equals(Object o); @Override int hashCode(); QueryStatusEnum getStatus(); void setStatus(QueryStatusEnum status); String getMessage(); void setMessage(String message); }### Answer: @Test public void testEquals() throws Exception { String testMessage = "Message for Unit Test"; QueryStatus one = new QueryStatus(QueryStatus.QueryStatusEnum.WARNING, testMessage); Assert.assertEquals("A QueryStatus object should be equal to itself.", one, one); QueryStatus other = new QueryStatus(QueryStatus.QueryStatusEnum.WARNING, testMessage); Assert.assertEquals("Two QueryStatus objects created with the same parameters should be equal.", one, other); other.setMessage("A different message"); Assert.assertNotEquals("QueryStatus objects with different messages should not be equal.", one, other); other.setMessage(testMessage); Assert.assertEquals("QueryStatus objects should be equal after setting message back to same value", one, other); other.setStatus(QueryStatus.QueryStatusEnum.ERROR); Assert.assertNotEquals("QueryStatusObjects with different statuses should not be equal.", one, other); }
### Question: Value { public final long getCount() { return count; } final double getValue(); final double getSum(); final long getCount(); final void add(final double value); final void addInterpolated(final double value); final boolean valueIsInterpolated(); final void remove(final double value); }### Answer: @Test public void testGetCount() throws Exception { Value victim = new Value(); Double[] testValues = new Double[]{1.0, 1.1, 2.0, 2.1}; for (Double value : testValues) { victim.add(value); } assertTrue(testValues.length == victim.getCount()); }
### Question: Value { public final void add(final double value) { sum += value; count++; } final double getValue(); final double getSum(); final long getCount(); final void add(final double value); final void addInterpolated(final double value); final boolean valueIsInterpolated(); final void remove(final double value); }### Answer: @Test public void testAdd() throws Exception { Value victim = new Value(); Double[] testValues = new Double[]{1.0, -1.0, 2.0, 2.1, 0.0, 53.0, -27.5}; double sum = 0.0; for (Double value : testValues) { victim.add(value); sum += value; } assertEquals(sum,victim.getSum(), EPSILON); }
### Question: Value { public final boolean valueIsInterpolated() { return count == 0 && hasInterpolated; } final double getValue(); final double getSum(); final long getCount(); final void add(final double value); final void addInterpolated(final double value); final boolean valueIsInterpolated(); final void remove(final double value); }### Answer: @Test public void uninitializedValueShouldReturnFalseForValueIsInterpolated() { Value victim = new Value(); assertEquals("An Uninitialized Value should return false on valueIsInterpolated().", false, victim.valueIsInterpolated()); }
### Question: Value { public final void remove(final double value) { sum -= value; count--; } final double getValue(); final double getSum(); final long getCount(); final void add(final double value); final void addInterpolated(final double value); final boolean valueIsInterpolated(); final void remove(final double value); }### Answer: @Test public void testRemove() throws Exception { Value victim = new Value(); Double[] testValues = new Double[]{1.0, -1.0, 2.0, 2.1, 0.0, 53.0, -27.5}; for (Double value : testValues) { victim.add(value); } double originalValue = victim.getValue(); double originalSum = victim.getSum(); long originalCount = victim.getCount(); Double[] newValues = new Double[] {2.1, -27.0, 2.1, 0.0 }; double newValueSum = 0.0; long newValueCount = newValues.length; for (Double value : newValues) { newValueSum += value; victim.add(value); } double appendedSum = originalSum + newValueSum; long appendedCount = originalCount + newValueCount; double appendedAverage = appendedSum / appendedCount; assertEquals("Appended sum should match.", appendedSum, victim.getSum(), EPSILON); assertEquals("Appended value (average) should match", appendedAverage, victim.getValue(), EPSILON); assertTrue("Appended count should match.", appendedCount == victim.getCount()); for (Double value : newValues) { victim.remove(value); } assertEquals("After remove, value should equal original value.", originalValue, victim.getValue(), EPSILON); assertEquals("After remove, sum should equal original sum.", originalSum,victim.getSum(), EPSILON); assertTrue("After remove, count should equal original count.", originalCount == victim.getCount()); }
### Question: QueryStatus { @Override public int hashCode() { int result = message != null ? message.hashCode() : 0; result = 31 * result + (status != null ? status.hashCode() : 0); return result; } QueryStatus(); QueryStatus(QueryStatusEnum status, String message); @Override boolean equals(Object o); @Override int hashCode(); QueryStatusEnum getStatus(); void setStatus(QueryStatusEnum status); String getMessage(); void setMessage(String message); }### Answer: @Test public void testHashCode() throws Exception { String testMessage = "Message for Unit Test"; QueryStatus.QueryStatusEnum testStatus = QueryStatus.QueryStatusEnum.WARNING; QueryStatus one = new QueryStatus(testStatus, testMessage); Assert.assertEquals("A QueryStatus object should have the same hashcode as itself.", one.hashCode(), one.hashCode()); QueryStatus other = new QueryStatus(testStatus, testMessage); Assert.assertEquals("Two QueryStatus objects created with the same parameters should have same hashcodes.", one.hashCode(), other.hashCode()); other.setMessage("A different message"); Assert.assertNotEquals("QueryStatus objects with different messages should have different hashcodes.", one.hashCode(), other.hashCode()); other.setMessage(testMessage); Assert.assertEquals("QueryStatus objects should have the same hashcode after setting message back to same value", one.hashCode(), other.hashCode()); other.setStatus(QueryStatus.QueryStatusEnum.ERROR); Assert.assertNotEquals("QueryStatusObjects with different statuses should have different hashcodes.", one.hashCode(), other.hashCode()); }
### Question: QueryStatus { public QueryStatusEnum getStatus() { return status; } QueryStatus(); QueryStatus(QueryStatusEnum status, String message); @Override boolean equals(Object o); @Override int hashCode(); QueryStatusEnum getStatus(); void setStatus(QueryStatusEnum status); String getMessage(); void setMessage(String message); }### Answer: @Test public void testGetStatus() throws Exception { String testMessage = "Message for Unit Test"; QueryStatus.QueryStatusEnum testStatus = QueryStatus.QueryStatusEnum.WARNING; QueryStatus one = new QueryStatus(testStatus, testMessage); Assert.assertEquals("getStatus should return status passed to constructor.", testStatus, one.getStatus()); }
### Question: QueryStatus { public void setStatus(QueryStatusEnum status) { this.status = status; } QueryStatus(); QueryStatus(QueryStatusEnum status, String message); @Override boolean equals(Object o); @Override int hashCode(); QueryStatusEnum getStatus(); void setStatus(QueryStatusEnum status); String getMessage(); void setMessage(String message); }### Answer: @Test public void testSetStatus() throws Exception { String testMessage = "Message for Unit Test"; QueryStatus.QueryStatusEnum testStatus = QueryStatus.QueryStatusEnum.WARNING; QueryStatus.QueryStatusEnum newStatus = QueryStatus.QueryStatusEnum.ERROR; QueryStatus one = new QueryStatus(testStatus, testMessage); Assert.assertEquals("getStatus should return status passed to constructor.", testStatus, one.getStatus()); one.setStatus(newStatus); Assert.assertEquals("getStatus should return status set with setStatus.", newStatus, one.getStatus()); }
### Question: QueryStatus { public String getMessage() { return message; } QueryStatus(); QueryStatus(QueryStatusEnum status, String message); @Override boolean equals(Object o); @Override int hashCode(); QueryStatusEnum getStatus(); void setStatus(QueryStatusEnum status); String getMessage(); void setMessage(String message); }### Answer: @Test public void testGetMessage() throws Exception { String testMessage = "Message for Unit Test"; QueryStatus.QueryStatusEnum testStatus = QueryStatus.QueryStatusEnum.WARNING; QueryStatus one = new QueryStatus(testStatus, testMessage); Assert.assertEquals("getMessage should return message passed to constructor.", testMessage, one.getMessage()); }
### Question: QueryStatus { public void setMessage(String message) { this.message = message; } QueryStatus(); QueryStatus(QueryStatusEnum status, String message); @Override boolean equals(Object o); @Override int hashCode(); QueryStatusEnum getStatus(); void setStatus(QueryStatusEnum status); String getMessage(); void setMessage(String message); }### Answer: @Test public void testSetMessage() throws Exception { String testMessage = "Message for Unit Test"; String newMessage = "New Unit Test Message"; QueryStatus.QueryStatusEnum testStatus = QueryStatus.QueryStatusEnum.WARNING; QueryStatus one = new QueryStatus(testStatus, testMessage); Assert.assertEquals("getMessage should return message passed to constructor.", testMessage, one.getMessage()); one.setMessage(newMessage); Assert.assertEquals("getMessage should return status set with setStatus.", newMessage, one.getMessage()); }
### Question: MboxIterator implements Iterable<CharBufferWrapper>, Closeable { public Iterator<CharBufferWrapper> iterator() { return new MessageIterator(); } private MboxIterator(final File mbox, final Charset charset, final String regexpPattern, final int regexpFlags, final int MAX_MESSAGE_SIZE); Iterator<CharBufferWrapper> iterator(); void close(); static Builder fromFile(File filePath); static Builder fromFile(String file); static String bufferDetailsToString(final Buffer buffer); }### Answer: @Test public void testIterator() throws FileNotFoundException, IOException { iterateWithMaxMessage(DEFAULT_MESSAGE_SIZE); } @Test public void testIterator() throws FileNotFoundException, IOException { System.out.println("Executing " + name.getMethodName()); iterateWithMaxMessage(DEFAULT_MESSAGE_SIZE); }
### Question: Mapping { String getResourceType(String nodePath, String nodeType) { String result = null; if(path!=null && nodePath.startsWith(path) && nodeTypeMatches(nodeType)) { final String [] paths = nodePath.split("/"); if(paths.length >= resourceTypeIndex+1) { result = paths[resourceTypeIndex]; } } return result; } Mapping(String definition); @Override String toString(); static final String DEFAULT_NODE_TYPE; }### Answer: @Test public void testLevel2() { final Mapping m = new Mapping("/content:3"); assertEquals("bar1", m.getResourceType("/content/foo/bar1", "nt:unstructured")); assertEquals("bar2", m.getResourceType("/content/foo/bar2/wii", "nt:unstructured")); assertNull(m.getResourceType("/", "nt:unstructured")); assertNull(m.getResourceType("/content", "nt:unstructured")); } @Test public void testLevel3() { final Mapping m = new Mapping("/content:3"); assertEquals("bar1", m.getResourceType("/content/foo/bar1", "nt:unstructured")); assertEquals("bar2", m.getResourceType("/content/foo/bar2/wii", "nt:unstructured")); assertEquals("bar3", m.getResourceType("/content/foo/bar3/wii2/xx", "nt:unstructured")); assertNull(m.getResourceType("/", "nt:unstructured")); assertNull(m.getResourceType("/content", "nt:unstructured")); assertNull(m.getResourceType("/content/foo", "nt:unstructured")); } @Test public void testNodetypeString() { final Mapping m = new Mapping("/content:2:nt:file"); assertNotNull("nt:file must match", m.getResourceType("/content/foo1", "nt:file")); assertEquals("foo1", m.getResourceType("/content/foo1", "nt:file")); assertNull(m.getResourceType("/content/foo1", "nt:unstructured")); assertNull(m.getResourceType("/content/foo1", "some:type")); } @Test public void testNodetypeRegexp() { final Mapping m = new Mapping("/content:2:(nt:(file|test))"); assertNotNull("nt:file must match", m.getResourceType("/content/foo1", "nt:file")); assertEquals("foo1", m.getResourceType("/content/foo1", "nt:file")); assertNotNull("nt:test must match", m.getResourceType("/content/foo1", "nt:test")); assertEquals("foo2", m.getResourceType("/content/foo2", "nt:test")); assertNull(m.getResourceType("/content/foo1", "nt:unstructured")); assertNull(m.getResourceType("/content/foo1", "some:type")); } @Test public void testSimpleMapping() { final Mapping m = new Mapping("/content:2"); final String[][] testCases = { { "/content/foo", "nt:unstructured", "foo" }, { "/content/foo/bar", "nt:unstructured", "foo" }, { "/not/content/foo/bar", "nt:unstructured", null }, { "/content/foo/bar", "nt:file", null } }; for(int i=0; i < testCases.length; i++) { final String [] tc = testCases[i]; if(tc[2] == null) { assertNull("At index " + i, m.getResourceType(tc[0], tc[1])); } else { assertEquals("At index " + i, tc[2], m.getResourceType(tc[0], tc[1])); } } }
### Question: ThreadKeyGeneratorImpl implements ThreadKeyGenerator { public String getThreadKey(String subject) { String wordCharsSubj; String noReSubj; if (subject != null) { noReSubj = removeRe(subject); wordCharsSubj = noReSubj.replaceAll("\\W", "_"); if (!isAddressable(wordCharsSubj)) { noReSubj = wordCharsSubj = UNADDRESSABLE_SUBJECT; } } else { noReSubj = wordCharsSubj = UNADDRESSABLE_SUBJECT; } char prefix1; char prefix2; prefix1 = assignPrefix(wordCharsSubj, LETTER_POS_WITH_BIGGEST_ENTROPY); prefix2 = assignPrefix(wordCharsSubj, LETTER_POS_WITH_2ND_BIGGEST_ENTROPY); return ""+prefix1+"/"+prefix1+prefix2+"/"+ makeJcrFriendly(noReSubj); } String getThreadKey(String subject); }### Answer: @Test public void testGetThreadKey() { assertEquals(expected, generator.getThreadKey(input)); }
### Question: Mime4jMboxParserImpl implements MboxParser { @Override public Iterator<Message> parse(InputStream is) throws IOException { return new Mime4jParserIterator(is); } @Override Iterator<Message> parse(InputStream is); }### Answer: @Test public void testMboxParsing() throws IOException { Iterator<Message> iter = parser.parse(new FileInputStream(new File(TU.TEST_FOLDER, WRONGBODY_MBOX))); boolean fail = true; int i = 1; while (iter.hasNext()) { final Message message = iter.next(); File bodyFile = new File(TU.TEST_FOLDER, specialPathFromFilePath(WRONGBODY_MBOX, "_bodyOf" + i, "txt")); if (bodyFile.exists()) { final String actual = getPlainBody(message); final String expected = readTextFile(bodyFile); assertEquals("Body #"+i, expected, actual); fail = false; } i++; } if (fail) { fail("No file with expected body."); } }
### Question: SlingshotUtil { public static String getUserId(final Resource resource) { final String prefix = SlingshotConstants.APP_ROOT_PATH + "/"; String id = null; if ( resource.getPath().startsWith(prefix) ) { final int areaEnd = resource.getPath().indexOf('/', prefix.length()); if ( areaEnd != -1 ) { final int userEnd = resource.getPath().indexOf('/', areaEnd + 1); if ( userEnd == -1 ) { id = resource.getPath().substring(areaEnd + 1); } else { id = resource.getPath().substring(areaEnd + 1, userEnd); } } } return id; } static String getUserId(final Resource resource); static String getContentPath(final Resource resource); static boolean isUser(final SlingHttpServletRequest request); }### Answer: @Test public void getUserId_deepPath() { Resource resource = context.resourceResolver().getResource("/content/slingshot/users/admin/hobby"); assertThat(SlingshotUtil.getUserId(resource), equalTo("admin")); } @Test public void getUserId_exactPath() { Resource resource = context.resourceResolver().getResource("/content/slingshot/users/admin"); assertThat(SlingshotUtil.getUserId(resource), equalTo("admin")); } @Test public void getUserId_noMatch() { Resource resource = context.resourceResolver().getResource("/content/slingshot/users"); assertThat(SlingshotUtil.getUserId(resource), nullValue()); }
### Question: SlingshotUtil { public static String getContentPath(final Resource resource) { final String prefix = SlingshotConstants.APP_ROOT_PATH + "/users/" + getUserId(resource) + "/"; final String path = resource.getPath(); if ( path != null && path.startsWith(prefix) ) { return path.substring(prefix.length() - 1); } return null; } static String getUserId(final Resource resource); static String getContentPath(final Resource resource); static boolean isUser(final SlingHttpServletRequest request); }### Answer: @Test public void getContentPath_match() { Resource resource = context.resourceResolver().getResource("/content/slingshot/users/admin/hobby"); assertThat(SlingshotUtil.getContentPath(resource), equalTo("/hobby")); } @Test public void getContentPath_noMatch() { Resource resource = context.resourceResolver().getResource("/content/slingshot/users/admin"); assertThat(SlingshotUtil.getContentPath(resource), nullValue()); }
### Question: Util { public static String filter(final String rsrcname) { final StringBuilder sb = new StringBuilder(); char lastAdded = 0; final String name = rsrcname.toLowerCase(); for(int i=0; i < name.length(); i++) { final char c = name.charAt(i); char toAdd = c; if (ALLOWED_CHARS.indexOf(c) < 0) { if (lastAdded == REPLACEMENT_CHAR) { continue; } toAdd = REPLACEMENT_CHAR; } else if(i == 0 && Character.isDigit(c)) { sb.append(REPLACEMENT_CHAR); } sb.append(toAdd); lastAdded = toAdd; } if (sb.length()==0) { sb.append(REPLACEMENT_CHAR); } return sb.toString(); } static String filter(final String rsrcname); }### Answer: @Test public void filter() { assertThat(output, equalTo(Util.filter(input))); }
### Question: EditorLinksImpl extends AbstractEmptyTextComponent implements EditorLinks { @Override public String getAssetDetailsEditorPath() { return request.getResourceResolver().map(ASSET_DETAILS_PREFIX + asset.getPath()); } @Override String getAssetDetailsEditorPath(); @Override String getAssetFolderEditorPath(); @Override boolean isEmpty(); @Override boolean isReady(); @Nonnull @Override String getExportedType(); }### Answer: @Test public void getAssetDetailsEditorPath() { final String expected = "/assetdetails.html/content/dam/test.png"; ctx.currentResource("/content/editor-links"); final EditorLinks editorLinks = ctx.request().adaptTo(EditorLinks.class); assertEquals(expected, editorLinks.getAssetDetailsEditorPath()); }
### Question: ExternalRedirectRenditionDispatcherImpl extends AbstractRenditionDispatcherImpl implements AssetRenditionDispatcher { @Override public String getLabel() { return cfg.label(); } @Override String getLabel(); @Override String getName(); @Override Map<String, String> getOptions(); @Override boolean isHidden(); @Override Set<String> getRenditionNames(); @Override List<String> getTypes(); @Override void dispatch(SlingHttpServletRequest request, SlingHttpServletResponse response); }### Answer: @Test public void getLabel() { final String expected = "Test Asset Rendition Resolver"; ctx.registerInjectActivateService(new ExternalRedirectRenditionDispatcherImpl(), "label", "Test Asset Rendition Resolver"); final AssetRenditionDispatcher assetRenditionDispatcher = ctx.getService(AssetRenditionDispatcher.class); final String actual = assetRenditionDispatcher.getLabel(); assertEquals(expected, actual); }
### Question: ExternalRedirectRenditionDispatcherImpl extends AbstractRenditionDispatcherImpl implements AssetRenditionDispatcher { @Override public String getName() { return cfg.name(); } @Override String getLabel(); @Override String getName(); @Override Map<String, String> getOptions(); @Override boolean isHidden(); @Override Set<String> getRenditionNames(); @Override List<String> getTypes(); @Override void dispatch(SlingHttpServletRequest request, SlingHttpServletResponse response); }### Answer: @Test public void getName() { final String expected = "test"; ctx.registerInjectActivateService(new ExternalRedirectRenditionDispatcherImpl(), "name", "test"); final AssetRenditionDispatcher assetRenditionDispatcher = ctx.getService(AssetRenditionDispatcher.class); final String actual = assetRenditionDispatcher.getName(); assertEquals(expected, actual); }
### Question: ExternalRedirectRenditionDispatcherImpl extends AbstractRenditionDispatcherImpl implements AssetRenditionDispatcher { @Override public Map<String, String> getOptions() { return assetRenditions.getOptions(mappings); } @Override String getLabel(); @Override String getName(); @Override Map<String, String> getOptions(); @Override boolean isHidden(); @Override Set<String> getRenditionNames(); @Override List<String> getTypes(); @Override void dispatch(SlingHttpServletRequest request, SlingHttpServletResponse response); }### Answer: @Test public void getOptions() { final Map<String, String> expected = ImmutableMap.<String, String>builder(). put("Foo", "foo"). put("Foo bar", "foo_bar"). put("Foo-bar", "foo-bar"). build(); ctx.registerInjectActivateService(new ExternalRedirectRenditionDispatcherImpl(), ImmutableMap.<String, Object>builder(). put("rendition.mappings", new String[]{ "foo=foo value", "foo_bar=foo_bar value", "foo-bar=foo-bar value"}). build()); final AssetRenditionDispatcher assetRenditionDispatcher = ctx.getService(AssetRenditionDispatcher.class); final Map<String, String> actual = assetRenditionDispatcher.getOptions(); assertEquals(expected, actual); }
### Question: ExternalRedirectRenditionDispatcherImpl extends AbstractRenditionDispatcherImpl implements AssetRenditionDispatcher { @Override public Set<String> getRenditionNames() { if (mappings == null) { return Collections.EMPTY_SET; } else { return mappings.keySet(); } } @Override String getLabel(); @Override String getName(); @Override Map<String, String> getOptions(); @Override boolean isHidden(); @Override Set<String> getRenditionNames(); @Override List<String> getTypes(); @Override void dispatch(SlingHttpServletRequest request, SlingHttpServletResponse response); }### Answer: @Test public void getRenditionNames() { Set<String> expected = new HashSet<>(); expected.add("foo"); expected.add("test.ing-rendition"); ctx.registerInjectActivateService(new ExternalRedirectRenditionDispatcherImpl(), ImmutableMap.<String, Object>builder(). put("rendition.mappings", new String[]{ "foo=foo value", "test.ing-rendition=test-rendition value"}). build()); final AssetRenditionDispatcher assetRenditionDispatcher = ctx.getService(AssetRenditionDispatcher.class); final Set<String> actual = assetRenditionDispatcher.getRenditionNames(); assertEquals(expected.size(), actual.size()); assertTrue(expected.contains("foo")); assertTrue(expected.contains("test.ing-rendition")); }
### Question: ExternalRedirectRenditionDispatcherImpl extends AbstractRenditionDispatcherImpl implements AssetRenditionDispatcher { @Override public void dispatch(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException, ServletException { final AssetRenditionParameters parameters = new AssetRenditionParameters(request); final String expression = mappings.get(parameters.getRenditionName()); final String evaluatedExpression = assetRenditions.evaluateExpression(request, expression); if (StringUtils.isNotBlank(evaluatedExpression)) { log.debug("Serving External redirect rendition [ {} ] for resolved rendition name [ {} ]", evaluatedExpression, parameters.getRenditionName()); if (cfg.redirect() == HttpServletResponse.SC_MOVED_TEMPORARILY) { response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); } else { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); } response.setHeader("Location", UrlUtil.escape(evaluatedExpression)); } else { log.error("Could not convert [ {} ] into a valid URI", evaluatedExpression); response.sendError(HttpServletResponse.SC_NOT_FOUND, "Could not serve asset rendition."); } } @Override String getLabel(); @Override String getName(); @Override Map<String, String> getOptions(); @Override boolean isHidden(); @Override Set<String> getRenditionNames(); @Override List<String> getTypes(); @Override void dispatch(SlingHttpServletRequest request, SlingHttpServletResponse response); }### Answer: @Test public void dispatch() throws IOException, ServletException { ctx.registerInjectActivateService(new ExternalRedirectRenditionDispatcherImpl(), ImmutableMap.<String, Object>builder(). put("rendition.mappings", new String[]{ "testing=${dm.domain}is/image/${dm.file}?$greyscale$"}). build()); final AssetRenditionDispatcher assetRenditionDispatcher = ctx.getService(AssetRenditionDispatcher.class); ctx.requestPathInfo().setResourcePath("/content/dam/test.png"); ctx.requestPathInfo().setExtension("rendition"); ctx.requestPathInfo().setSuffix("testing/download/asset.rendition"); assetRenditionDispatcher.dispatch(ctx.request(), ctx.response()); assertEquals(301, ctx.response().getStatus()); } @Test public void dispatch_WithSpacesInPath() throws IOException, ServletException { ctx.registerInjectActivateService(new ExternalRedirectRenditionDispatcherImpl(), ImmutableMap.<String, Object>builder(). put("rendition.mappings", new String[]{ "testing=${asset.path}.test.500.500.${asset.extension}"}). put("redirect", 302). build()); final AssetRenditionDispatcher assetRenditionDispatcher = ctx.getService(AssetRenditionDispatcher.class); doReturn(DamUtil.resolveToAsset(ctx.resourceResolver().getResource("/content/dam/test with spaces.png"))).when(assetResolver).resolveAsset(ctx.request()); ctx.currentResource("/content/dam/test with spaces.png"); ctx.requestPathInfo().setExtension("rendition"); ctx.requestPathInfo().setSuffix("testing/download/asset.rendition"); assetRenditionDispatcher.dispatch(ctx.request(), ctx.response()); assertEquals(302, ctx.response().getStatus()); assertEquals("/content/dam/test%20with%20spaces.png.test.500.500.png", ctx.response().getHeader("Location")); }
### Question: AssetRenditionServlet extends SlingSafeMethodsServlet { public final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException, ServletException { try { final AssetRenditionParameters parameters = new AssetRenditionParameters(request); if (acceptsAssetRenditionParameters(parameters)) { for (final AssetRenditionDispatcher assetRenditionDispatcher : assetRenditionDispatchers.getAssetRenditionDispatchers()) { if (acceptedByAssetRenditionDispatcher(assetRenditionDispatcher, parameters)) { setResponseHeaders(response, parameters); assetRenditionDispatcher.dispatch(request, response); return; } } response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unable to resolve an AssetRenditionDispatcher that can dispatch to a rendition."); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported suffix parameters detected."); } } catch (IllegalArgumentException e) { log.warn("Invalid request URL format for AssetRenditionServlet.", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR , "Invalid request URL format for AssetRenditionServlet."); } } final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response); static final String SERVLET_EXTENSION; }### Answer: @Test public void doGet() throws IOException, ServletException { final AssetRenditionDispatcher assetRenditionDispatcher = Mockito.spy(new StaticRenditionDispatcherImpl()); final byte[] expectedOutputStream = IOUtils.toByteArray(this.getClass().getResourceAsStream("AssetRenditionServletTest__cq5dam.web.1280.1280.png")); doAnswer(invocation -> { Object[] args = invocation.getArguments(); ((MockSlingHttpServletResponse) args[1]).getOutputStream().write(expectedOutputStream); return null; }).when(requestDispatcher).include(any(SlingHttpServletRequest.class), any(SlingHttpServletResponse.class)); ctx.registerInjectActivateService( new StaticRenditionDispatcherImpl(), ImmutableMap.<String, Object>builder(). put("rendition.mappings", new String[]{ "testing1=value doesnt matter"}). build()); ctx.registerInjectActivateService( assetRenditionDispatcher, ImmutableMap.<String, Object>builder(). put("rendition.mappings", new String[]{ "original=original", "testing2=^cq5dam\\.web\\..*"}). build()); ctx.registerInjectActivateService(new AssetRenditionServlet()); ctx.request().setMethod("GET"); ctx.requestPathInfo().setResourcePath("/content/dam/test.png"); ctx.requestPathInfo().setExtension("renditions"); ctx.requestPathInfo().setSuffix("testing2/asset.rendition"); ctx.getService(Servlet.class).service(ctx.request(), ctx.response()); Mockito.verify(assetRenditionDispatcher, Mockito.times(1)).dispatch(ctx.request(), ctx.response()); }
### Question: AssetRenditionServlet extends SlingSafeMethodsServlet { protected void setResponseHeaders(final SlingHttpServletResponse response, final AssetRenditionParameters parameters) { if (parameters.isDownload()) { response.setHeader("Content-Disposition", String.format("attachment; filename=%s", parameters.getFileName())); } else { response.setHeader("Content-Disposition", String.format("filename=%s", parameters.getFileName())); } } final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response); static final String SERVLET_EXTENSION; }### Answer: @Test public void setResponseHeaders() { ctx.requestPathInfo().setResourcePath("/content/dam/test.png"); ctx.requestPathInfo().setExtension("rendition"); ctx.requestPathInfo().setSuffix("testing/asset.rendition"); final AssetRenditionParameters params = new AssetRenditionParameters(ctx.request()); new AssetRenditionServlet().setResponseHeaders(ctx.response(), params); assertEquals("filename=test.testing.png", ctx.response().getHeader("Content-Disposition")); } @Test public void setResponseHeaders_AsAttachment() { ctx.requestPathInfo().setResourcePath("/content/dam/test.png"); ctx.requestPathInfo().setExtension("rendition"); ctx.requestPathInfo().setSuffix("testing/download/asset.rendition"); final AssetRenditionParameters params = new AssetRenditionParameters(ctx.request()); new AssetRenditionServlet().setResponseHeaders(ctx.response(), params); assertEquals("attachment; filename=test.testing.png", ctx.response().getHeader("Content-Disposition")); }
### Question: AssetRenditionsZipperImpl implements AssetRenditionsDownloadOrchestrator { @Override public boolean accepts(SlingHttpServletRequest request, List<AssetModel> assets, List<String> renditionNames) { return NAME.equals(request.getRequestParameter(REQUEST_PARAMETER_NAME).getString()); } @Override void execute(final SlingHttpServletRequest request, final SlingHttpServletResponse response, final List<AssetModel> assets, final List<String> renditionNames); @Override boolean accepts(SlingHttpServletRequest request, List<AssetModel> assets, List<String> renditionNames); static final String NAME; static final String VAR_ASSET_NAME; static final String VAR_ASSET_EXTENSION; static final String VAR_RENDITION_NAME; static final String VAR_RENDITION_EXTENSION; static final String VAR_ASSET_FILE_NAME; static final String VAR_ASSET_TITLE; static final String ZIP_EXTENSION; static final String DEFAULT_NO_CONTENT_FILE_NAME; static final String DEFAULT_NO_CONTENT_MESSAGE; }### Answer: @Test public void accepts() { ctx.registerService(AssetRenditionsDownloadOrchestrator.class, new AssetRenditionsZipperImpl()); AssetRenditionsZipperImpl zipper = (AssetRenditionsZipperImpl) ctx.getService(AssetRenditionsDownloadOrchestrator.class); ctx.request().setQueryString(AssetRenditionsDownloadOrchestrator.REQUEST_PARAMETER_NAME + "=" + AssetRenditionsZipperImpl.NAME); assertTrue(zipper.accepts(ctx.request(), Collections.emptyList(), Collections.emptyList())); }
### Question: MetadataImpl extends AbstractEmptyTextComponent implements Metadata { @Override public String getFormat() { if (type == null) { getType(); } switch (type) { case DATE: return formatDate; case NUMBER: return formatNumber; default: return null; } } @PostConstruct void init(); @Override DataType getType(); @Override String getLocale(); @Override String getFormat(); @Override ValueMap getProperties(); @Override AssetModel getAsset(); @Override String getPropertyName(); @Override boolean isEmpty(); @Override boolean isReady(); @Nonnull @Override String getExportedType(); }### Answer: @Test public void getFormat_Date() { final String expected = "yyyy-MM-dd"; ctx.currentResource("/content/date"); final Metadata metadata = ctx.request().adaptTo(Metadata.class); assertEquals(expected, metadata.getFormat()); } @Test public void getFormat_Number() { final String expected = "#.###"; ctx.currentResource("/content/number"); final Metadata metadata = ctx.request().adaptTo(Metadata.class); assertEquals(expected, metadata.getFormat()); } @Test public void getFormat() { ctx.currentResource("/content/metadata"); final Metadata metadata = ctx.request().adaptTo(Metadata.class); assertNull(metadata.getFormat()); }
### Question: AssetRenditionsZipperImpl implements AssetRenditionsDownloadOrchestrator { protected String getFileName(final ValueMap properties) { String fileName = properties.get(PN_FILE_NAME, StringUtils.defaultString(cfg.file_name(), DEFAULT_FILE_ATTACHMENT_NAME)); if (!StringUtils.endsWith(fileName, ZIP_EXTENSION)) { fileName += ZIP_EXTENSION; } return fileName; } @Override void execute(final SlingHttpServletRequest request, final SlingHttpServletResponse response, final List<AssetModel> assets, final List<String> renditionNames); @Override boolean accepts(SlingHttpServletRequest request, List<AssetModel> assets, List<String> renditionNames); static final String NAME; static final String VAR_ASSET_NAME; static final String VAR_ASSET_EXTENSION; static final String VAR_RENDITION_NAME; static final String VAR_RENDITION_EXTENSION; static final String VAR_ASSET_FILE_NAME; static final String VAR_ASSET_TITLE; static final String ZIP_EXTENSION; static final String DEFAULT_NO_CONTENT_FILE_NAME; static final String DEFAULT_NO_CONTENT_MESSAGE; }### Answer: @Test public void getFileName_FromResource() { final String expected = "My Assets.zip"; ctx.registerInjectActivateService(new AssetRenditionsZipperImpl(), "file.name", "OSGi value"); AssetRenditionsZipperImpl zipper = (AssetRenditionsZipperImpl) ctx.getService(AssetRenditionsDownloadOrchestrator.class); assertEquals(expected, zipper.getFileName(new ValueMapDecorator(ImmutableMap.of("fileName", "My Assets")))); } @Test public void getFileName_FromOSGiConfig() { final String expected = "Test Assets.zip"; ctx.registerInjectActivateService(new AssetRenditionsZipperImpl(), "file.name", expected); AssetRenditionsZipperImpl zipper = (AssetRenditionsZipperImpl) ctx.getService(AssetRenditionsDownloadOrchestrator.class); assertEquals(expected, zipper.getFileName(new ValueMapDecorator(Collections.emptyMap()))); } @Test public void getFileName_Default() { final String expected = "Assets.zip"; ctx.registerInjectActivateService(new AssetRenditionsZipperImpl()); AssetRenditionsZipperImpl zipper = (AssetRenditionsZipperImpl) ctx.getService(AssetRenditionsDownloadOrchestrator.class); assertEquals(expected, zipper.getFileName(new ValueMapDecorator(Collections.emptyMap()))); }
### Question: AssetRenditionsZipperImpl implements AssetRenditionsDownloadOrchestrator { protected void checkForMaxSize(long size) throws AssetRenditionsException { if (cfg.max_size() >= 0 && size > cfg.max_size() * BYTES_IN_MB) { throw new AssetRenditionsException("Selected assets exceed maximum allows size."); } } @Override void execute(final SlingHttpServletRequest request, final SlingHttpServletResponse response, final List<AssetModel> assets, final List<String> renditionNames); @Override boolean accepts(SlingHttpServletRequest request, List<AssetModel> assets, List<String> renditionNames); static final String NAME; static final String VAR_ASSET_NAME; static final String VAR_ASSET_EXTENSION; static final String VAR_RENDITION_NAME; static final String VAR_RENDITION_EXTENSION; static final String VAR_ASSET_FILE_NAME; static final String VAR_ASSET_TITLE; static final String ZIP_EXTENSION; static final String DEFAULT_NO_CONTENT_FILE_NAME; static final String DEFAULT_NO_CONTENT_MESSAGE; }### Answer: @Test public void checkForMaxSize_Under() throws AssetRenditionsException { final String expected = "Test Assets.zip"; ctx.registerInjectActivateService(new AssetRenditionsZipperImpl(), "max.size", 10000); AssetRenditionsZipperImpl zipper = (AssetRenditionsZipperImpl) ctx.getService(AssetRenditionsDownloadOrchestrator.class); zipper.checkForMaxSize(200); assertTrue( "Exception should not be throw", true); } @Test(expected = AssetRenditionsException.class) public void checkForMaxSize_Over() throws AssetRenditionsException { final String expected = "Test Assets.zip"; ctx.registerInjectActivateService(new AssetRenditionsZipperImpl(), "max.size", 10000); AssetRenditionsZipperImpl zipper = (AssetRenditionsZipperImpl) ctx.getService(AssetRenditionsDownloadOrchestrator.class); zipper.checkForMaxSize((10000 * 1024) + 100); assertTrue( "Exception should not be throw", true); }
### Question: AssetRenditionsZipperImpl implements AssetRenditionsDownloadOrchestrator { protected String getZipEntryName(final String folderName, final AssetModel asset, final String renditionName, final String responseContentType, final Set<String> zipEntryFileNames) { final String extension = mimeTypeService.getExtension(responseContentType); final Map<String, String> variables = new HashMap<>(); variables.put(VAR_ASSET_FILE_NAME, asset.getName()); variables.put(VAR_ASSET_NAME, StringUtils.substringBeforeLast(asset.getName(), ".")); variables.put(VAR_ASSET_TITLE, asset.getTitle()); variables.put(VAR_ASSET_EXTENSION, StringUtils.substringAfterLast(asset.getName(), ".")); variables.put(VAR_RENDITION_NAME, renditionName); variables.put(VAR_RENDITION_EXTENSION, extension); String zipEntryName = StringUtils.replaceEach(cfg.rendition_filename_expression(), variables.keySet().toArray(new String[variables.keySet().size()]), variables.values().toArray(new String[variables.values().size()])); zipEntryName = generateUniqueZipEntry(zipEntryName, zipEntryFileNames); if (folderName != null) { zipEntryFileNames.add(folderName + "/" + zipEntryName); } else { zipEntryFileNames.add(zipEntryName); } return zipEntryName; } @Override void execute(final SlingHttpServletRequest request, final SlingHttpServletResponse response, final List<AssetModel> assets, final List<String> renditionNames); @Override boolean accepts(SlingHttpServletRequest request, List<AssetModel> assets, List<String> renditionNames); static final String NAME; static final String VAR_ASSET_NAME; static final String VAR_ASSET_EXTENSION; static final String VAR_RENDITION_NAME; static final String VAR_RENDITION_EXTENSION; static final String VAR_ASSET_FILE_NAME; static final String VAR_ASSET_TITLE; static final String ZIP_EXTENSION; static final String DEFAULT_NO_CONTENT_FILE_NAME; static final String DEFAULT_NO_CONTENT_MESSAGE; }### Answer: @Test public void getZipEntryName() { final String expected = "test__my-rendition.png"; ctx.registerInjectActivateService(new AssetRenditionsZipperImpl(), "rendition.filename.expression", AssetRenditionsZipperImpl.VAR_ASSET_NAME + "__" + AssetRenditionsZipperImpl.VAR_RENDITION_NAME + "." + AssetRenditionsZipperImpl.VAR_ASSET_EXTENSION ); AssetRenditionsZipperImpl zipper = (AssetRenditionsZipperImpl) ctx.getService(AssetRenditionsDownloadOrchestrator.class); AssetModel asset = modelFactory.getModelFromWrappedRequest(ctx.request(), ctx.resourceResolver().getResource("/content/dam/test.png"), AssetModel.class); final String actual = zipper.getZipEntryName("", asset, "my-rendition", "image/png", new HashSet<>()); assertEquals( expected, actual); } @Test public void getZipEntryName_GenerateUniqueZipFileNameEntry() { final String expected = "1-test__my-rendition.png"; final Set<String> zipEntryFileNames = new HashSet<>(); zipEntryFileNames.add("test__my-rendition.png"); ctx.registerInjectActivateService(new AssetRenditionsZipperImpl(), "rendition.filename.expression", AssetRenditionsZipperImpl.VAR_ASSET_NAME + "__" + AssetRenditionsZipperImpl.VAR_RENDITION_NAME + "." + AssetRenditionsZipperImpl.VAR_ASSET_EXTENSION ); AssetRenditionsZipperImpl zipper = (AssetRenditionsZipperImpl) ctx.getService(AssetRenditionsDownloadOrchestrator.class); AssetModel asset = modelFactory.getModelFromWrappedRequest(ctx.request(), ctx.resourceResolver().getResource("/content/dam/test.png"), AssetModel.class); final String actual = zipper.getZipEntryName("", asset, "my-rendition", "image/png", zipEntryFileNames); assertEquals( expected, actual); }
### Question: AssetRenditionsDownloadServlet extends SlingAllMethodsServlet implements AssetRenditionsDownloadOrchestratorManager { protected List<AssetModel> getAssets(final SlingHttpServletRequest request) { final RequestParameter[] requestParameters = request.getRequestParameters(REQ_KEY_ASSET_PATHS); if (requestParameters == null) { return EMPTY_LIST; } return Arrays.stream(requestParameters) .map(RequestParameter::getString) .map(path -> request.getResourceResolver().getResource(path)) .filter(Objects::nonNull) .map(resource -> modelFactory.getModelFromWrappedRequest(request, resource, AssetModel.class)) .filter(Objects::nonNull) .collect(Collectors.toList()); } final AssetRenditionsDownloadOrchestrator getAssetRenditionsDownloadOrchestrator(final String id); }### Answer: @Test public void getAssets() { ctx.registerInjectActivateService(new AssetRenditionsDownloadServlet()); AssetRenditionsDownloadServlet servlet = (AssetRenditionsDownloadServlet) ctx.getService(Servlet.class); ctx.request().setQueryString("path=/content/dam/test.png&path=/content/dam/test-2.png&path=/content/dam/test-3.png"); List<com.adobe.aem.commons.assetshare.content.AssetModel> actual = servlet.getAssets(ctx.request()); assertEquals(1, actual.size()); assertEquals("/content/dam/test.png", actual.get(0).getPath()); }
### Question: AssetRenditionsDownloadServlet extends SlingAllMethodsServlet implements AssetRenditionsDownloadOrchestratorManager { protected List<String> getRenditionNames(final SlingHttpServletRequest request) { final String[] allowedRenditionNames = request.getResource().getValueMap().get(PN_ALLOWED_RENDITION_NAMES, new String[]{}); if (allowedRenditionNames == null) { return EMPTY_LIST; } final RequestParameter[] requestParameters = request.getRequestParameters(REQ_KEY_RENDITION_NAMES); if (requestParameters != null) { return Arrays.stream(requestParameters).map(RequestParameter::getString) .filter(renditionName -> allowedRenditionNames.length == 0 || ArrayUtils.contains(allowedRenditionNames, renditionName)) .distinct() .collect(Collectors.toList()); } else { return emptyList(); } } final AssetRenditionsDownloadOrchestrator getAssetRenditionsDownloadOrchestrator(final String id); }### Answer: @Test public void getRenditionNames() { ctx.registerInjectActivateService(new AssetRenditionsDownloadServlet()); AssetRenditionsDownloadServlet servlet = (AssetRenditionsDownloadServlet) ctx.getService(Servlet.class); ctx.currentResource("/content/allowed-rendition-names"); ctx.request().setQueryString("renditionName=one&renditionName=four"); List<String> actual = servlet.getRenditionNames(ctx.request()); assertEquals(1, actual.size()); assertEquals("one", actual.get(0)); }
### Question: AssetRenditionsDownloadServlet extends SlingAllMethodsServlet implements AssetRenditionsDownloadOrchestratorManager { @Override protected final void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { servletHelper.addSlingBindings(request, response); final List<String> renditionNames = getRenditionNames(request); final List<AssetModel> assets = getAssets(request); final String id = getAssetRenditionsDownloadOrchestratorId(request); final AssetRenditionsDownloadOrchestrator orchestrator = getAssetRenditionsDownloadOrchestrator(id); if (orchestrator == null) { log.warn("Invalid AssetRenditionsDownloadOrchestrator ID [ {} ]", id); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { orchestrator.execute(request, response, assets, renditionNames); } catch (AssetRenditionsException e) { throw new ServletException(e); } } final AssetRenditionsDownloadOrchestrator getAssetRenditionsDownloadOrchestrator(final String id); }### Answer: @Test public void doPost() throws ServletException, IOException { final byte[] expectedOutputStream = IOUtils.toByteArray(this.getClass().getResourceAsStream("AssetRenditionsDownloadServletTest__original.png")); doAnswer(invocation -> { Object[] args = invocation.getArguments(); ((AssetRenditionDownloadResponse) args[1]).getOutputStream().write(expectedOutputStream); return null; }).when(requestDispatcher).include(any(SlingHttpServletRequest.class), any(SlingHttpServletResponse.class)); ctx.registerInjectActivateService(new AssetRenditionsDownloadServlet()); AssetRenditionsDownloadServlet servlet = (AssetRenditionsDownloadServlet) ctx.getService(Servlet.class); ctx.currentResource("/content/download-servlet"); ctx.request().setMethod("POST"); ctx.requestPathInfo().setResourcePath("/content/download-servlet"); ctx.requestPathInfo().setSelectorString("asset-renditions-download"); ctx.requestPathInfo().setExtension("zip"); ctx.request().setQueryString("path=/content/dam/test.png&renditionName=test"); servlet.service(ctx.request(), ctx.response()); assertEquals("application/zip", ctx.response().getContentType()); assertEquals(334, ctx.response().getOutput().length); }
### Question: AssetRenditionDownloadResponse extends BufferedSlingHttpServletResponse { public ByteArrayOutputStream getByteArrayOutputStream() { return this.baos; } AssetRenditionDownloadResponse(SlingHttpServletResponse wrappedResponse, StringWriter writer, ByteArrayOutputStream outputStream); boolean isRedirect(); String getRedirect(); @Override void sendRedirect(String location); @Override void setStatus(int statusCode); @Override void setHeader(String key, String value); @Override void sendError(int statusCode); @Override void sendError(int statusCode, String msg); ByteArrayOutputStream getByteArrayOutputStream(); int getStatusCode(); @Override String getContentType(); @Override void setContentLength(int contentLength); }### Answer: @Test public void getByteArrayOutputStream() { baos.write(100); AssetRenditionDownloadResponse response = new AssetRenditionDownloadResponse(ctx.response(), stringWriter, baos); assertEquals(baos, response.getByteArrayOutputStream()); }
### Question: AssetRenditionDownloadResponse extends BufferedSlingHttpServletResponse { @Override public String getContentType() { return StringUtils.defaultIfEmpty(contentType, super.getContentType()); } AssetRenditionDownloadResponse(SlingHttpServletResponse wrappedResponse, StringWriter writer, ByteArrayOutputStream outputStream); boolean isRedirect(); String getRedirect(); @Override void sendRedirect(String location); @Override void setStatus(int statusCode); @Override void setHeader(String key, String value); @Override void sendError(int statusCode); @Override void sendError(int statusCode, String msg); ByteArrayOutputStream getByteArrayOutputStream(); int getStatusCode(); @Override String getContentType(); @Override void setContentLength(int contentLength); }### Answer: @Test public void getContentType() { AssetRenditionDownloadResponse response = new AssetRenditionDownloadResponse(ctx.response(), stringWriter, baos); response.setHeader("Content-Type", "application/test"); assertEquals("application/test", response.getContentType()); }
### Question: AssetRenditionDownloadRequest extends SlingHttpServletRequestWrapper { @Override public Object getAttribute(String name) { if (SlingBindings.class.getName().equals(name)) { return bindings; } else { return super.getAttribute(name); } } AssetRenditionDownloadRequest(final SlingHttpServletRequest wrappedRequest, final String method, final Resource resource, final String[] selectors, final String extension, final String suffix); @Override Object getAttribute(String name); @Override Resource getResource(); @Override String getMethod(); @Override RequestPathInfo getRequestPathInfo(); }### Answer: @Test public void getAttribute() { final SlingHttpServletRequest request = new AssetRenditionDownloadRequest( ctx.request(), "GET", resource, new String[]{}, "html", "/my/suffix"); SlingBindings actual = (SlingBindings) request.getAttribute(SlingBindings.class.getName()); assertEquals(resource, actual.get(SlingBindings.RESOURCE)); assertEquals(ctx.resourceResolver(), actual.get(SlingBindings.RESOLVER)); assertNull(actual.get("not-sling-bindings")); }
### Question: AssetRenditionDownloadRequest extends SlingHttpServletRequestWrapper { @Override public Resource getResource() { return resource; } AssetRenditionDownloadRequest(final SlingHttpServletRequest wrappedRequest, final String method, final Resource resource, final String[] selectors, final String extension, final String suffix); @Override Object getAttribute(String name); @Override Resource getResource(); @Override String getMethod(); @Override RequestPathInfo getRequestPathInfo(); }### Answer: @Test public void getResource() { final Resource expected = resource; final SlingHttpServletRequest request = new AssetRenditionDownloadRequest( ctx.request(), "GET", expected, new String[]{}, "html", "/my/suffix"); final Resource actual = request.getResource(); assertEquals(expected, actual); }
### Question: AssetRenditionDownloadRequest extends SlingHttpServletRequestWrapper { @Override public String getMethod() { return method; } AssetRenditionDownloadRequest(final SlingHttpServletRequest wrappedRequest, final String method, final Resource resource, final String[] selectors, final String extension, final String suffix); @Override Object getAttribute(String name); @Override Resource getResource(); @Override String getMethod(); @Override RequestPathInfo getRequestPathInfo(); }### Answer: @Test public void getMethod() { final String expected = "HEAD"; final SlingHttpServletRequest request = new AssetRenditionDownloadRequest( ctx.request(), expected, resource, new String[]{}, "html", "/my/suffix"); final String actual = request.getMethod(); assertEquals(expected, actual); }
### Question: AssetRenditionDownloadRequest extends SlingHttpServletRequestWrapper { @Override public RequestPathInfo getRequestPathInfo() { return new RequestPathInfo() { @Nonnull @Override public String getResourcePath() { return getResource().getPath(); } @CheckForNull @Override public String getExtension() { return extension; } @CheckForNull @Override public String getSelectorString() { return StringUtils.join(selectors, "."); } @Nonnull @Override public String[] getSelectors() { return selectors; } @CheckForNull @Override public String getSuffix() { return suffix; } @CheckForNull @Override public Resource getSuffixResource() { return getResource().getResourceResolver().getResource(getSuffix()); } }; } AssetRenditionDownloadRequest(final SlingHttpServletRequest wrappedRequest, final String method, final Resource resource, final String[] selectors, final String extension, final String suffix); @Override Object getAttribute(String name); @Override Resource getResource(); @Override String getMethod(); @Override RequestPathInfo getRequestPathInfo(); }### Answer: @Test public void getRequestPathInfo() { final String expectedResourcePath = "/content/test"; final String expectedSuffix = "/content/my/suffix"; final String expectedExtension = "html"; final String[] expectedSelectors = new String[]{"foo", "bar"}; final String expectedSelectorString = StringUtils.join(expectedSelectors, "."); final Resource expectedSuffixResource = ctx.create().resource(expectedSuffix); final SlingHttpServletRequest request = new AssetRenditionDownloadRequest( ctx.request(), "GET", resource, expectedSelectors, expectedExtension, expectedSuffix); RequestPathInfo actual = request.getRequestPathInfo(); assertEquals(expectedResourcePath, actual.getResourcePath()); assertArrayEquals(expectedSelectors, actual.getSelectors()); assertEquals(expectedSelectorString, actual.getSelectorString()); assertEquals(expectedExtension, actual.getExtension()); assertEquals(expectedSuffix, actual.getSuffix()); assertEquals(expectedSuffixResource.getPath(), actual.getSuffixResource().getPath()); }