method2testcases
stringlengths
118
3.08k
### Question: SunConventionsProfile extends ProfileDefinition { public RulesProfile createProfile(ValidationMessages messages) { return xmlProfileParser.parseResource(getClass().getClassLoader(), "org/sonar/plugins/ideainspections/profile-sun-conventions.xml", messages); } SunConventionsProfile(XMLProfileParser xmlProfileParser); RulesProfile createProfile(ValidationMessages messages); }### Answer: @Test public void shouldCreateProfile() { ProfileDefinition definition = new SunConventionsProfile(new XMLProfileParser(newRuleFinder())); ValidationMessages validation = ValidationMessages.create(); RulesProfile sunProfile = definition.createProfile(validation); assertThat(sunProfile.getActiveRulesByRepository(IdeaConstants.REPOSITORY_KEY).size(), greaterThan(1)); assertThat(validation.hasErrors(), Is.is(false)); }
### Question: IdeaPlugin implements Plugin { public List getExtensions() { return Arrays.asList(IdeaSensor.class, IdeaConfiguration.class, IdeaExecutor.class, IdeaAuditListener.class, IdeaProfileExporter.class, IdeaImporter.class, IdeaRepository.class, SonarWayProfile.class, SunConventionsProfile.class, SonarWayWithFindbugsProfile.class); } String getKey(); String getName(); String getDescription(); List getExtensions(); }### Answer: @Test public void getSonarWayProfileDefinition() { IdeaPlugin plugin = new IdeaPlugin(); assertThat(plugin.getExtensions().size(), greaterThan(1)); }
### Question: SonarWayProfile extends ProfileDefinition { public RulesProfile createProfile(ValidationMessages messages) { return xmlProfileParser.parseResource(getClass().getClassLoader(), "org/sonar/plugins/ideainspections/profile-sonar-way.xml", messages); } SonarWayProfile(XMLProfileParser xmlProfileParser); RulesProfile createProfile(ValidationMessages messages); }### Answer: @Test public void shouldCreateProfile() { ProfileDefinition sonarWay = new SonarWayProfile(new XMLProfileParser(newRuleFinder())); ValidationMessages validation = ValidationMessages.create(); RulesProfile profile = sonarWay.createProfile(validation); assertThat(profile.getActiveRulesByRepository(IdeaConstants.REPOSITORY_KEY).size(), greaterThan(1)); assertThat(validation.hasErrors(), is(false)); }
### Question: IdeaReportParser { public Collection<Violation> getViolations() { return violations; } IdeaReportParser(File reportDir); Collection<Violation> getViolations(); void parseAll(); }### Answer: @Test public void testGetViolations() { IdeaReportParser parser = new IdeaReportParser(TestUtils.getResource(REPORT_DIR)); parser.parseAll(); Collection<IdeaReportParser.Violation> violations = parser.getViolations(); assertThat(violations.size(), is(13)); IdeaReportParser.Violation violation = violations.iterator().next(); assertThat(violation.getType(), is("RedundantCast")); assertThat(violation.getDescription(), is("Casting <code>t.tree</code> to <code>Node</code> is redundant")); assertThat(violation.getLine(), is(467)); assertThat(violation.getSonarJavaFileKey(), is("elg.conj.C")); assertThat(violation.getSourcePath(), is("target/generated-sources/antlr3/elg/conj/C.java")); assertThat(violation.getModule(), is("conj")); }
### Question: SonarWayWithFindbugsProfile extends ProfileDefinition { @Override public RulesProfile createProfile(ValidationMessages validationMessages) { RulesProfile profile = sonarWay.createProfile(validationMessages); profile.setName(RulesProfile.SONAR_WAY_FINDBUGS_NAME); return profile; } SonarWayWithFindbugsProfile(SonarWayProfile sonarWay); @Override RulesProfile createProfile(ValidationMessages validationMessages); }### Answer: @Test public void shouldBeSameAsSonarWay() { RuleFinder ruleFinder = newRuleFinder(); SonarWayProfile sonarWay = new SonarWayProfile(new XMLProfileParser(ruleFinder)); RulesProfile withoutFindbugs = sonarWay.createProfile(ValidationMessages.create()); RulesProfile withFindbugs = new SonarWayWithFindbugsProfile(sonarWay).createProfile(ValidationMessages.create()); assertThat(withFindbugs.getActiveRules().size(), is(withoutFindbugs.getActiveRules().size())); assertThat(withFindbugs.getName(), is(RulesProfile.SONAR_WAY_FINDBUGS_NAME)); }
### Question: ClassConverterFactory implements TypeConverterFactory<String, Class> { @Override public TypeConverter<String, Class> createTypeConverter() { return value -> { try { return ClassUtil.forName(value.trim(), ClassConverterFactory.class); } catch (ClassNotFoundException e) { throw new TypeConverterException("Failed to decode '" + value + "' as a Java Class.", e); } }; } @Override TypeConverter<String, Class> createTypeConverter(); @Override TypeConverterDescriptor<Class<String>, Class<Class>> getTypeConverterDescriptor(); }### Answer: @Test public void test() { ClassConverterFactory classConverterFactory = new ClassConverterFactory(); assertEquals(String.class, classConverterFactory.createTypeConverter().convert(String.class.getName())); }
### Question: IntegerToStringConverterFactory implements TypeConverterFactory<Integer, String> { @Override public TypeConverter<Integer, String> createTypeConverter() { return new NumberToStringConverter<>(); } @Override TypeConverter<Integer, String> createTypeConverter(); @Override TypeConverterDescriptor<Class<Integer>, Class<String>> getTypeConverterDescriptor(); }### Answer: @Test public void test_encode_format_config() { IntegerToStringConverterFactory integerToStringConverterFactory = new IntegerToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.FORMAT, "#,###.##"); TypeConverter<Integer, String> typeConverter = integerToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1,234", typeConverter.convert(1234)); } @Test public void test_encode_locale_config() { IntegerToStringConverterFactory integerToStringConverterFactory = new IntegerToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.LOCALE, "de-DE"); TypeConverter<Integer, String> typeConverter = integerToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1234", typeConverter.convert(1234)); }
### Question: ShortToStringConverterFactory implements TypeConverterFactory<Short, String> { @Override public TypeConverter<Short, String> createTypeConverter() { return new NumberToStringConverter<>(); } @Override TypeConverter<Short, String> createTypeConverter(); @Override TypeConverterDescriptor<Class<Short>, Class<String>> getTypeConverterDescriptor(); }### Answer: @Test public void test_encode_format_config() { ShortToStringConverterFactory shortToStringConverterFactory = new ShortToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.FORMAT, "#,###.##"); TypeConverter<Short, String> typeConverter = shortToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1,234", typeConverter.convert((short) 1234)); } @Test public void test_encode_locale_config() { ShortToStringConverterFactory shortToStringConverterFactory = new ShortToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.LOCALE, "de-DE"); TypeConverter<Short, String> typeConverter = shortToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1234", typeConverter.convert((short)1234)); }
### Question: LongToStringConverterFactory implements TypeConverterFactory<Long, String> { @Override public TypeConverter<Long, String> createTypeConverter() { return new NumberToStringConverter<>(); } @Override TypeConverter<Long, String> createTypeConverter(); @Override TypeConverterDescriptor<Class<Long>, Class<String>> getTypeConverterDescriptor(); }### Answer: @Test public void test_encode_format_config() { LongToStringConverterFactory longToStringConverterFactory = new LongToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.FORMAT, "#,###.##"); TypeConverter<Long, String> typeConverter = longToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1,234", typeConverter.convert(1234L)); } @Test public void test_encode_locale_config() { LongToStringConverterFactory longToStringConverterFactory = new LongToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.LOCALE, "de-DE"); TypeConverter<Long, String> typeConverter = longToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1234", typeConverter.convert(1234L)); }
### Question: BigIntegerToStringConverterFactory implements TypeConverterFactory<BigInteger, String> { @Override public TypeConverter<BigInteger, String> createTypeConverter() { return new NumberToStringConverter<>(); } @Override TypeConverter<BigInteger, String> createTypeConverter(); @Override TypeConverterDescriptor<Class<BigInteger>, Class<String>> getTypeConverterDescriptor(); }### Answer: @Test public void test_encode_format_config() { BigIntegerToStringConverterFactory bigIntegerToStringConverterFactory = new BigIntegerToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.FORMAT, "#,###.##"); TypeConverter<BigInteger, String> typeConverter = bigIntegerToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1,234", typeConverter.convert(new BigInteger("1234"))); } @Test public void test_encode_locale_config() { BigIntegerToStringConverterFactory bigIntegerToStringConverterFactory = new BigIntegerToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.LOCALE, "de-DE"); TypeConverter<BigInteger, String> typeConverter = bigIntegerToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1234", typeConverter.convert(new BigInteger("1234"))); }
### Question: DoubleToStringConverterFactory implements TypeConverterFactory<Double, String> { @Override public TypeConverter<Double, String> createTypeConverter() { return new NumberToStringConverter<>(); } @Override TypeConverter<Double, String> createTypeConverter(); @Override TypeConverterDescriptor<Class<Double>, Class<String>> getTypeConverterDescriptor(); }### Answer: @Test public void test_encode_format_config() { DoubleToStringConverterFactory doubleToStringConverterFactory = new DoubleToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.FORMAT, "#,###.##"); TypeConverter<Double, String> typeConverter = doubleToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1,234.45", typeConverter.convert(1234.45d)); } @Test public void test_encode_locale_config() { DoubleToStringConverterFactory doubleToStringConverterFactory = new DoubleToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.LOCALE, "de-DE"); TypeConverter<Double, String> typeConverter = doubleToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1234,45", typeConverter.convert(1234.45d)); }
### Question: BigDecimalToStringConverterFactory implements TypeConverterFactory<BigDecimal, String> { @Override public TypeConverter<BigDecimal, String> createTypeConverter() { return new NumberToStringConverter<>(); } @Override TypeConverter<BigDecimal, String> createTypeConverter(); @Override TypeConverterDescriptor<Class<BigDecimal>, Class<String>> getTypeConverterDescriptor(); }### Answer: @Test public void test_encode_format_config() { BigDecimalToStringConverterFactory bigDecimalToStringConverterFactory = new BigDecimalToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.FORMAT, "#,###.##"); TypeConverter<BigDecimal, String> typeConverter = bigDecimalToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1,234.45", typeConverter.convert(new BigDecimal("1234.45"))); } @Test public void test_encode_locale_config() { BigDecimalToStringConverterFactory bigDecimalToStringConverterFactory = new BigDecimalToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.LOCALE, "de-DE"); TypeConverter<BigDecimal, String> typeConverter = bigDecimalToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1234,45", typeConverter.convert(new BigDecimal("1234.45"))); }
### Question: SqlTimeConverterFactory implements TypeConverterFactory<String, Time> { @Override public TypeConverter<String, Time> createTypeConverter() { return new SqlTimeTypeConverter(); } @Override TypeConverter<String, Time> createTypeConverter(); @Override TypeConverterDescriptor<Class<String>, Class<Time>> getTypeConverterDescriptor(); }### Answer: @Test public void test_DateDecoder() { Properties config = new Properties(); config.setProperty(DateToStringLocaleAwareConverter.FORMAT, "EEE MMM dd HH:mm:ss z yyyy"); SqlTimeConverterFactory sqlTimeConverterFactory = new SqlTimeConverterFactory(); config.setProperty(DateToStringLocaleAwareConverter.LOCALE_LANGUAGE_CODE, "en"); config.setProperty(DateToStringLocaleAwareConverter.LOCALE_COUNTRY_CODE, "IE"); TypeConverter<String, Time> typeConverter = sqlTimeConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); Object object = typeConverter.convert("Wed Nov 15 13:45:28 EST 2006"); assertTrue(object instanceof Time); Time time_a = typeConverter.convert("Wed Nov 15 13:45:28 EST 2006"); assertEquals(1163616328000L, time_a.getTime()); Time date_b = typeConverter.convert("Wed Nov 15 13:45:28 EST 2006"); assertNotSame(time_a, date_b); }
### Question: CharsetConverterFactory implements TypeConverterFactory<String, Charset> { @Override public TypeConverter<String, Charset> createTypeConverter() { return value -> { try { return Charset.forName(value); } catch (UnsupportedCharsetException e) { throw new TypeConverterException("Unsupported character set '" + value + "'."); } }; } @Override TypeConverter<String, Charset> createTypeConverter(); @Override TypeConverterDescriptor<Class<String>, Class<Charset>> getTypeConverterDescriptor(); }### Answer: @Test public void test_CharsetDecoder() { new CharsetConverterFactory().createTypeConverter().convert("UTF-8"); try { new CharsetConverterFactory().createTypeConverter().convert("XXXXXX"); } catch(TypeConverterException e) { assertEquals("Unsupported character set 'XXXXXX'.", e.getMessage()); } }
### Question: Smooks { public ApplicationContext getApplicationContext() { return applicationContext; } Smooks(); Smooks(StandaloneApplicationContext applicationContext); Smooks(String resourceURI); Smooks(InputStream resourceConfigStream); ClassLoader getClassLoader(); void setClassLoader(ClassLoader classLoader); void setFilterSettings(FilterSettings filterSettings); Smooks setExports(Exports exports); void setReaderConfig(ReaderConfigurator readerConfigurator); void setNamespaces(Properties namespaces); SmooksResourceConfiguration addVisitor(Visitor visitor); SmooksResourceConfiguration addVisitor(Visitor visitor, String targetSelector); SmooksResourceConfiguration addVisitor(Visitor visitor, String targetSelector, String targetSelectorNS); void addVisitors(VisitorAppender visitorAppender); void addConfiguration(SmooksResourceConfiguration resourceConfig); void addConfigurations(String resourceURI); void addConfigurations(String baseURI, InputStream resourceConfigStream); void addConfigurations(InputStream resourceConfigStream); ExecutionContext createExecutionContext(); ExecutionContext createExecutionContext(String targetProfile); void filterSource(Source source); void filterSource(Source source, Result... results); void filterSource(ExecutionContext executionContext, Source source, Result... results); ApplicationContext getApplicationContext(); void close(); }### Answer: @Test public void test_setResourceLocator() throws IOException, SAXException { Smooks smooks = new Smooks("classpath:/org/smooks/test_setClassLoader_01.xml"); URIResourceLocator resourceLocator = (URIResourceLocator)smooks.getApplicationContext().getResourceLocator(); assertEquals("classpath:/org/smooks/", resourceLocator.getBaseURI().toString()); assertEquals("classpath:/org/smooks/somethingelse.xml", resourceLocator.getBaseURI().resolve("somethingelse.xml").toString()); }
### Question: AbstractOutputStreamResource implements SAXVisitBefore, DOMVisitBefore, Consumer, VisitLifecycleCleanable, ExecutionLifecycleCleanable { public abstract OutputStream getOutputStream( final ExecutionContext executionContext ) throws IOException; abstract OutputStream getOutputStream( final ExecutionContext executionContext ); String getResourceName(); boolean consumes(Object object); AbstractOutputStreamResource setResourceName(String resourceName); AbstractOutputStreamResource setWriterEncoding(Charset writerEncoding); Charset getWriterEncoding(); void visitBefore( final SAXElement element, final ExecutionContext executionContext ); void visitBefore( final Element element, final ExecutionContext executionContext ); void executeVisitLifecycleCleanup(Fragment fragment, ExecutionContext executionContext); void executeExecutionLifecycleCleanup( ExecutionContext executionContext ); static OutputStream getOutputStream( final String resourceName, final ExecutionContext executionContext); static Writer getOutputWriter(final String resourceName, final ExecutionContext executionContext); }### Answer: @Test public void getOutputStream () throws IOException { AbstractOutputStreamResource resource = new MockAbstractOutputStreamResource(); MockExecutionContext executionContext = new MockExecutionContext(); assertNull(getResource(resource, executionContext)); resource.visitBefore( (Element)null, executionContext ); assertNotNull(getResource(resource, executionContext)); OutputStream outputStream = AbstractOutputStreamResource.getOutputStream( resource.getResourceName(), executionContext); assertNotNull( outputStream ); assertTrue( outputStream instanceof ByteArrayOutputStream ); try { AbstractOutputStreamResource.getOutputWriter( resource.getResourceName(), executionContext); fail("Expected SmooksException"); } catch(SmooksException e) { assertEquals("An OutputStream to the 'Mock' resource is already open. Cannot open a Writer to this resource now!", e.getMessage()); } resource.executeVisitLifecycleCleanup(new Fragment((Element)null), executionContext); assertNull(getResource(resource, executionContext)); assertTrue(MockAbstractOutputStreamResource.isClosed); }
### Question: SmooksResourceConfigurationSortComparator implements Comparator { public int compare(Object configObj1, Object configObj2) { SmooksResourceConfiguration config1 = (SmooksResourceConfiguration)configObj1; SmooksResourceConfiguration config = (SmooksResourceConfiguration)configObj2; if(config1 == config) { return 0; } double config1Specificity = getSpecificity(config1); double config2Specificity = getSpecificity(config); if(config1Specificity > config2Specificity) { return -1; } else if(config1Specificity < config2Specificity) { return 1; } else { return 0; } } SmooksResourceConfigurationSortComparator(ProfileSet profileSet); int compare(Object configObj1, Object configObj2); }### Answer: @Test public void test_compare() { SmooksResourceConfigurationSortComparator sortComparator = new SmooksResourceConfigurationSortComparator(profileSet); SmooksResourceConfiguration config1; SmooksResourceConfiguration config2; config1 = new SmooksResourceConfiguration("selector", "http: assertEquals(0, sortComparator.compare(config1, config1)); config1 = new SmooksResourceConfiguration("selector", "http: config2 = new SmooksResourceConfiguration("selector", "http: assertEquals(0, sortComparator.compare(config1, config2)); config1 = new SmooksResourceConfiguration("selector", "http: config2 = new SmooksResourceConfiguration("selector", "http: assertEquals(-1, sortComparator.compare(config1, config2)); config1 = new SmooksResourceConfiguration("selector", "http: config2 = new SmooksResourceConfiguration("selector", "http: assertEquals(1, sortComparator.compare(config1, config2)); }
### Question: PropertyListParameterDecoder extends ParameterDecoder<String> { public Object decodeValue(String value) throws ParameterDecodeException { Properties properties = new Properties(); try { properties.load(new ByteArrayInputStream(value.getBytes(StandardCharsets.UTF_8))); } catch (UnsupportedEncodingException e) { throw new ParameterDecodeException("Unexpected error. 'UTF-8' is not a supported character encoding.", e); } catch (IOException e) { throw new ParameterDecodeException("Unexpected error. Unable to read ByteArrayInputStream based stream.", e); } return properties; } Object decodeValue(String value); }### Answer: @Test public void test_decodeValue() { SmooksResourceConfiguration config = new SmooksResourceConfiguration("x", "x"); MockApplicationContext mockApplicationContext = new MockApplicationContext(); PropertyListParameterDecoder propertyListParameterDecoder = new PropertyListParameterDecoder(); mockApplicationContext.getRegistry().lookup(new LifecycleManagerLookup()).applyPhase(propertyListParameterDecoder, new PostConstructLifecyclePhase(new Scope(mockApplicationContext.getRegistry(), config, propertyListParameterDecoder))); Properties properties = (Properties) propertyListParameterDecoder.decodeValue("x=111\ny=222"); assertEquals(2, properties.size()); assertEquals("111", properties.getProperty("x")); assertEquals("222", properties.getProperty("y")); }
### Question: ParameterAccessor { public static <T> T getParameterValue(String name, Class<T> valueClass, ContentDeliveryConfig config) { Parameter<T> param = getParameter(name, valueClass, config); if(param != null) { return param.getValue(); } return null; } static T getParameterValue(String name, Class<T> valueClass, ContentDeliveryConfig config); static T getParameterValue(String name, Class<T> valueClass, T defaultVal, ContentDeliveryConfig config); static Parameter<T> getParameter(String name, Class<T> valueType, ContentDeliveryConfig config); static Parameter<T> getParameter(String name, Class<T> valueType, Map<String, List<SmooksResourceConfiguration>> resourceConfigurations); static T getParameterValue(String name, Class<T> valueType, T defaultVal, Map<String, List<SmooksResourceConfiguration>> config); static T getParameterValue(String name, Class<T> valueType, Map<String, List<SmooksResourceConfiguration>> resourceConfigurations); static void setParameter(String name, Object value, Smooks smooks); static void removeParameter(String name, Smooks smooks); static final String GLOBAL_PARAMETERS; }### Answer: @Test public void test_system_property() { Smooks smooks = new Smooks(); ContentDeliveryConfig deliveryConfig = smooks.createExecutionContext().getDeliveryConfig(); assertNull(ParameterAccessor.getParameterValue("test.parameter", String.class, deliveryConfig)); System.setProperty("test.parameter", "xxxxxxx"); assertEquals("xxxxxxx", ParameterAccessor.getParameterValue("test.parameter", String.class, deliveryConfig)); }
### Question: SmooksResourceConfigurationList { public String getName() { return name; } SmooksResourceConfigurationList(String name); void add(SmooksResourceConfiguration smooksResourceConfiguration); void addAll(SmooksResourceConfigurationList configList); void add(ProfileSet profileSet); String getName(); boolean isSystemConfigList(); void setSystemConfigList(boolean systemConfigList); boolean isEmpty(); int size(); SmooksResourceConfiguration get(int index); SmooksResourceConfiguration[] getTargetConfigurations(ProfileSet profileSet); List<ProfileSet> getProfiles(); List<SmooksResourceConfiguration> lookupResource(ConfigSearch searchCriteria); }### Answer: @Test public void testConstructor() { testBadArgs(null); testBadArgs(" "); SmooksResourceConfigurationList list = new SmooksResourceConfigurationList("list-name"); assertEquals("list-name", list.getName()); }
### Question: SmooksResourceConfigurationList { public void add(SmooksResourceConfiguration smooksResourceConfiguration) { AssertArgument.isNotNull(smooksResourceConfiguration, "smooksResourceConfiguration"); String[] selectors = smooksResourceConfiguration.getSelectorPath().getSelector().split(","); for(String selector : selectors) { SmooksResourceConfiguration clone = (SmooksResourceConfiguration) smooksResourceConfiguration.clone(); clone.setSelector(selector.trim()); smooksResourceConfigurations.add(clone); LOGGER.debug("Smooks ResourceConfiguration [" + clone + "] added to list [" + name + "]."); } } SmooksResourceConfigurationList(String name); void add(SmooksResourceConfiguration smooksResourceConfiguration); void addAll(SmooksResourceConfigurationList configList); void add(ProfileSet profileSet); String getName(); boolean isSystemConfigList(); void setSystemConfigList(boolean systemConfigList); boolean isEmpty(); int size(); SmooksResourceConfiguration get(int index); SmooksResourceConfiguration[] getTargetConfigurations(ProfileSet profileSet); List<ProfileSet> getProfiles(); List<SmooksResourceConfiguration> lookupResource(ConfigSearch searchCriteria); }### Answer: @Test public void testAdd() { SmooksResourceConfigurationList list = new SmooksResourceConfigurationList("list-name"); assertTrue(list.isEmpty()); list.add(new SmooksResourceConfiguration("*", "a/b.zap")); assertFalse(list.isEmpty()); assertEquals(1, list.size()); assertEquals("a/b.zap", list.get(0).getResource()); list.add(new SmooksResourceConfiguration("*", "c/d.zap")); assertEquals(2, list.size()); assertEquals("c/d.zap", list.get(1).getResource()); }
### Question: BeanMapExpressionEvaluator extends MVELExpressionEvaluator implements ExecutionContextExpressionEvaluator { public boolean eval(ExecutionContext context) throws ExpressionEvaluationException { return (Boolean) getValue(context); } BeanMapExpressionEvaluator(); BeanMapExpressionEvaluator(String expression); boolean eval(ExecutionContext context); Object getValue(ExecutionContext context); static final String MVEL_EXECUTION_CONTEXT_KEY; }### Answer: @Test public void testInvalidExpression() { try { new BeanMapExpressionEvaluator("x.y").eval(new HashMap()); fail("Expected ExpressionEvaluationException"); } catch(Exception e) { assertTrue(e instanceof ExpressionEvaluationException); } }
### Question: SmooksDOMFilter extends Filter { public void doFilter() throws SmooksException { Source source = FilterSource.getSource(executionContext); Result result; result = FilterResult.getResult(executionContext, StreamResult.class); if(result == null) { result = FilterResult.getResult(executionContext, DOMResult.class); } doFilter(source, result); } SmooksDOMFilter(ExecutionContext executionContext); void doFilter(); void cleanup(); Node filter(Source source); Node filter(Document doc); Node filter(Element element); void serialize(Node node, Writer writer); static final String DELIVERY_NODE_REQUEST_KEY; }### Answer: @Test public void doFilter_verify_that_flush_is_called() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamResult result = new StreamResult( baos ); domFilter.doFilter( new StreamSource( new ByteArrayInputStream( input ) ), result ); OutputStream outputStream = result.getOutputStream(); assertTrue( outputStream instanceof ByteArrayOutputStream ); byte[] byteArray = ((ByteArrayOutputStream)outputStream).toByteArray(); assertTrue ( byteArray.length > 0 ); }
### Question: SmooksSAXFilter extends Filter { public void doFilter() throws SmooksException { Source source = FilterSource.getSource(executionContext); Result result = FilterResult.getResult(executionContext, StreamResult.class); doFilter(source, result); } SmooksSAXFilter(ExecutionContext executionContext); void doFilter(); void cleanup(); }### Answer: @Test public void doFilter_verify_that_flush_is_called() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamResult result = new StreamResult( baos ); saxFilter.doFilter( new StreamSource( new ByteArrayInputStream( input ) ), result ); OutputStream outputStream = result.getOutputStream(); assertTrue( outputStream instanceof ByteArrayOutputStream ); byte[] byteArray = ((ByteArrayOutputStream)outputStream).toByteArray(); assertTrue ( byteArray.length > 0 ); }
### Question: SAXUtil { public static String getXPath(SAXElement element) { StringBuilder builder = new StringBuilder(); addXPathElement(element, builder); return builder.toString(); } static String getAttribute(String attributeName, Attributes attributes); static String getAttribute(String attributeName, Attributes attributes, String defaultVal); static String getAttribute(String attributeNamespace, String attributeName, Attributes attributes, String defaultVal); static String getXPath(SAXElement element); static int getDepth(SAXElement element); static QName toQName(String namespaceURI, String localName, String qName); static QName toQName(Element element); }### Answer: @Test public void test_getXPath() { SAXElement a = new SAXElement("http: SAXElement b = new SAXElement("http: SAXElement c = new SAXElement("http: assertEquals("a/b/c", SAXUtil.getXPath(c)); }
### Question: SAXUtil { public static String getAttribute(String attributeName, Attributes attributes) { return getAttribute(attributeName, attributes, ""); } static String getAttribute(String attributeName, Attributes attributes); static String getAttribute(String attributeName, Attributes attributes, String defaultVal); static String getAttribute(String attributeNamespace, String attributeName, Attributes attributes, String defaultVal); static String getXPath(SAXElement element); static int getDepth(SAXElement element); static QName toQName(String namespaceURI, String localName, String qName); static QName toQName(Element element); }### Answer: @Test public void test_getAttribute() { AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute("", "a", "", "", "1"); attributes.addAttribute("http: attributes.addAttribute("http: assertEquals("1", SAXUtil.getAttribute("a", attributes)); assertEquals("a", SAXUtil.getAttribute("http: assertEquals("b", SAXUtil.getAttribute("http: }
### Question: TerminateVisitor implements SAXVisitBefore, SAXVisitAfter, Producer { @SuppressWarnings("WeakerAccess") @Inject public TerminateVisitor setTerminateBefore(Optional<Boolean> terminateBefore) { this.terminateBefore = terminateBefore.orElse(this.terminateBefore); return this; } void visitBefore(SAXElement element, ExecutionContext executionContext); void visitAfter(SAXElement element, ExecutionContext executionContext); @SuppressWarnings("WeakerAccess") @Inject TerminateVisitor setTerminateBefore(Optional<Boolean> terminateBefore); @SuppressWarnings("unchecked") Set<?> getProducts(); }### Answer: @Test public void test_terminate_prog_before() { Smooks smooks = new Smooks(); smooks.addVisitor(new TerminateVisitor().setTerminateBefore(Optional.of(true)), "customer"); smooks.addVisitor(new SAXVisitBeforeVisitor().setInjectedParam("blah"), "user"); smooks.filterSource(new StreamSource(getClass().getResourceAsStream("order.xml"))); assertFalse(SAXVisitBeforeVisitor.visited); }
### Question: Export implements ContentHandler { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((extract == null) ? 0 : extract.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } Export(); Export(final Class<?> type); Export(final Class<?> type, final String name); Export(final Class<?> type, final String name, final String extract); @PostConstruct void addToExportsInApplicationContext(); String getName(); Class<?> getType(); String getExtract(); Set<String> getExtractSet(); @Override int hashCode(); @Override boolean equals(final Object obj); String toString(); }### Answer: @Test public void equalsIsSymetric() { Export x = new Export(String.class); Export y = new Export(String.class); assertEquals(x, y); assertEquals(y, x); assertEquals(x.hashCode(), y.hashCode()); } @Test public void equalsIsTransitive() { Export x = new Export(String.class); Export y = new Export(String.class); Export z = new Export(String.class); assertEquals(x, y); assertEquals(y, z); assertEquals(x, z); assertEquals(x.hashCode(), y.hashCode()); assertEquals(y.hashCode(), z.hashCode()); assertEquals(x.hashCode(), z.hashCode()); }
### Question: Exports implements ContentHandler { public Collection<Export> getExports() { return Collections.unmodifiableCollection(exportsMap.values()); } Exports(); Exports(final Export export); Exports(final Set<Export> exportTypes); Exports(final Class<?> resultType); Exports(final String resultType); void addExport(Export export); Collection<Export> getExports(); Set<Class<?>> getResultTypes(); boolean hasExports(); Export getExport(Class<?> type); Result[] createResults(); Collection<Export> getProducts(); static List<Object> extractResults(final Result[] results, final Exports exports); }### Answer: @Test public void createSingleExports() { Exports exports = new Exports(StringResult.class); Collection<Export> exportTypes = exports.getExports(); assertFalse(exportTypes.isEmpty()); assertEquals(exportTypes.iterator().next().getType(), StringResult.class); } @Test public void createMultipleExports() { Set<Export> results = new HashSet<Export>(); results.add(new Export(StringResult.class)); results.add(new Export(JavaResult.class)); Exports exports = new Exports(results); Collection<Export> exportTypes = exports.getExports(); assertEquals(2, exportTypes.size()); }
### Question: JavaResult extends FilterResult implements ResultExtractor<JavaResult> { public Object extractFromResult(JavaResult result, Export export) { Set<String> extractSet = export.getExtractSet(); if (extractSet == null) { return extractBeans(result, result.getResultMap().keySet()); } if(extractSet.size() == 1) { return result.getBean(extractSet.iterator().next()); } else { return extractBeans(result, extractSet); } } JavaResult(); JavaResult(boolean preserveOrder); JavaResult(Map<String, Object> resultMap); Object getBean(String name); T getBean(Class<T> beanType); Map<String, Object> getResultMap(); void setResultMap(Map<String, Object> resultMap); String toString(); Object extractFromResult(JavaResult result, Export export); }### Answer: @Test public void extractSpecificBean() { JavaResult javaResult = new JavaResult(beans); Object result = javaResult.extractFromResult(javaResult, new Export(JavaResult.class, null, "second")); assertEquals("bean2", result); } @Test public void extractSpecificBeans() { JavaResult javaResult = new JavaResult(beans); Map<String, Object> result = (Map<String, Object>) javaResult.extractFromResult(javaResult, new Export(JavaResult.class, null, "second,first")); Assert.assertTrue(result.containsKey("first")); Assert.assertTrue(result.containsKey("second")); Assert.assertFalse(result.containsKey("third")); }
### Question: SourceFactory { public Source createSource(final Object from) { Source source; if (from instanceof String) { source = new StreamSource(new StringReader((String) from)); } else if (from instanceof InputStream) { source = new StreamSource((InputStream) from); } else if (from instanceof Reader) { source = new StreamSource((Reader) from); } else if (from instanceof Node) { source = new DOMSource((Node) from); } else if (from instanceof Source) { source = (Source) from; } else if (from instanceof byte[]) { source = new StreamSource(new ByteArrayInputStream((byte[]) from)); } else { source = new JavaSource(from); } return source; } private SourceFactory(); static SourceFactory getInstance(); Source createSource(final Object from); }### Answer: @Test public void createStreamSourceStreamFromString() { Source source = factory.createSource( "testing" ); assertNotNull( source ); assertTrue( source instanceof StreamSource ); } @Test public void getSourceByteArray() { Source source = factory.createSource( "test".getBytes() ); assertNotNull( source ); assertTrue( source instanceof StreamSource ); } @Test public void getSourceReader() { Source source = factory.createSource( new StringReader( "testing" )); assertNotNull( source ); assertTrue( source instanceof StreamSource ); } @Test public void getSourceInputStream() { Source source = factory.createSource( new ByteArrayInputStream( "testing".getBytes() ) ); assertNotNull( source ); assertTrue( source instanceof StreamSource ); }
### Question: StandaloneExecutionContext implements ExecutionContext { public Hashtable<Object, Object> getAttributes() { return attributes; } StandaloneExecutionContext(String targetProfile, ApplicationContext context, List<ContentHandlerBinding<Visitor>> extendedContentHandlerBindings); StandaloneExecutionContext(String targetProfile, ApplicationContext applicationContext, String contentEncoding, List<ContentHandlerBinding<Visitor>> extendedContentHandlerBindings); void setDocumentSource(URI docSource); URI getDocumentSource(); ApplicationContext getApplicationContext(); ProfileSet getTargetProfiles(); ContentDeliveryConfig getDeliveryConfig(); void setContentEncoding(String contentEncoding); String getContentEncoding(); void setEventListener(ExecutionEventListener listener); ExecutionEventListener getEventListener(); void setTerminationError(Throwable terminationError); Throwable getTerminationError(); String getConfigParameter(String name); String getConfigParameter(String name, String defaultVal); boolean isDefaultSerializationOn(); void setAttribute(Object key, Object value); Object getAttribute(Object key); void removeAttribute(Object key); String toString(); Hashtable<Object, Object> getAttributes(); BeanContext getBeanContext(); void setBeanContext(BeanContext beanContext); }### Answer: @Test public void getAttributes() { final String key = "testKey"; final String value = "testValue"; context.setAttribute( key, value ); Hashtable attributes = context.getAttributes(); assertTrue( attributes.containsKey( key ) ); assertTrue( attributes.contains( value ) ); }
### Question: AnnotatedDaoInvoker implements DaoInvoker { public void flush() { final FlushMethod method = daoRuntimeInfo.getFlushMethod(); assertMethod(method, Flush.class); method.invoke(dao); } AnnotatedDaoInvoker(final Object dao, final AnnotatedDaoRuntimeInfo daoRuntimeInfo); void flush(); Object update(final Object entity); Object update(String name, Object entity); Object insert(final Object entity); Object insert(String name, Object entity); Object delete(final Object entity); Object delete(String name, Object entity); Object lookupByQuery(final String query, final Object ... parameters); Object lookupByQuery(final String query, final Map<String, ?> parameters); Object lookup(final String name, final Map<String, ?> parameters); Object lookup(final String name, final Object ... parameters); }### Answer: @Test public void test_flush() { DaoInvoker invoker = new AnnotatedDaoInvoker(fullDao, fullDaoRuntimeInfo); invoker.flush(); verify(fullDao).flushIt(); } @Test(groups = "unit", expectedExceptions = NoMethodWithAnnotationFoundException.class) public void test_flush_no_annotation() { DaoInvoker invoker = new AnnotatedDaoInvoker(minimumDao, minimumDaoRuntimeInfo); invoker.flush(); }
### Question: InterfaceDaoInvoker implements DaoInvoker { public Object insert(final Object obj) { if(dao == null) { throw new UnsupportedOperationException("The DAO '" + dao.getClass().getName() + "' doesn't implement the '" + Dao.class.getName() + "' interface and there for can't insert the entity."); } return dao.insert(obj); } @SuppressWarnings("unchecked") InterfaceDaoInvoker(final Object dao); Object insert(final Object obj); Object insert(String name, Object obj); Object update(final Object obj); Object update(String name, Object obj); Object delete(Object entity); Object delete(String name, Object entity); void flush(); Object lookupByQuery(final String query, final Object ... parameters); Object lookupByQuery(final String query, final Map<String, ?> parameters); Object lookup(final String name, final Object ... parameters); Object lookup(final String name, final Map<String, ?> parameters); }### Answer: @Test(groups = "unit") public void test_insert() { DaoInvoker invoker = new InterfaceDaoInvoker(fullDao); Object toPersist = new Object(); invoker.insert(toPersist); verify(fullDao).insert(same(toPersist)); } @Test public void test_insert_named() { DaoInvoker invoker = new InterfaceDaoInvoker(fullDao); Object toPersist = new Object(); invoker.insert("myInsert", toPersist); verify(fullDao).insert(eq("myInsert"), same(toPersist)); }
### Question: InterfaceDaoInvoker implements DaoInvoker { public Object update(final Object obj) { if(dao == null) { throw new UnsupportedOperationException("The DAO '" + dao.getClass().getName() + "' doesn't implement the '" + Dao.class.getName() + "' interface and there for can't insert the entity."); } return dao.update(obj); } @SuppressWarnings("unchecked") InterfaceDaoInvoker(final Object dao); Object insert(final Object obj); Object insert(String name, Object obj); Object update(final Object obj); Object update(String name, Object obj); Object delete(Object entity); Object delete(String name, Object entity); void flush(); Object lookupByQuery(final String query, final Object ... parameters); Object lookupByQuery(final String query, final Map<String, ?> parameters); Object lookup(final String name, final Object ... parameters); Object lookup(final String name, final Map<String, ?> parameters); }### Answer: @Test public void test_update() { DaoInvoker invoker = new InterfaceDaoInvoker(fullDao); Object toMerge = new Object(); invoker.update(toMerge); verify(fullDao).update(same(toMerge)); } @Test public void test_update_named() { DaoInvoker invoker = new InterfaceDaoInvoker(fullDao); Object toMerge = new Object(); invoker.update("myMerge", toMerge); verify(fullDao).update(eq("myMerge") ,same(toMerge)); }
### Question: InterfaceDaoInvoker implements DaoInvoker { public Object delete(Object entity) { if(dao == null) { throw new UnsupportedOperationException("The DAO '" + dao.getClass().getName() + "' doesn't implement the '" + Dao.class.getName() + "' interface and there for can't delete the entity."); } return dao.delete(entity); } @SuppressWarnings("unchecked") InterfaceDaoInvoker(final Object dao); Object insert(final Object obj); Object insert(String name, Object obj); Object update(final Object obj); Object update(String name, Object obj); Object delete(Object entity); Object delete(String name, Object entity); void flush(); Object lookupByQuery(final String query, final Object ... parameters); Object lookupByQuery(final String query, final Map<String, ?> parameters); Object lookup(final String name, final Object ... parameters); Object lookup(final String name, final Map<String, ?> parameters); }### Answer: @Test public void test_delete() { DaoInvoker invoker = new InterfaceDaoInvoker(fullDao); Object toDelete = new Object(); invoker.delete(toDelete); verify(fullDao).delete(same(toDelete)); } @Test public void test_delete_named() { DaoInvoker invoker = new InterfaceDaoInvoker(fullDao); Object toDelete = new Object(); invoker.delete("myDelete", toDelete); verify(fullDao).delete(eq("myDelete"), same(toDelete)); }
### Question: InterfaceDaoInvoker implements DaoInvoker { public void flush() { if(flushableDAO == null) { throw new UnsupportedOperationException("The DAO '" + dao.getClass().getName() + "' doesn't implement the '" + Flushable.class.getName() + "' interface and there for can't flush the DAO."); } flushableDAO.flush(); } @SuppressWarnings("unchecked") InterfaceDaoInvoker(final Object dao); Object insert(final Object obj); Object insert(String name, Object obj); Object update(final Object obj); Object update(String name, Object obj); Object delete(Object entity); Object delete(String name, Object entity); void flush(); Object lookupByQuery(final String query, final Object ... parameters); Object lookupByQuery(final String query, final Map<String, ?> parameters); Object lookup(final String name, final Object ... parameters); Object lookup(final String name, final Map<String, ?> parameters); }### Answer: @Test public void test_flush() { DaoInvoker invoker = new InterfaceDaoInvoker(fullDao); invoker.flush(); verify(fullDao).flush(); } @Test(expectedExceptions = UnsupportedOperationException.class) public void test_flush_non_flushable_dao() { DaoInvoker invoker = new InterfaceDaoInvoker(minimumDao); invoker.flush(); }
### Question: InterfaceDaoInvoker implements DaoInvoker { public Object lookup(final String name, final Object ... parameters) { if(finderDAO == null) { throw new UnsupportedOperationException("The DAO '" + dao.getClass().getName() + "' doesn't implement the '" + Locator.class.getName() + "' interface and there for can't find by query."); } return finderDAO.lookup(name, parameters); } @SuppressWarnings("unchecked") InterfaceDaoInvoker(final Object dao); Object insert(final Object obj); Object insert(String name, Object obj); Object update(final Object obj); Object update(String name, Object obj); Object delete(Object entity); Object delete(String name, Object entity); void flush(); Object lookupByQuery(final String query, final Object ... parameters); Object lookupByQuery(final String query, final Map<String, ?> parameters); Object lookup(final String name, final Object ... parameters); Object lookup(final String name, final Map<String, ?> parameters); }### Answer: @Test public void test_lookup() { DaoInvoker invoker = new InterfaceDaoInvoker(fullDao); Map<String, Object> params = new HashMap<String, Object>(); invoker.lookup("id", params); verify(fullDao).lookup(eq("id"), same(params)); } @Test(expectedExceptions = UnsupportedOperationException.class) public void test_findBy_non_finder_dao() { DaoInvoker invoker = new InterfaceDaoInvoker(minimumDao); Map<String, Object> params = new HashMap<String, Object>(); invoker.lookup("id", params); }
### Question: AbstractDaoAdapterRegister extends AbstractDaoRegister<D> { public D getDefaultDao() { if(defaultDao == null) { throw new IllegalStateException("No default DAO is set on this '" + this.getClass().getName() + "' DaoRegister."); } return defaultDao; } AbstractDaoAdapterRegister(A defaultAdaptable); AbstractDaoAdapterRegister(A defaultAdaptable, Map<String, ? extends A> adaptableMap); AbstractDaoAdapterRegister(Map<String, ? extends A> adaptableMap); D getDefaultDao(); D getDao(String name); }### Answer: @Test(expectedExceptions = IllegalStateException.class) public void test_no_default_adaptable() { Mock mock = new Mock(new HashMap<String, Object>()); mock.getDefaultDao(); }
### Question: AbstractDaoAdapterRegister extends AbstractDaoRegister<D> { public D getDao(String name) { if(name == null) { return getDefaultDao(); } D dao = daoMap.get(name); if(dao == null) { throw new IllegalStateException("No DAO under the name '"+ name +"' was found in this '" + this.getClass().getName() + "' DaoRegister."); } return dao; } AbstractDaoAdapterRegister(A defaultAdaptable); AbstractDaoAdapterRegister(A defaultAdaptable, Map<String, ? extends A> adaptableMap); AbstractDaoAdapterRegister(Map<String, ? extends A> adaptableMap); D getDefaultDao(); D getDao(String name); }### Answer: @Test(expectedExceptions = IllegalStateException.class) public void test_unknown_mapped_adaptable() { Mock mock = new Mock(new HashMap<String, Object>()); mock.getDao(""); }
### Question: SqlMapClientDaoAdapter implements MappingDao<Object>, Locator { public Object insert(String id, Object entity) { try { sqlMapClient.insert(id, entity); } catch (SQLException e) { throw new DaoException("Exception throw while executing insert with statement id '" + id + "' and entity '" + entity + "'", e); } return null; } SqlMapClientDaoAdapter(SqlMapClient sqlMapClient); Object update(String id, Object entity); Object insert(String id, Object entity); Object delete(String id, Object entity); @SuppressWarnings("unchecked") Collection<Object> lookup(String id, Map<String, ?> parameters); @SuppressWarnings("unchecked") Collection<Object> lookup(String id, Object ... parameters); SqlMapClient getSqlMapClient(); }### Answer: @Test(groups = "unit") public void test_persist() throws SQLException { Object toPersist = new Object(); adapter.insert("id", toPersist); verify(sqlMapClient).insert(eq("id"), same(toPersist)); }
### Question: SqlMapClientDaoAdapter implements MappingDao<Object>, Locator { public Object update(String id, Object entity) { try { sqlMapClient.update(id, entity); } catch (SQLException e) { throw new DaoException("Exception throw while executing update with statement id '" + id + "' and entity '" + entity + "'", e); } return null; } SqlMapClientDaoAdapter(SqlMapClient sqlMapClient); Object update(String id, Object entity); Object insert(String id, Object entity); Object delete(String id, Object entity); @SuppressWarnings("unchecked") Collection<Object> lookup(String id, Map<String, ?> parameters); @SuppressWarnings("unchecked") Collection<Object> lookup(String id, Object ... parameters); SqlMapClient getSqlMapClient(); }### Answer: @Test(groups = "unit") public void test_merge() throws SQLException { Object toMerge = new Object(); Object merged = adapter.update("id", toMerge); verify(sqlMapClient).update(eq("id"), same(toMerge)); assertNull(merged); }
### Question: SqlMapClientDaoAdapter implements MappingDao<Object>, Locator { @SuppressWarnings("unchecked") public Collection<Object> lookup(String id, Map<String, ?> parameters) { try { return sqlMapClient.queryForList(id, parameters); } catch (SQLException e) { throw new DaoException("Exception throw while executing query with statement id '" + id + "' and parameters '" + parameters + "'", e); } } SqlMapClientDaoAdapter(SqlMapClient sqlMapClient); Object update(String id, Object entity); Object insert(String id, Object entity); Object delete(String id, Object entity); @SuppressWarnings("unchecked") Collection<Object> lookup(String id, Map<String, ?> parameters); @SuppressWarnings("unchecked") Collection<Object> lookup(String id, Object ... parameters); SqlMapClient getSqlMapClient(); }### Answer: @Test(groups = "unit") public void test_lookup_map_parameters() throws SQLException { List<?> listResult = Collections.emptyList(); stub(sqlMapClient.queryForList(anyString(), anyObject())).toReturn(listResult); Map<String, Object> params = new HashMap<String, Object>(); params.put("key1", "value1"); params.put("key2", "value2"); Collection<Object> result = adapter.lookup("name", params); assertSame(listResult, result); verify(sqlMapClient).queryForList(eq("name"), same(params)); } @Test(groups = "unit") public void test_lookup_array_parameters() throws SQLException { List<?> listResult = Collections.emptyList(); stub(sqlMapClient.queryForList(anyString(), anyObject())).toReturn(listResult); Object[] params = new Object[2]; params[0] = "value1"; params[1] = "value2"; Collection<Object> result = adapter.lookup("name", params); assertSame(listResult, result); verify(sqlMapClient).queryForList(eq("name"), same(params)); }
### Question: SessionDaoAdapter implements Dao<Object>, Locator, Queryable, Flushable { public Object insert(final Object entity) { AssertArgument.isNotNull(entity, "entity"); session.save(entity); return null; } SessionDaoAdapter(final Session session); void flush(); Object update(final Object entity); Object insert(final Object entity); Object delete(Object entity); Object lookup(final String name, final Object ... parameters); Object lookup(final String name, final Map<String, ?> parameters); Object lookupByQuery(final String query, final Object ... parameters); Object lookupByQuery(final String query, final Map<String, ?> parameters); Session getSession(); }### Answer: @Test(groups = "unit") public void test_persist() { Object toPersist = new Object(); adapter.insert(toPersist); verify(session).save(same(toPersist)); }
### Question: SessionDaoAdapter implements Dao<Object>, Locator, Queryable, Flushable { public Object update(final Object entity) { AssertArgument.isNotNull(entity, "entity"); session.update(entity); return entity; } SessionDaoAdapter(final Session session); void flush(); Object update(final Object entity); Object insert(final Object entity); Object delete(Object entity); Object lookup(final String name, final Object ... parameters); Object lookup(final String name, final Map<String, ?> parameters); Object lookupByQuery(final String query, final Object ... parameters); Object lookupByQuery(final String query, final Map<String, ?> parameters); Session getSession(); }### Answer: @Test(groups = "unit") public void test_merge() { Object toMerge = new Object(); Object merged = adapter.update(toMerge); verify(session).update(same(toMerge)); assertSame(toMerge, merged); }
### Question: SessionDaoAdapter implements Dao<Object>, Locator, Queryable, Flushable { public void flush() { session.flush(); } SessionDaoAdapter(final Session session); void flush(); Object update(final Object entity); Object insert(final Object entity); Object delete(Object entity); Object lookup(final String name, final Object ... parameters); Object lookup(final String name, final Map<String, ?> parameters); Object lookupByQuery(final String query, final Object ... parameters); Object lookupByQuery(final String query, final Map<String, ?> parameters); Session getSession(); }### Answer: @Test(groups = "unit") public void test_flush() { adapter.flush(); verify(session).flush(); }
### Question: XsdDOMValidator extends XsdValidator { public void validate() throws SAXException, IOException { validate(new DOMSource(document)); } XsdDOMValidator(Document document); URI getDefaultNamespace(); List<URI> getNamespaces(); void validate(); static String getDefaultNamespace(Element element); }### Answer: @Test public void test_validation_validdoc() throws IOException, SAXException, ParserConfigurationException { Document document = XmlUtil.parseStream(getClass().getResourceAsStream("xsdDomValidator-test-01.xml")); XsdDOMValidator validator = new XsdDOMValidator(document); validator.validate(); } @Test public void test_validation_invaliddoc() throws IOException, SAXException, ParserConfigurationException { Document document = XmlUtil.parseStream(getClass().getResourceAsStream("xsdDomValidator-test-02.xml")); XsdDOMValidator validator = new XsdDOMValidator(document); try { validator.validate(); fail("Expected SAXParseException"); } catch(SAXParseException e) { assertEquals("cvc-complex-type.4: Attribute 'myName' must appear on element 'a:myNVP'.", e.getMessage()); } }
### Question: EntityManagerDaoAdapter implements Dao<Object>, Locator, Queryable, Flushable { public Object insert(final Object entity) { AssertArgument.isNotNull(entity, "entity"); entityManager.persist(entity); return null; } EntityManagerDaoAdapter(final EntityManager entityManager); void flush(); Object update(final Object entity); Object insert(final Object entity); Object delete(Object entity); @SuppressWarnings("unchecked") Collection<Object> lookup(final String name, final Object ... parameters); @SuppressWarnings("unchecked") Collection<Object> lookup(final String name, final Map<String, ?> parameters); @SuppressWarnings("unchecked") Collection<Object> lookupByQuery(final String query, final Object ... parameters); @SuppressWarnings("unchecked") Collection<Object> lookupByQuery(final String query, final Map<String, ?> parameters); EntityManager getEntityManager(); }### Answer: @Test( groups = "unit" ) public void test_persist() { Object toPersist = new Object(); adapter.insert(toPersist); verify(entityManager).persist(same(toPersist)); }
### Question: EntityManagerDaoAdapter implements Dao<Object>, Locator, Queryable, Flushable { public Object update(final Object entity) { AssertArgument.isNotNull(entity, "entity"); return entityManager.merge(entity); } EntityManagerDaoAdapter(final EntityManager entityManager); void flush(); Object update(final Object entity); Object insert(final Object entity); Object delete(Object entity); @SuppressWarnings("unchecked") Collection<Object> lookup(final String name, final Object ... parameters); @SuppressWarnings("unchecked") Collection<Object> lookup(final String name, final Map<String, ?> parameters); @SuppressWarnings("unchecked") Collection<Object> lookupByQuery(final String query, final Object ... parameters); @SuppressWarnings("unchecked") Collection<Object> lookupByQuery(final String query, final Map<String, ?> parameters); EntityManager getEntityManager(); }### Answer: @Test( groups = "unit" ) public void test_merge() { Object toPersist = new Object(); Object merged = adapter.update(toPersist); verify(entityManager).merge(same(toPersist)); }
### Question: EntityManagerDaoAdapter implements Dao<Object>, Locator, Queryable, Flushable { public void flush() { entityManager.flush(); } EntityManagerDaoAdapter(final EntityManager entityManager); void flush(); Object update(final Object entity); Object insert(final Object entity); Object delete(Object entity); @SuppressWarnings("unchecked") Collection<Object> lookup(final String name, final Object ... parameters); @SuppressWarnings("unchecked") Collection<Object> lookup(final String name, final Map<String, ?> parameters); @SuppressWarnings("unchecked") Collection<Object> lookupByQuery(final String query, final Object ... parameters); @SuppressWarnings("unchecked") Collection<Object> lookupByQuery(final String query, final Map<String, ?> parameters); EntityManager getEntityManager(); }### Answer: @Test( groups = "unit" ) public void test_flush() { adapter.flush(); verify(entityManager).flush(); }
### Question: SmooksServiceFactory implements ServiceFactory { public Object getService(final Bundle bundle, final ServiceRegistration registration) { return new SmooksOSGIFactory(bundle); } Object getService(final Bundle bundle, final ServiceRegistration registration); void ungetService(final Bundle bundle, final ServiceRegistration registration, final Object service); }### Answer: @Test public void getService() { final ServiceFactory serviceFactory = new SmooksServiceFactory(); final Bundle bundle = mock(Bundle.class); final Object service = serviceFactory.getService(bundle, null); assertThat(service, is(instanceOf(SmooksFactory.class))); }
### Question: BundleClassLoaderDelegator extends ClassLoader { @Override public URL getResource(String name) { URL resource = findResource(name); if (resource == null) { resource = classLoader.getResource(name); } return resource; } BundleClassLoaderDelegator(final Bundle bundle); BundleClassLoaderDelegator(final Bundle bundle, final ClassLoader delegate); @Override URL getResource(String name); }### Answer: @Test public void getResourceFromBundle() throws Exception { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "bundle.jar"); jar.addAsResource(folder.newFile("test.properties")); BundleClassLoaderDelegator bcl = new BundleClassLoaderDelegator(new MockBundle(jar), getClass().getClassLoader()); URL resource = bcl.getResource("test.properties"); assertNotNull(resource); }
### Question: SmooksOSGIFactory implements SmooksFactory { public Smooks createInstance() { return createSmooksWithDelegatingClassloader(); } SmooksOSGIFactory(final Bundle bundle); Smooks createInstance(); Smooks createInstance(final InputStream config); Smooks createInstance(String config); }### Answer: @Test public void createWithoutConfig() throws IOException, SAXException { final Bundle bundle = mock(Bundle.class); final SmooksOSGIFactory factory = new SmooksOSGIFactory(bundle); final Smooks smooks = factory.createInstance(); assertThat(smooks.getClassLoader(), is(instanceOf(BundleClassLoaderDelegator.class))); }
### Question: HTMLEntityLookup { public static Character getCharacterCode(String entityName) { return m_nameMap.get(entityName); } static Character getCharacterCode(String entityName); static String getEntityRef(char charCode); }### Answer: @Test public void testGetCharacterCode() { assertEquals('\u00A4', HTMLEntityLookup.getCharacterCode("curren") .charValue()); assertEquals('\u0026', HTMLEntityLookup.getCharacterCode("amp") .charValue()); assertEquals('\u00A0', HTMLEntityLookup.getCharacterCode("nbsp") .charValue()); assertEquals('\'', HTMLEntityLookup.getCharacterCode("apos").charValue()); assertEquals('\u0022', HTMLEntityLookup.getCharacterCode("quot").charValue()); }
### Question: HTMLEntityLookup { public static String getEntityRef(char charCode) { return m_codeMap.get(new Character(charCode)); } static Character getCharacterCode(String entityName); static String getEntityRef(char charCode); }### Answer: @Test public void testGetEntityRef() { assertEquals("curren", HTMLEntityLookup.getEntityRef('\u00A4')); assertEquals("amp", HTMLEntityLookup.getEntityRef('\u0026')); assertEquals("nbsp", HTMLEntityLookup.getEntityRef('\u00A0')); assertEquals("apos", HTMLEntityLookup.getEntityRef('\'')); assertEquals("quot", HTMLEntityLookup.getEntityRef('\u0022')); }
### Question: CollectionsUtil { public static <T> Set<T> toSet(T... objects) { Set<T> theSet = new HashSet<T>(); addToCollection(theSet, objects); return theSet; } private CollectionsUtil(); static Set<T> toSet(T... objects); static List<T> toList(T... objects); static List<T> toList(Enumeration<T> objects); }### Answer: @Test public void test_Set_01() { Set<String> strings = CollectionsUtil.toSet("1", "2", "3"); assertTrue(strings.contains("1")); assertTrue(strings.contains("2")); assertTrue(strings.contains("3")); } @Test public void test_Set_02() { Set<Integer> integers = CollectionsUtil.toSet(1, 2, 3); assertTrue(integers.contains(1)); assertTrue(integers.contains(2)); assertTrue(integers.contains(3)); }
### Question: CollectionsUtil { public static <T> List<T> toList(T... objects) { List<T> theList = new ArrayList<T>(); addToCollection(theList, objects); return theList; } private CollectionsUtil(); static Set<T> toSet(T... objects); static List<T> toList(T... objects); static List<T> toList(Enumeration<T> objects); }### Answer: @Test public void test_List_01() { List<String> strings = CollectionsUtil.toList("1", "2", "3"); assertTrue(strings.contains("1")); assertTrue(strings.contains("2")); assertTrue(strings.contains("3")); } @Test public void test_List_02() { List<Integer> integers = CollectionsUtil.toList(1, 2, 3); assertTrue(integers.contains(1)); assertTrue(integers.contains(2)); assertTrue(integers.contains(3)); }
### Question: DollarBraceDecoder { public static List<String> getTokens(String string) { List<String> tokens = new ArrayList<String>(); Matcher m = pattern.matcher(string); while (m.find()) { int start = m.start(); int end = m.end(); String token = string.substring((start + 2), (end - 1)); tokens.add(token); } return tokens; } static List<String> getTokens(String string); static String replaceTokens(String string, String replacement); static final String PATTERN; }### Answer: @Test public void test_getTokens() { assertEquals("[]", DollarBraceDecoder.getTokens("aaaaaa").toString()); assertEquals("[x]", DollarBraceDecoder.getTokens("aaa${x}aaa").toString()); assertEquals("[x, x]", DollarBraceDecoder.getTokens("aaa${x}a${x}aa").toString()); assertEquals("[x, x, y]", DollarBraceDecoder.getTokens("aaa${x}a${x}a${y}a").toString()); assertEquals("[x, x, y]", DollarBraceDecoder.getTokens("a}aa${x}a${x}a${y}a").toString()); assertEquals("[a${x, x, y]", DollarBraceDecoder.getTokens("a}a${a${x}a${x}a${y}a").toString()); assertEquals("[a${x, x, y]", DollarBraceDecoder.getTokens("a}a${a${x}a${x}a${y}a${").toString()); assertEquals("[orderDetail.orderNum, accounts[0].USERID[2], orderDetail.date]", DollarBraceDecoder.getTokens( "INSERT INTO ORDERS VALUES(${orderDetail.orderNum}, ${accounts[0].USERID[2]}, ${orderDetail.date})").toString()); }
### Question: DollarBraceDecoder { public static String replaceTokens(String string, String replacement) { List<String> tokens = getTokens(string); for (String token : tokens) { string = string.replace("${" + token + "}", replacement); } return string; } static List<String> getTokens(String string); static String replaceTokens(String string, String replacement); static final String PATTERN; }### Answer: @Test public void test_replaceTokens() { assertEquals("aaaaaa", DollarBraceDecoder.replaceTokens("aaaaaa", "?")); assertEquals("aaa?aaa", DollarBraceDecoder.replaceTokens("aaa${x}aaa", "?")); assertEquals("aaa?a?aa", DollarBraceDecoder.replaceTokens("aaa${x}a${x}aa", "?")); assertEquals("aaa?a?a?a", DollarBraceDecoder.replaceTokens("aaa${x}a${x}a${y}a", "?")); assertEquals("test-?.txt", DollarBraceDecoder.replaceTokens( "test-${currentDate.date?string('yyyy')}.txt", "?")); assertEquals("test-?.txt", DollarBraceDecoder.replaceTokens( "test-${currentDate.date?string('yyyy-MM-dd-HH-mm-sss')}.txt", "?")); assertEquals("test-?.txt", DollarBraceDecoder.replaceTokens( "test-${currentDate.date?string(\"yyyy-MM-dd-HH-mm-sss\")}.txt", "?")); assertEquals("INSERT INTO ORDERS VALUES(?, ?, ?)", DollarBraceDecoder.replaceTokens( "INSERT INTO ORDERS VALUES(${orderDetail.orderNum + \"-\" + product.ID}, ${accounts[0].USERID[2]}, ${orderDetail.date})", "?")); }
### Question: ClasspathResourceLocator implements ContainerResourceLocator { public InputStream getResource(String configName, String defaultUri) throws IllegalArgumentException { return getResource(defaultUri); } InputStream getResource(String configName, String defaultUri); InputStream getResource(String uri); URI getBaseURI(); }### Answer: @Test public void test_getResource() { ClasspathResourceLocator cpResLocator = new ClasspathResourceLocator(); testArgs(cpResLocator, null); testArgs(cpResLocator, "http: testArgs(cpResLocator, "a/b.txt"); InputStream stream = cpResLocator.getResource("/a.adf"); assertNotNull("Expected a resource stream.", stream); stream = cpResLocator.getResource("/x.txt"); assertNull("Expected no resource stream.", stream); }
### Question: URIResourceLocator implements ContainerResourceLocator { public InputStream getResource(String configName, String defaultUri) throws IllegalArgumentException, IOException { return getResource(defaultUri); } InputStream getResource(String configName, String defaultUri); InputStream getResource(String uri); URI resolveURI(String uri); void setBaseURI(URI baseURI); URI getBaseURI(); static URI getSystemBaseURI(); static URI extractBaseURI(String resourceURI); static URI extractBaseURI(URI resourceURI); static final String SCHEME_CLASSPATH; static final String BASE_URI_SYSKEY; static final URI DEFAULT_BASE_URI; }### Answer: @Test public void test_urlBasedResource() throws IllegalArgumentException, IOException { URIResourceLocator locator = new URIResourceLocator(); InputStream stream; try { stream = locator.getResource((new File("nofile")).toURI() .toString()); fail("Expected FileNotFoundException."); } catch (FileNotFoundException e) { } stream = locator.getResource(file.toURI().toString()); assertNotNull(stream); stream.close(); } @Test public void test_classpathBasedResource() throws IllegalArgumentException, IOException { URIResourceLocator locator = new URIResourceLocator(); InputStream stream; try { stream = locator.getResource("classpath:/org/smooks/resource/someunknownfile.txt"); fail("Expected IOException for bad resource path."); } catch (IOException e) { assertTrue(e.getMessage().startsWith( "Failed to access data stream for")); } stream = locator.getResource("classpath:/org/smooks/resource/somefile.txt"); assertNotNull(stream); stream = locator.getResource("/org/smooks/resource/somefile.txt"); assertNotNull(stream); }
### Question: DefaultProfileSet extends LinkedHashMap implements ProfileSet { public void addProfile(String profile) { addProfile(new BasicProfile(profile)); } DefaultProfileSet(String baseProfile); String getBaseProfile(); boolean isMember(String profile); void addProfile(String profile); @SuppressWarnings("unchecked") void addProfile(Profile profile); Profile getProfile(String profile); Iterator iterator(); void addProfiles(String[] subProfiles); String toString(); static DefaultProfileSet create(String baseProfile, String[] subProfiles); }### Answer: @Test public void testAddProfile_exceptions() { DefaultProfileSet set = new DefaultProfileSet("baseProfile"); try { set.addProfile((Profile) null); fail("no arg exception on null"); } catch (IllegalArgumentException e) { } try { set.addProfile(""); fail("no arg exception on empty"); } catch (IllegalArgumentException e) { } try { set.addProfile(" "); fail("no arg exception on whitespace"); } catch (IllegalArgumentException e) { } }
### Question: DefaultProfileSet extends LinkedHashMap implements ProfileSet { public boolean isMember(String profile) { if (profile == null) { throw new IllegalArgumentException( "null 'profile' arg in method call."); } if(profile.equalsIgnoreCase(baseProfile)) { return true; } else { return containsKey(profile.trim()); } } DefaultProfileSet(String baseProfile); String getBaseProfile(); boolean isMember(String profile); void addProfile(String profile); @SuppressWarnings("unchecked") void addProfile(Profile profile); Profile getProfile(String profile); Iterator iterator(); void addProfiles(String[] subProfiles); String toString(); static DefaultProfileSet create(String baseProfile, String[] subProfiles); }### Answer: @Test public void testIsMember_exceptions() { DefaultProfileSet set = new DefaultProfileSet("baseProfile"); try { set.isMember(null); fail("no arg exception on null"); } catch (IllegalArgumentException e) { } } @Test public void testIsMember() { DefaultProfileSet set = new DefaultProfileSet("baseProfile"); assertFalse(set.isMember("xxx")); set.addProfile("xxx"); assertTrue(set.isMember("xxx")); assertFalse(set.isMember("yyy")); set.addProfile(" YYY"); assertTrue(set.isMember("YYY")); assertTrue(set.isMember(" YYY")); assertTrue(set.isMember("YYY ")); }
### Question: HttpAcceptHeaderProfile extends BasicProfile { public HttpAcceptHeaderProfile(String media, String[] params) { super("accept:" + media); for (int i = 0; i < params.length; i++) { params[i] = params[i].trim(); } this.params = params; } HttpAcceptHeaderProfile(String media, String[] params); String getParam(String name); double getParamNumeric(String name, double defaultVal); }### Answer: @Test public void testHttpAcceptHeaderProfile() { HttpAcceptHeaderProfile profile = new HttpAcceptHeaderProfile( "text/plain", new String[] { "q=0.9", "", " level=1 " }); assertEquals("Invalid profile name.", "accept:text/plain", profile .getName()); if (profile.getParamNumeric("q", 1.0) != 0.9) { fail("Invalid qvalue param value."); } if ((int) profile.getParamNumeric("level", 2.0) != 1) { fail("Invalid level param value."); } if (profile.getParamNumeric("xxx", 2.0) != 2.0) { fail("Invalid level param value."); } }
### Question: URIUtil { public static URI getParent(URI uri) throws URISyntaxException { AssertArgument.isNotNull(uri, "uri"); String parentPath = new File(uri.getPath()).getParent(); if(parentPath == null) { return new URI("../"); } return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), parentPath.replace('\\', '/'), uri.getQuery(), uri.getFragment()); } static URI getParent(URI uri); }### Answer: @Test public void test_getParent() throws URISyntaxException { URI uriIn; URI uriOut; uriIn = new URI("/a/b/s/x.txt"); uriOut = URIUtil.getParent(uriIn); assertEquals(new URI("/a/b/s"), uriOut); uriIn = new URI("file:/a/b/s/x.txt"); uriOut = URIUtil.getParent(uriIn); assertEquals(new URI("file:/a/b/s"), uriOut); uriIn = new URI("x.txt"); uriOut = URIUtil.getParent(uriIn); assertEquals(new URI("../"), uriOut); }
### Question: LowerCaseFunction implements StringFunction { public String execute(String input) { return input.toLowerCase(); } String execute(String input); }### Answer: @Test public void test_execute() { LowerCaseFunction function = new LowerCaseFunction(); assertEquals("zzzzzz", function.execute("ZZZZZZ")); }
### Question: TrimFunction implements StringFunction { public String execute(String input) { return input.trim(); } String execute(String input); }### Answer: @Test public void test_execute() { TrimFunction function = new TrimFunction(); assertEquals("zzzzzz", function.execute("zzzzzz ")); assertEquals("zzzzzz", function.execute(" zzzzzz")); assertEquals("ZZZZ", function.execute(" ZZZZ ")); }
### Question: CapitalizeFirstFunction implements StringFunction { public String execute(String input) { for (int i = 0; i < input.length(); i++) { final char ch = input.charAt(i); if (!Character.isWhitespace(ch)) { if (Character.isUpperCase(ch)) { return input; } final char[] chars = input.toCharArray(); chars[i] = Character.toUpperCase(ch); return new String(chars); } } return input; } String execute(String input); }### Answer: @Test public void test_execute() { CapitalizeFirstFunction function = new CapitalizeFirstFunction(); assertEquals("Maurice", function.execute("maurice")); assertEquals("MAURICE", function.execute("MAURICE")); assertEquals(" Maurice", function.execute(" maurice")); assertEquals("Maurice zeijen", function.execute("maurice zeijen")); }
### Question: StringFunctionExecutor { public static StringFunctionExecutor getInstance(String functionDefinition) { StringFunctionExecutor executor = cache.get(functionDefinition); if(executor == null) { executor = new StringFunctionExecutor(functionDefinition, StringFunctionDefinitionParser.parse(functionDefinition)); StringFunctionExecutor existing = cache.putIfAbsent(functionDefinition, executor); if(existing != null) { executor = existing; } } return executor; } private StringFunctionExecutor(String functionDefinition, List<StringFunction> functions); static StringFunctionExecutor getInstance(String functionDefinition); String execute(String input); @Override String toString(); }### Answer: @Test public void test_caching() { String def1 = LOWER_CASE_DEFINITION; StringFunctionExecutor executor1 = StringFunctionExecutor.getInstance(def1); StringFunctionExecutor executor2 = StringFunctionExecutor.getInstance(def1); assertSame(executor1, executor2); String def2 = TRIM_DEFINITION + SEPARATOR + UPPER_CASE_DEFINITION; StringFunctionExecutor executor3 = StringFunctionExecutor.getInstance(def2); StringFunctionExecutor executor4 = StringFunctionExecutor.getInstance(def2); assertSame(executor3, executor4); assertNotSame(executor1, executor3); StringFunctionExecutor executor5 = StringFunctionExecutor.getInstance(def1); assertSame(executor1, executor5); }
### Question: UncapitalizeFirstFunction implements StringFunction { public String execute(String input) { for (int i = 0; i < input.length(); i++) { final char ch = input.charAt(i); if (!Character.isWhitespace(ch)) { if (Character.isLowerCase(ch)) { return input; } final char[] chars = input.toCharArray(); chars[i] = Character.toLowerCase(ch); return new String(chars); } } return input; } String execute(String input); }### Answer: @Test public void test_execute() { UncapitalizeFirstFunction function = new UncapitalizeFirstFunction(); assertEquals("maurice", function.execute("Maurice")); assertEquals("mAURICE", function.execute("MAURICE")); assertEquals(" maurice", function.execute(" Maurice")); assertEquals("maurice Zeijen", function.execute("Maurice Zeijen")); }
### Question: RightTrimFunction implements StringFunction { public String execute(String input) { int i = input.length() - 1; while (i > 0 && Character.isWhitespace(input.charAt(i))) { i--; } return input.substring(0, i + 1); } String execute(String input); }### Answer: @Test public void test_execute() { RightTrimFunction function = new RightTrimFunction(); assertEquals("zzzzzz", function.execute("zzzzzz ")); assertEquals(" ZZZZ", function.execute(" ZZZZ ")); }
### Question: UpperCaseFunction implements StringFunction { public String execute(String input) { return input.toUpperCase(); } String execute(String input); }### Answer: @Test public void test_execute() { UpperCaseFunction function = new UpperCaseFunction(); assertEquals("ZZZZZZ", function.execute("zzzzzz")); }
### Question: FloatToStringConverterFactory implements TypeConverterFactory<Float, String> { @Override public TypeConverter<Float, String> createTypeConverter() { return new NumberToStringConverter<>(); } @Override TypeConverter<Float, String> createTypeConverter(); @Override TypeConverterDescriptor<Class<Float>, Class<String>> getTypeConverterDescriptor(); }### Answer: @Test public void test_encode_format_config() { FloatToStringConverterFactory floatToStringConverterFactory = new FloatToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.FORMAT, "#,###.##"); TypeConverter<Float, String> typeConverter = floatToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1,234.45", typeConverter.convert(1234.45f)); } @Test public void test_encode_locale_config() { FloatToStringConverterFactory floatToStringConverterFactory = new FloatToStringConverterFactory(); Properties config = new Properties(); config.setProperty(NumberTypeConverter.LOCALE, "de-DE"); TypeConverter<Float, String> typeConverter = floatToStringConverterFactory.createTypeConverter(); ((Configurable) typeConverter).setConfiguration(config); assertEquals("1234,45", typeConverter.convert(1234.45f)); }
### Question: ByteConverterFactory implements TypeConverterFactory<String, Byte> { @Override public TypeConverter<String, Byte> createTypeConverter() { return value -> { try { return Byte.parseByte(value.trim()); } catch(NumberFormatException e) { throw new TypeConverterException("Failed to decode Byte value '" + value + "'.", e); } }; } @Override TypeConverter<String, Byte> createTypeConverter(); @Override TypeConverterDescriptor<Class<String>, Class<Byte>> getTypeConverterDescriptor(); }### Answer: @Test public void test_empty_ok_value() { assertEquals(new Byte((byte) 1), byteConverterFactory.createTypeConverter().convert("1")); } @Test public void test_empty_data_string() { try { byteConverterFactory.createTypeConverter().convert(""); fail("Expected DataDecodeException"); } catch (TypeConverterException e) { assertEquals("Failed to decode Byte value ''.", e.getMessage()); } }
### Question: FileConverterFactory implements TypeConverterFactory<String, File> { @Override public TypeConverter<String, File> createTypeConverter() { return value -> { try { return new File(value); } catch (Exception e) { throw new TypeConverterException("Unable to decode '" + value + "' as a " + File.class.getName() + " instance.", e); } }; } @Override TypeConverter<String, File> createTypeConverter(); @Override TypeConverterDescriptor<Class<String>, Class<File>> getTypeConverterDescriptor(); }### Answer: @Test public void test() { FileConverterFactory fileConverterFactory = new FileConverterFactory(); assertEquals(new File("/a.txt"), fileConverterFactory.createTypeConverter().convert("/a.txt")); }
### Question: CsvConverterFactory implements TypeConverterFactory<String, String[]> { @Override public TypeConverter<String, String[]> createTypeConverter() { return value -> { final String[] values = value.split(","); for (int i = 0; i < values.length; i++) { values[i] = values[i].trim(); } return values; }; } @Override TypeConverter<String, String[]> createTypeConverter(); @Override TypeConverterDescriptor<Class<String>, Class<String[]>> getTypeConverterDescriptor(); }### Answer: @Test public void test() { CsvConverterFactory csvConverterFactory = new CsvConverterFactory(); String[] values; values = csvConverterFactory.createTypeConverter().convert("a,b,c"); assertEquals("[a, b, c]", Arrays.asList(values).toString()); values = csvConverterFactory.createTypeConverter().convert("\na\n,\nb\n,\nc\n"); assertEquals("[a, b, c]", Arrays.asList(values).toString()); }
### Question: HBaseClient { public void createTable(final String tableName, final Set<String> columnFamilies) { checkTableAndColumnFamilies(tableName, columnFamilies); try (final Admin admin = _connection.getAdmin()) { final TableDescriptorBuilder tableBuilder = getTableDescriptorBuilder(tableName, columnFamilies); admin.createTable(tableBuilder.build()); } catch (IOException e) { throw new MetaModelException(e); } } HBaseClient(final Connection connection); void insertRow(final String tableName, final HBaseColumn[] columns, final Object[] values, final int indexOfIdColumn); void deleteRow(final String tableName, final Object rowKey); void createTable(final String tableName, final Set<String> columnFamilies); void createTable(final String tableName, final Set<String> columnFamilies, byte[][] splitKeys); void dropTable(final String tableName); }### Answer: @Test public void testCreateTableWithTableNameNull() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Can't create a table without having the tableName or columnFamilies"); final Set<String> columnFamilies = new LinkedHashSet<>(); columnFamilies.add("1"); new HBaseClient(getDataContext().getConnection()).createTable(null, columnFamilies); } @Test public void testCreateTableWithColumnFamiliesNull() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Can't create a table without having the tableName or columnFamilies"); new HBaseClient(getDataContext().getConnection()).createTable("1", null); } @Test public void testCreateTableWithColumnFamiliesEmpty() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Can't create a table without having the tableName or columnFamilies"); final Set<String> columnFamilies = new LinkedHashSet<>(); new HBaseClient(getDataContext().getConnection()).createTable("1", columnFamilies); }
### Question: HBaseClient { public void deleteRow(final String tableName, final Object rowKey) { if (tableName == null || rowKey == null) { throw new IllegalArgumentException("Can't delete a row without having tableName or rowKey"); } byte[] rowKeyAsByteArray = getValueAsByteArray(rowKey); if (rowKeyAsByteArray.length > 0) { try (final Table table = _connection.getTable(TableName.valueOf(tableName))) { if (rowExists(table, rowKeyAsByteArray)) { table.delete(new Delete(rowKeyAsByteArray)); } else { logger.warn("Rowkey with value {} doesn't exist in the table", rowKey.toString()); } } catch (IOException e) { throw new MetaModelException(e); } } else { throw new IllegalArgumentException("Can't delete a row without an empty rowKey."); } } HBaseClient(final Connection connection); void insertRow(final String tableName, final HBaseColumn[] columns, final Object[] values, final int indexOfIdColumn); void deleteRow(final String tableName, final Object rowKey); void createTable(final String tableName, final Set<String> columnFamilies); void createTable(final String tableName, final Set<String> columnFamilies, byte[][] splitKeys); void dropTable(final String tableName); }### Answer: @Test public void testDeleteRowWithTableNameNull() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Can't delete a row without having tableName or rowKey"); new HBaseClient(getDataContext().getConnection()).deleteRow(null, new String("1")); } @Test public void testDeleteRowWithRowKeyNull() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Can't delete a row without having tableName or rowKey"); new HBaseClient(getDataContext().getConnection()).deleteRow("tableName", null); }
### Question: HBaseClient { public void dropTable(final String tableName) { if (tableName == null) { throw new IllegalArgumentException("Can't drop a table without having the tableName"); } try (final Admin admin = _connection.getAdmin()) { final TableName hBasetableName = TableName.valueOf(tableName); admin.disableTable(hBasetableName); admin.deleteTable(hBasetableName); } catch (IOException e) { throw new MetaModelException(e); } } HBaseClient(final Connection connection); void insertRow(final String tableName, final HBaseColumn[] columns, final Object[] values, final int indexOfIdColumn); void deleteRow(final String tableName, final Object rowKey); void createTable(final String tableName, final Set<String> columnFamilies); void createTable(final String tableName, final Set<String> columnFamilies, byte[][] splitKeys); void dropTable(final String tableName); }### Answer: @Test public void testDropTableWithTableNameNull() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Can't drop a table without having the tableName"); new HBaseClient(getDataContext().getConnection()).dropTable(null); }
### Question: ExcelDataContext extends QueryPostprocessDataContext implements UpdateableDataContext { @Override public UpdateSummary executeUpdate(UpdateScript update) { final ExcelUpdateCallback updateCallback = new ExcelUpdateCallback(this); synchronized (WRITE_LOCK) { try { update.run(updateCallback); } finally { updateCallback.close(); } } return updateCallback.getUpdateSummary(); } ExcelDataContext(File file); ExcelDataContext(File file, ExcelConfiguration configuration); ExcelDataContext(Resource resource, ExcelConfiguration configuration); ExcelConfiguration getConfiguration(); Resource getResource(); @Override DataSet materializeMainSchemaTable(Table table, List<Column> columns, int maxRows); @Override UpdateSummary executeUpdate(UpdateScript update); }### Answer: @Test(expected = MetaModelException.class) public void testInsertingValueOfInvalidColumnType() { final ExcelDataContext dataContext = new ExcelDataContext(copyOf("src/test/resources/different_datatypes.xls"), new ExcelConfiguration(ExcelConfiguration.DEFAULT_COLUMN_NAME_LINE, null, true, false, true, 19)); final Table table = dataContext.getDefaultSchema().getTable(0); dataContext.executeUpdate(new InsertInto(table).value("INTEGER", "this is not an integer")); } @Test(expected = MetaModelException.class) public void testUpdatingValueOfInvalidColumnType() { final ExcelDataContext dataContext = new ExcelDataContext(copyOf("src/test/resources/different_datatypes.xls"), new ExcelConfiguration(ExcelConfiguration.DEFAULT_COLUMN_NAME_LINE, null, true, false, true, 19)); final Table table = dataContext.getDefaultSchema().getTable(0); dataContext.executeUpdate(new Update(table).value("INTEGER", 1).value("INTEGER", "this is not an integer")); }
### Question: CsvTable extends AbstractTable { private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { final GetField getFields = stream.readFields(); Object columns = getFields.get("_columns", null); if (columns instanceof Column[]) { columns = Arrays.<Column> asList((Column[]) columns); } final Object schema = getFields.get("_schema", null); final Object tableName = getFields.get("_tableName", null); LegacyDeserializationObjectInputStream.setField(CsvTable.class, this, "_columns", columns); LegacyDeserializationObjectInputStream.setField(CsvTable.class, this, "_schema", schema); LegacyDeserializationObjectInputStream.setField(CsvTable.class, this, "_tableName", tableName); } CsvTable(CsvSchema schema, String tableName, List<String> columnNames); CsvTable(CsvSchema schema, String tableName); @Override String getName(); @Override List<Column> getColumns(); @Override Schema getSchema(); @Override TableType getType(); @Override Collection<Relationship> getRelationships(); @Override String getRemarks(); @Override String getQuote(); }### Answer: @Test public void testDeserializeOldTable() throws Exception { final File file = new File("src/test/resources/MetaModel-4.6.0-CsvTable.ser"); try (LegacyDeserializationObjectInputStream in = new LegacyDeserializationObjectInputStream(new FileInputStream(file))) { final Object object = in.readObject(); assertPeopleCsv(object); } } @Test public void testSerializeAndDeserializeCurrentVersion() throws Exception { final DataContext dc = new CsvDataContext(new File("src/test/resources/csv_people.csv")); final Table table1 = dc.getDefaultSchema().getTables().get(0); assertPeopleCsv(table1); final byte[] bytes = SerializationUtils.serialize(table1); try (LegacyDeserializationObjectInputStream in = new LegacyDeserializationObjectInputStream(new ByteArrayInputStream(bytes))) { final Object object = in.readObject(); assertPeopleCsv(object); } }
### Question: SingleLineCsvRow extends AbstractRow { private void writeObject(ObjectOutputStream stream) throws IOException { getValues(); stream.defaultWriteObject(); } SingleLineCsvRow(SingleLineCsvDataSet dataSet, final String line, final int columnsInTable, final boolean failOnInconsistentRowLength, final int rowNumber); @Override Object getValue(int index); @Override Style getStyle(int index); }### Answer: @Test public void testSerialize() throws Exception { final List<Column> columns = new ArrayList<>(); columns.add(new MutableColumn("1")); columns.add(new MutableColumn("2")); final SingleLineCsvDataSet dataSet = new SingleLineCsvDataSet(null, columns, null, 2, new CsvConfiguration()); final SingleLineCsvRow originalRow = new SingleLineCsvRow(dataSet, "foo,bar", 2, false, 1); final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(originalRow); out.flush(); bytes.flush(); final byte[] byteArray = bytes.toByteArray(); Assert.assertTrue(byteArray.length > 0); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(byteArray)); final Row deserializedRow = (Row) in.readObject(); final Object[] values1 = originalRow.getValues(); final Object[] values2 = deserializedRow.getValues(); Assert.assertArrayEquals(values1, values2); }
### Question: SingleLineCsvRow extends AbstractRow { @Override public Object getValue(int index) throws IndexOutOfBoundsException { final String[] values = getValuesInternal(); assert values != null; return values[index]; } SingleLineCsvRow(SingleLineCsvDataSet dataSet, final String line, final int columnsInTable, final boolean failOnInconsistentRowLength, final int rowNumber); @Override Object getValue(int index); @Override Style getStyle(int index); }### Answer: @Test public void testConcurrentAccess() throws Exception { final List<Column> columns = new ArrayList<>(); columns.add(new MutableColumn("b").setColumnNumber(2)); columns.add(new MutableColumn("d").setColumnNumber(4)); columns.add(new MutableColumn("f").setColumnNumber(6)); columns.add(new MutableColumn("h").setColumnNumber(8)); columns.add(new MutableColumn("J").setColumnNumber(10)); try (final DataSet dataSet = new SingleLineCsvDataSet(FileHelper .getBufferedReader(new FileResource("src/test/resources/empty_fields.csv").read(), FileHelper.UTF_8_CHARSET), columns, null, 11, new CsvConfiguration())) { dataSet.toRows().parallelStream().forEach(row -> { for (int i = 0; i < 5; i++) { assertEquals("", row.getValue(i)); } }); } }
### Question: CsvWriter { public String buildLine(String[] nextLine) { final StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE); for (int i = 0; i < nextLine.length; i++) { if (i != 0) { sb.append(_configuration.getSeparatorChar()); } final String nextElement = nextLine[i]; if (nextElement == null) { continue; } final char quoteChar = _configuration.getQuoteChar(); if (quoteChar != CsvConfiguration.NOT_A_CHAR) { sb.append(quoteChar); } sb.append(valueNeedsEscaping(nextElement) ? processValue(nextElement) : nextElement); if (quoteChar != CsvConfiguration.NOT_A_CHAR) { sb.append(quoteChar); } } sb.append('\n'); return sb.toString(); } CsvWriter(CsvConfiguration configuration); String buildLine(String[] nextLine); static final int INITIAL_STRING_SIZE; }### Answer: @Test public void testBuildLineWithSeparatorInValue() throws Exception { CsvConfiguration configuration = new CsvConfiguration(1, "UTF-8", ',', '"', '\\'); CsvWriter writer = new CsvWriter(configuration); String line = writer.buildLine(new String[] {"0", "1,2", "3'4", "5\\6"}); assertEquals("\"0\",\"1,2\",\"3'4\",\"5\\\\6\"\n", line); } @Test public void testBuildLineWithSeparatorInValueAndNoQuoteCharacterSet() throws Exception { CsvConfiguration configuration = new CsvConfiguration(1, "UTF-8", ',', CsvConfiguration.NOT_A_CHAR, '\\'); CsvWriter writer = new CsvWriter(configuration); String line = writer.buildLine(new String[] {"0", "1,2", "3'4", "5\\6"}); assertEquals("0,1\\,2,3'4,5\\\\6\n", line); }
### Question: FixedWidthConfigurationReader { public FixedWidthConfiguration readFromSasFormatFile(String encoding, Resource resource, boolean failOnInconsistentLineWidth) { final List<FixedWidthColumnSpec> columnSpecs = new ArrayList<>(); final CsvDataContext dataContext = new CsvDataContext(resource, new CsvConfiguration()); final Table table = dataContext.getDefaultSchema().getTable(0); try (final DataSet dataSet = dataContext.query().from(table).select("Name", "BeginPosition", "EndPosition") .execute()) { while (dataSet.next()) { final String name = (String) dataSet.getRow().getValue(0); final int beginPosition = Integer.parseInt((String) dataSet.getRow().getValue(1)); final int endPosition = Integer.parseInt((String) dataSet.getRow().getValue(2)); final int width = 1 + endPosition - beginPosition; columnSpecs.add(new FixedWidthColumnSpec(name, width)); } } return new FixedWidthConfiguration(encoding, columnSpecs, failOnInconsistentLineWidth); } FixedWidthConfiguration readFromSasFormatFile(String encoding, Resource resource, boolean failOnInconsistentLineWidth); FixedWidthConfiguration readFromSasInputDefinition(String encoding, Resource resource, boolean failOnInconsistentLineWidth); }### Answer: @Test public void testReadConfigurationFromSasFormatFile() throws Exception { final FixedWidthConfigurationReader reader = new FixedWidthConfigurationReader(); final Resource resource = new FileResource("src/test/resources/metadata_spec1/sas-formatfile-metadata.txt"); assertTrue(resource.isExists()); final FixedWidthConfiguration configuration = reader.readFromSasFormatFile("UTF8", resource, false); assertEquals("[1, 20, 2]", Arrays.toString(configuration.getValueWidths())); final FixedWidthDataContext dataContext = new FixedWidthDataContext(dataResource, configuration); performAssertionsOnSpec1(dataContext); }
### Question: NumberComparator implements Comparator<Object> { public static Comparable<Object> getComparable(Object o) { final Number n = toNumber(o); return new Comparable<Object>() { @Override public boolean equals(Object obj) { return _instance.equals(obj); } public int compareTo(Object o) { return _instance.compare(n, o); } @Override public String toString() { return "NumberComparable[number=" + n + "]"; } }; } private NumberComparator(); static Comparator<Object> getComparator(); static Comparable<Object> getComparable(Object o); int compare(Object o1, Object o2); static boolean isIntegerType(Number n); static Number toNumber(Object value); }### Answer: @Test public void testComparable() throws Exception { Comparable<Object> comparable = NumberComparator.getComparable("125"); assertEquals(0, comparable.compareTo(125)); assertEquals(-1, comparable.compareTo(126)); }
### Question: NumberComparator implements Comparator<Object> { public static Number toNumber(Object value) { if (value == null) { return null; } else if (value instanceof Number) { return (Number) value; } else if (value instanceof Boolean) { if (Boolean.TRUE.equals(value)) { return 1; } else { return 0; } } else { final String stringValue = value.toString().trim(); if (stringValue.isEmpty()) { return null; } try { return Integer.parseInt(stringValue); } catch (NumberFormatException e) { } try { return Long.parseLong(stringValue); } catch (NumberFormatException e) { } try { return new BigInteger(stringValue); } catch (NumberFormatException e) { } try { return Double.parseDouble(stringValue); } catch (NumberFormatException e) { } { if ("true".equalsIgnoreCase(stringValue)) { return 1; } if ("false".equalsIgnoreCase(stringValue)) { return 0; } } logger.warn("Could not convert '{}' to number, returning null", value); return null; } } private NumberComparator(); static Comparator<Object> getComparator(); static Comparable<Object> getComparable(Object o); int compare(Object o1, Object o2); static boolean isIntegerType(Number n); static Number toNumber(Object value); }### Answer: @Test public void testToNumberInt() throws Exception { assertEquals(4212, NumberComparator.toNumber("4212")); } @Test public void testToNumberLong() throws Exception { assertEquals(4212000000l, NumberComparator.toNumber("4212000000")); } @Test public void testToNumberBigInteger() throws Exception { assertEquals(new BigInteger("42120000000000004212"), NumberComparator.toNumber("42120000000000004212")); } @Test public void testToNumberDouble() throws Exception { assertEquals(42.12, NumberComparator.toNumber("42.12")); }
### Question: DefaultCompiledQuery implements CompiledQuery { public Query cloneWithParameterValues(Object[] values) { final AtomicInteger parameterIndex = new AtomicInteger(0); final Query clonedQuery = _query.clone(); replaceParametersInQuery(values, parameterIndex, _query, clonedQuery); return clonedQuery; } DefaultCompiledQuery(Query query); Query cloneWithParameterValues(Object[] values); @Override List<QueryParameter> getParameters(); @Override String toSql(); @Override String toString(); @Override void close(); }### Answer: @Test public void testCloneWithParameterValues() { DefaultCompiledQuery defaultCompiledQuery = new DefaultCompiledQuery(query); Query resultQuery = defaultCompiledQuery.cloneWithParameterValues(new Object[] { "BE", 1, "BE" }); defaultCompiledQuery.close(); defaultCompiledQuery = new DefaultCompiledQuery(resultQuery); Assert.assertEquals(0, defaultCompiledQuery.getParameters().size()); defaultCompiledQuery.close(); }
### Question: LastAggregateFunction extends DefaultAggregateFunction<Object> { @Override public String getFunctionName() { return "LAST"; } @Override AggregateBuilder<?> createAggregateBuilder(); @Override String getFunctionName(); }### Answer: @Test public void testGetName() throws Exception { assertEquals("LAST", FUNCTION.getFunctionName()); assertEquals("LAST", FUNCTION.toString()); }
### Question: ElasticSearchDataContext extends AbstractElasticSearchDataContext { @Override protected Row executePrimaryKeyLookupQuery(Table table, List<SelectItem> selectItems, Column primaryKeyColumn, Object keyValue) { if (keyValue == null) { return null; } final String documentType = table.getName(); final String id = keyValue.toString(); final GetResponse response = getElasticSearchClient().prepareGet(indexName, documentType, id).execute().actionGet(); if (!response.isExists()) { return null; } final Map<String, Object> source = response.getSource(); final String documentId = response.getId(); final DataSetHeader header = new SimpleDataSetHeader(selectItems); return ElasticSearchUtils.createRow(source, documentId, header); } ElasticSearchDataContext(Client client, String indexName, SimpleTableDef... tableDefinitions); ElasticSearchDataContext(Client client, String indexName); static SimpleTableDef detectTable(ClusterState cs, String indexName, String documentType); @Override UpdateSummary executeUpdate(UpdateScript update); Client getElasticSearchClient(); }### Answer: @Test public void testExecutePrimaryKeyLookupQuery() throws Exception { indexTweeterDocuments(); Table table = dataContext.getDefaultSchema().getTableByName("tweet2"); Column[] pks = table.getPrimaryKeys().toArray(new Column[0]); try (DataSet ds = dataContext.query().from(table).selectAll().where(pks[0]).eq("tweet_tweet2_1").execute()) { assertTrue(ds.next()); Object dateValue = ds.getRow().getValue(2); assertEquals("Row[values=[tweet_tweet2_1, 1, " + dateValue + ", user1]]", ds.getRow().toString()); assertFalse(ds.next()); assertEquals(InMemoryDataSet.class, ds.getClass()); } }
### Question: LastAggregateFunction extends DefaultAggregateFunction<Object> { @Override public AggregateBuilder<?> createAggregateBuilder() { return new LastAggregateBuilder(); } @Override AggregateBuilder<?> createAggregateBuilder(); @Override String getFunctionName(); }### Answer: @Test public void testBuildAggregate() throws Exception { final AggregateBuilder<?> aggregateBuilder = FUNCTION.createAggregateBuilder(); aggregateBuilder.add("1"); aggregateBuilder.add("2"); aggregateBuilder.add("3"); assertEquals("3", aggregateBuilder.getAggregate()); }
### Question: RandomAggregateFunction extends DefaultAggregateFunction<Object> { @Override public String getFunctionName() { return "RANDOM"; } @Override AggregateBuilder<?> createAggregateBuilder(); @Override String getFunctionName(); }### Answer: @Test public void testGetName() throws Exception { assertEquals("RANDOM", FUNCTION.getFunctionName()); assertEquals("RANDOM", FUNCTION.toString()); }
### Question: RandomAggregateFunction extends DefaultAggregateFunction<Object> { @Override public AggregateBuilder<?> createAggregateBuilder() { return new RandomAggregateBuilder(); } @Override AggregateBuilder<?> createAggregateBuilder(); @Override String getFunctionName(); }### Answer: @Test public void testBuildAggregate() throws Exception { final AggregateBuilder<?> aggregateBuilder = FUNCTION.createAggregateBuilder(); aggregateBuilder.add("foo"); aggregateBuilder.add("bar"); aggregateBuilder.add("baz"); final Object aggregate = aggregateBuilder.getAggregate(); assertTrue(Arrays.asList("foo", "bar", "baz").contains(aggregate)); }
### Question: FirstAggregateFunction extends DefaultAggregateFunction<Object> { @Override public String getFunctionName() { return "FIRST"; } @Override AggregateBuilder<?> createAggregateBuilder(); @Override String getFunctionName(); }### Answer: @Test public void testGetName() throws Exception { assertEquals("FIRST", FUNCTION.getFunctionName()); assertEquals("FIRST", FUNCTION.toString()); }
### Question: FirstAggregateFunction extends DefaultAggregateFunction<Object> { @Override public AggregateBuilder<?> createAggregateBuilder() { return new FirstAggregateBuilder(); } @Override AggregateBuilder<?> createAggregateBuilder(); @Override String getFunctionName(); }### Answer: @Test public void testBuildAggregate() throws Exception { final AggregateBuilder<?> aggregateBuilder = FUNCTION.createAggregateBuilder(); aggregateBuilder.add("1"); aggregateBuilder.add("2"); aggregateBuilder.add("3"); assertEquals("1", aggregateBuilder.getAggregate()); }
### Question: ResourceFactoryRegistryImpl implements ResourceFactoryRegistry { @Override public Resource createResource(ResourceProperties properties) { for (ResourceFactory factory : factories) { if (factory.accepts(properties)) { return factory.create(properties); } } throw new UnsupportedResourcePropertiesException(); } ResourceFactoryRegistryImpl(); static ResourceFactoryRegistry getDefaultInstance(); @Override void addFactory(ResourceFactory factory); @Override void clearFactories(); @Override Collection<ResourceFactory> getFactories(); @Override Resource createResource(ResourceProperties properties); void discoverFromClasspath(); }### Answer: @Test public void testGetQualifiedFileResource() throws Exception { final File file = new File("src/test/resources/unicode-text-utf8.txt"); final Resource res = registry.createResource(new SimpleResourceProperties("file: .replace('\\', '/'))); assertTrue(res.isExists()); assertEquals("unicode-text-utf8.txt", res.getName()); } @Test public void testGetUnqualifiedRelativeFileResource() throws Exception { final Resource res = registry.createResource(new SimpleResourceProperties( "src/test/resources/unicode-text-utf8.txt")); assertTrue(res.isExists()); assertEquals("unicode-text-utf8.txt", res.getName()); } @Test public void testGetInMemoryResource() throws Exception { final Resource res = registry.createResource(new SimpleResourceProperties("mem: assertTrue(res instanceof InMemoryResource); } @Test public void testGetClasspathResource() throws Exception { final Resource res = registry.createResource(new SimpleResourceProperties("classpath: assertTrue(res.isExists()); assertTrue(res instanceof ClasspathResource); } @Test public void testGetUrlResource() throws Exception { final Resource res = registry.createResource(new SimpleResourceProperties( "http: assertTrue(res.isExists()); assertTrue(res instanceof UrlResource); }
### Question: MutableSchema extends AbstractSchema implements Serializable, Schema { public MutableSchema addTable(Table table) { _tables.add(table); return this; } MutableSchema(); MutableSchema(String name); MutableSchema(String name, Table... tables); @Override String getName(); MutableSchema setName(String name); @Override List<Table> getTables(); MutableSchema setTables(Collection<? extends Table> tables); MutableSchema setTables(Table... tables); MutableSchema clearTables(); MutableSchema addTable(Table table); MutableSchema removeTable(Table table); @Override String getQuote(); }### Answer: @Test public void testEqualsAndHashCode() throws Exception { MutableSchema schema1 = new MutableSchema("foo"); MutableSchema schema2 = new MutableSchema("foo"); assertTrue(schema1.equals(schema2)); assertTrue(schema1.hashCode() == schema2.hashCode()); schema2.addTable(new MutableTable("foo")); assertFalse(schema1.equals(schema2)); assertTrue(schema1.hashCode() == schema2.hashCode()); schema2 = new MutableSchema("foo"); assertTrue(schema1.equals(schema2)); assertTrue(schema1.hashCode() == schema2.hashCode()); }
### Question: MutableSchema extends AbstractSchema implements Serializable, Schema { @Override public String getName() { return _name; } MutableSchema(); MutableSchema(String name); MutableSchema(String name, Table... tables); @Override String getName(); MutableSchema setName(String name); @Override List<Table> getTables(); MutableSchema setTables(Collection<? extends Table> tables); MutableSchema setTables(Table... tables); MutableSchema clearTables(); MutableSchema addTable(Table table); MutableSchema removeTable(Table table); @Override String getQuote(); }### Answer: @Test public void testDeserializeOldFormat() throws Exception { final File file = new File("src/test/resources/metamodel-4.6.0-mutableschema-etc.ser"); assertTrue(file.exists()); try (final FileInputStream in = new FileInputStream(file)) { final LegacyDeserializationObjectInputStream ois = new LegacyDeserializationObjectInputStream(in); final Object obj = ois.readObject(); assertTrue(obj instanceof MutableSchema); ois.close(); final MutableSchema sch = (MutableSchema) obj; assertEquals("schema", sch.getName()); assertEquals(2, sch.getTableCount()); final Table table1 = sch.getTable(0); assertTrue(table1 instanceof MutableTable); assertEquals("t1", table1.getName()); assertEquals(Arrays.asList("t1_c1", "t1_c2"), table1.getColumnNames()); assertEquals(1, table1.getRelationshipCount()); final Table table2 = sch.getTable(1); assertTrue(table2 instanceof MutableTable); assertEquals("t2", table2.getName()); assertEquals(Arrays.asList("t2_c1"), table2.getColumnNames()); assertEquals(1, table2.getRelationshipCount()); final Relationship rel1 = table1.getRelationships().iterator().next(); final Relationship rel2 = table2.getRelationships().iterator().next(); assertSame(rel1, rel2); assertTrue(rel1 instanceof MutableRelationship); } }
### Question: DelegatingIntrinsicSwitchColumnNamingStrategy implements ColumnNamingStrategy { @Override public ColumnNamingSession startColumnNamingSession() { final ColumnNamingSession intrinsicSession = intrinsicStrategy.startColumnNamingSession(); final ColumnNamingSession nonIntrinsicSession = nonIntrinsicStrategy.startColumnNamingSession(); return new ColumnNamingSession() { @Override public String getNextColumnName(ColumnNamingContext ctx) { final String intrinsicColumnName = ctx.getIntrinsicColumnName(); if (intrinsicColumnName == null || intrinsicColumnName.isEmpty()) { return nonIntrinsicSession.getNextColumnName(ctx); } return intrinsicSession.getNextColumnName(ctx); } @Override public void close() { intrinsicSession.close(); nonIntrinsicSession.close(); } }; } DelegatingIntrinsicSwitchColumnNamingStrategy(ColumnNamingStrategy intrinsicStrategy, ColumnNamingStrategy nonIntrinsicStrategy); @Override ColumnNamingSession startColumnNamingSession(); }### Answer: @Test public void testDuplicateColumnNames() throws Exception { try (final ColumnNamingSession session = namingStrategy.startColumnNamingSession()) { assertEquals("foo", session.getNextColumnName(new ColumnNamingContextImpl(null, "foo", 0))); assertEquals("bar", session.getNextColumnName(new ColumnNamingContextImpl(null, "bar", 1))); assertEquals("foo_2", session.getNextColumnName(new ColumnNamingContextImpl(null, "foo", 2))); } } @Test public void testNoIntrinsicColumnNames() throws Exception { try (final ColumnNamingSession session = namingStrategy.startColumnNamingSession()) { assertEquals("A", session.getNextColumnName(new ColumnNamingContextImpl(null, "", 0))); assertEquals("B", session.getNextColumnName(new ColumnNamingContextImpl(null, null, 1))); assertEquals("C", session.getNextColumnName(new ColumnNamingContextImpl(null, "", 2))); } }
### Question: ImmutableSchema extends AbstractSchema implements Serializable { @Override public String getName() { return name; } private ImmutableSchema(String name, String quote); ImmutableSchema(Schema schema); @Override List<Table> getTables(); @Override String getName(); @Override String getQuote(); }### Answer: @Test public void testDeserializeOldFormat() throws Exception { final File file = new File("src/test/resources/metamodel-4.6.0-immutableschema-etc.ser"); assertTrue(file.exists()); try (final FileInputStream in = new FileInputStream(file)) { final LegacyDeserializationObjectInputStream ois = new LegacyDeserializationObjectInputStream(in); final Object obj = ois.readObject(); assertTrue(obj instanceof ImmutableSchema); ois.close(); final ImmutableSchema sch = (ImmutableSchema) obj; assertEquals("schema", sch.getName()); assertEquals(2, sch.getTableCount()); final Table table1 = sch.getTable(0); assertTrue(table1 instanceof ImmutableTable); assertEquals("t1", table1.getName()); assertEquals(Arrays.asList("t1_c1", "t1_c2"), table1.getColumnNames()); assertEquals(1, table1.getRelationshipCount()); final Table table2 = sch.getTable(1); assertTrue(table2 instanceof ImmutableTable); assertEquals("t2", table2.getName()); assertEquals(Arrays.asList("t2_c1"), table2.getColumnNames()); assertEquals(1, table2.getRelationshipCount()); final Relationship rel1 = table1.getRelationships().iterator().next(); final Relationship rel2 = table2.getRelationships().iterator().next(); assertSame(rel1, rel2); assertTrue(rel1 instanceof ImmutableRelationship); } }