method2testcases
stringlengths
118
6.63k
### Question: ApplicationStartup { protected static void replaceInFile(File file, String search, String replacement) throws IOException { Path path = file.toPath(); Charset charset = StandardCharsets.UTF_8; String content = new String(Files.readAllBytes(path), charset); content = content.replaceAll(Pattern.quote(search), Matcher.quoteReplacement(replacement)); System.out.println("Replaced " + search + " with " + replacement + " in " + path); Files.write(path, content.getBytes(charset)); } static void main(String[] args); }### Answer: @Test public void testReplaceInFile() throws Exception { ClassLoader classLoader = ApplicationStartupTest.class.getClassLoader(); File original = new File(classLoader.getResource("xml/sourceConfig.xml").toURI()); File copy = new File("src/test/resources/xml/copyConfig.xml"); File replacementSource = new File(classLoader.getResource("txt/replacement.txt").toURI()); FileUtils.deleteQuietly(copy); FileUtils.copyFile(original, copy); Charset utf8 = StandardCharsets.UTF_8; String replacement = IOUtils.toString(new FileInputStream(replacementSource), utf8); System.out.println("Replacement String: " + replacement); ApplicationStartup.replaceInFile(copy, "${replaceMe}", replacement); String newContent = IOUtils.toString(new FileInputStream(copy), utf8); Assert.assertEquals("C:\\Foo\\Bar\\Bla\\Blubb", newContent); }
### Question: DatabaseController extends ControllerBase { @PostMapping(value = "/platform/database/initialize") public ResponseEntity<Database> initialize( @RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged) throws Exception { DatabaseConnection platformConnection = databaseService.initDatabase(configurer.getProps(), isManaged, true); return info(platformConnection); } @GetMapping(value = "/platform/database") ResponseEntity<Database> info(); @PutMapping(value = "/platform/database") ResponseEntity<Database> updateRootConnection(@RequestBody org.appng.appngizer.model.xml.Database database); @PostMapping(value = "/platform/database/initialize") ResponseEntity<Database> initialize( @RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged); @GetMapping(value = "/site/{name}/database") ResponseEntity<Databases> getDatabaseConnections(@PathVariable("name") String name); @GetMapping(value = "/site/{site}/application/{app}/database") ResponseEntity<Database> getDatabaseConnectionForApplication(@PathVariable("site") String site, @PathVariable("app") String app); @PutMapping(value = "/site/{site}/application/{app}/database") ResponseEntity<Database> updateDatabaseConnectionforApplication(@PathVariable("site") String site, @PathVariable("app") String app, @RequestBody org.appng.appngizer.model.xml.Database database); @GetMapping(value = "/site/{name}/database/{id}") ResponseEntity<Database> getDatabaseConnection(@PathVariable("name") String name, @PathVariable("id") Integer id); @PutMapping(value = "/site/{name}/database/{id}") ResponseEntity<Database> updateDatabaseConnection(@PathVariable("name") String name, @PathVariable("id") Integer id, @RequestBody org.appng.appngizer.model.xml.Database database); }### Answer: @Test public void testInitialize() throws Exception { ignorePasswordAndInstalledDate(); postAndVerify("/platform/database/initialize", "xml/database-init.xml", null, HttpStatus.OK); }
### Question: AppNGizer implements AppNGizerClient { static String encode(String segment) { try { return UriUtils.encodePathSegment(segment, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return segment; } } AppNGizer(String endpoint, String sharedSecret); Home welcome(); Home login(); Subjects subjects(); Subject subject(String name); Subject createSubject(Subject subject); Subject updateSubject(String name, Subject subject); void deleteSubject(String name); Groups groups(); Group group(String name); Group createGroup(Group group); Group updateGroup(String name, Group group); void deleteGroup(String name); Applications applications(); Application application(String app); Application updateApplication(String app, Application application); void deleteApplication(String app); Properties applicationProperties(String app); Property createApplicationProperty(String app, Property property); Property updateApplicationProperty(String app, Property property); void deleteApplicationProperty(String app, String name); Roles roles(String app); Role role(String app, String name); Role createRole(String app, Role role); Role updateRole(String app, String name, Role role); void deleteRole(String app, String name); Permissions permissions(String app); Permission permission(String app, String name); Permission createPermission(String app, Permission permission); Permission updatePermission(String app, String name, Permission permission); void deletePermission(String app, String name); Sites sites(); Site site(String name); Site createSite(Site site); Site updateSite(String name, Site site); void deleteSite(String name); void reloadSite(String name); Properties siteProperties(String site); Property siteProperty(String site, String name); Property createSiteProperty(String site, Property property); Property updateSiteProperty(String site, String name, Property property); void deleteSiteProperty(String site, String name); Applications applications(String site); Application application(String site, String app); void activateApplication(String site, String app); void deactivateApplication(String site, String app); Grants siteGrants(String site, String app); Grants updateSiteGrants(String site, String app, Grants grants); Properties applicationProperties(String site, String app); Property createApplicationProperty(String site, String app, Property property); Property updateApplicationProperty(String site, String app, String name, Property property); void deleteApplicationProperty(String site, String app, String name); Repositories repositories(); Repository repository(String name); Repository createRepository(Repository repository); Repository updateRepository(String name, Repository repository); void deleteRepository(String name); Package installPackage(String name, Package packageToInstall); Package uploadPackage(String name, File archive); Properties platformProperties(); Property platformProperty(String name); Property createPlatformProperty(Property property); Property updatePlatformProperty(String name, Property property); void deletePlatformProperty(String name); Properties environment(); Properties system(); Database database(); Database initializeDatabase(); }### Answer: @Test public void testEncode() { Assert.assertEquals("name%20with%20spaces", AppNGizer.encode("name with spaces")); }
### Question: AppNGizer implements AppNGizerClient { public Package uploadPackage(String name, File archive) throws IOException { MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>(); multipartRequest.add("file", new FileSystemResource(archive)); HttpHeaders headers = getHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); return exchange("/repository/" + encode(name) + "/upload", multipartRequest, HttpMethod.POST, headers, Package.class); } AppNGizer(String endpoint, String sharedSecret); Home welcome(); Home login(); Subjects subjects(); Subject subject(String name); Subject createSubject(Subject subject); Subject updateSubject(String name, Subject subject); void deleteSubject(String name); Groups groups(); Group group(String name); Group createGroup(Group group); Group updateGroup(String name, Group group); void deleteGroup(String name); Applications applications(); Application application(String app); Application updateApplication(String app, Application application); void deleteApplication(String app); Properties applicationProperties(String app); Property createApplicationProperty(String app, Property property); Property updateApplicationProperty(String app, Property property); void deleteApplicationProperty(String app, String name); Roles roles(String app); Role role(String app, String name); Role createRole(String app, Role role); Role updateRole(String app, String name, Role role); void deleteRole(String app, String name); Permissions permissions(String app); Permission permission(String app, String name); Permission createPermission(String app, Permission permission); Permission updatePermission(String app, String name, Permission permission); void deletePermission(String app, String name); Sites sites(); Site site(String name); Site createSite(Site site); Site updateSite(String name, Site site); void deleteSite(String name); void reloadSite(String name); Properties siteProperties(String site); Property siteProperty(String site, String name); Property createSiteProperty(String site, Property property); Property updateSiteProperty(String site, String name, Property property); void deleteSiteProperty(String site, String name); Applications applications(String site); Application application(String site, String app); void activateApplication(String site, String app); void deactivateApplication(String site, String app); Grants siteGrants(String site, String app); Grants updateSiteGrants(String site, String app, Grants grants); Properties applicationProperties(String site, String app); Property createApplicationProperty(String site, String app, Property property); Property updateApplicationProperty(String site, String app, String name, Property property); void deleteApplicationProperty(String site, String app, String name); Repositories repositories(); Repository repository(String name); Repository createRepository(Repository repository); Repository updateRepository(String name, Repository repository); void deleteRepository(String name); Package installPackage(String name, Package packageToInstall); Package uploadPackage(String name, File archive); Properties platformProperties(); Property platformProperty(String name); Property createPlatformProperty(Property property); Property updatePlatformProperty(String name, Property property); void deletePlatformProperty(String name); Properties environment(); Properties system(); Database database(); Database initializeDatabase(); }### Answer: @Ignore("Run locally") @Test(expected = HttpClientErrorException.class) public void testUploadPackage() throws Exception { getAppNGizer().uploadPackage("local", new File("pom.xml")); }
### Question: StyleSheetProvider { public StyleSheetProvider() { } StyleSheetProvider(); void init(); void setMasterSource(InputStream masterXsl, String templateRoot); void addStyleSheet(InputStream styleSheet, String reference); byte[] getStyleSheet(boolean deleteIncludes); byte[] getStyleSheet(boolean deleteIncludes, OutputStream additionalOut); DocumentBuilderFactory getDocumentBuilderFactory(); void setDocumentBuilderFactory(DocumentBuilderFactory documentBuilderFactory); TransformerFactory getTransformerFactory(); void setTransformerFactory(TransformerFactory transformerFactory); DocumentBuilder getDocumentBuilder(); void setDocumentBuilder(DocumentBuilder documentBuilder); Transformer getTransformer(); void setTransformer(Transformer transformer); String getInsertBefore(); void setInsertBefore(String insertBefore); String getName(); void setName(String name); String getId(); void cleanup(); boolean isValid(); }### Answer: @Test public void testStyleSheetProvider() throws Exception { ClassLoader classLoader = getClass().getClassLoader(); ssProvider.setName("container"); ssProvider.setInsertBefore("include-4.xsl"); addStyleSheet("include-1.xsl"); addStyleSheet("include-2.xsl"); addStyleSheet("include-3.xsl"); File expected = new File(classLoader.getResource("xsl/result.xsl").toURI()).getAbsoluteFile(); File result = new File("target/xsl/result-2.xsl"); FileUtils.writeByteArrayToFile(result, ssProvider.getStyleSheet(true)); List<String> lines1 = FileUtils.readLines(expected, "UTF-8"); List<String> lines2 = FileUtils.readLines(result, "UTF-8"); Assert.assertEquals(lines1.size(), lines2.size()); for (int i = 0; i < lines1.size(); i++) { Assert.assertEquals(lines1.get(i).trim(), lines2.get(i).trim()); } }
### Question: ApplicationPropertyConstantCreator { public static void main(String[] args) throws IOException, JAXBException { if (args.length < 3) { throw new IllegalArgumentException("need 3 params (filePath, targetClass, outFolder)"); } String filePath = args[0]; String targetClass = args[1]; String outfolder = args[2]; String prefix = args.length == 4 ? args[3] : ""; if (!targetClass.matches("([a-zA-Z]+[0-9]*)+(\\.[a-zA-Z]+[0-9]*)*")) { throw new IllegalArgumentException("not a valid classname: " + targetClass); } File appXml = new File(filePath); MarshallService applicationMarshallService = MarshallService.getApplicationMarshallService(); ApplicationInfo application = applicationMarshallService.unmarshall(appXml, ApplicationInfo.class); readNameAndVersionFromPom(application, appXml); List<Property> properties = application.getProperties().getProperty(); Collections.sort(properties, new Comparator<Property>() { public int compare(Property o1, Property o2) { return o1.getId().compareToIgnoreCase(o2.getId()); } }); String separator = System.getProperty("line.separator"); int pckg = targetClass.lastIndexOf("."); StringBuilder sb = new StringBuilder(); sb.append("package " + targetClass.substring(0, pckg) + ";" + separator); sb.append(separator); sb.append(""); sb.append(separator); sb.append("public class " + targetClass.substring(pckg + 1) + " {" + separator); sb.append(separator); for (Property property : properties) { if (StringUtils.isNotBlank(property.getDescription())) { sb.append("\t" + separator); } sb.append("\tpublic static final String "); sb.append(prefix); String[] tokens = StringUtils.splitByCharacterTypeCamelCase(property.getId()); for (int i = 0; i < tokens.length; i++) { String s = tokens[i]; if (StringUtils.containsNone(s, '_', '-', '.')) { if (i > 0) { sb.append("_"); } sb.append(s.toUpperCase()); } } sb.append(" = \"" + property.getId() + "\";" + separator); } sb.append(separator); sb.append("}"); String fileName = targetClass.replaceAll("\\.", "/") + ".java"; File outFile = new File(new File(outfolder).getAbsoluteFile(), fileName); outFile.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(sb.toString().getBytes(StandardCharsets.UTF_8)); fos.close(); LOGGER.debug("Wrote {}", outFile.getAbsolutePath()); } } static void main(String[] args); }### Answer: @Test public void test() throws Exception { String outFile = "src/test/resources/xml/application.xml"; ApplicationPropertyConstantCreator .main(new String[] { outFile, "org.appng.xml.ApplicationProperty", "target/tmp", "PROP_" }); String actual = FileUtils.readFileToString(new File("target/tmp/org/appng/xml/ApplicationProperty.java"), StandardCharsets.UTF_8); String expected = FileUtils.readFileToString(new File("src/test/resources/ApplicationProperty.java"), StandardCharsets.UTF_8); Assert.assertEquals(expected, actual); }
### Question: ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } ParseTags(String tagPrefix); Map<String, StringBuilder> parse(InputStream is); }### Answer: @Test public void testFile() throws Exception { Map<String, StringBuilder> parsed = parseTags.parse(new File("pages/en/42.jsp")); Assert.assertEquals("The Hitchhiker's Guide to the Galaxy", parsed.get("title").toString()); String contents = parsed.get("contents").toString(); String expected = "The Hitchhiker's Guide to the Galaxy is a comic science fiction series"; Assert.assertTrue(contents.startsWith(expected)); } @Test public void testNestedTags() throws Exception { String in = "<a:searchable index=\"true\" field=\"contents\">" + "<a:searchable index=\"true\" field=\"field1\"> A </a:searchable>" + "<a:searchable index=\"true\" field=\"field2\"> B </a:searchable>" + "<a:searchable index=\"false\"> C </a:searchable>" + " D </a:searchable>"; Map<String, StringBuilder> parsed = new ParseTags("a").parse(new ByteArrayInputStream(in.getBytes())); System.out.println(parsed); Assert.assertEquals("A", parsed.get("field1").toString()); Assert.assertEquals("B", parsed.get("field2").toString()); Assert.assertNull(parsed.get("field3")); Assert.assertEquals("A B D", parsed.get("contents").toString()); } @Test public void testNotIndexed() throws Exception { String in = "<html><head></head><appNG:searchable index=\"false\">" + "<appNG:searchable index=\"true\" field=\"field1\"> A </appNG:searchable>" + "<appNG:searchable index=\"true\" field=\"field2\"> B </appNG:searchable>" + "<appNG:searchable index=\"false\"> C </appNG:searchable>" + " D </appNG:searchable></html>"; Map<String, StringBuilder> parsed = parseTags.parse(new ByteArrayInputStream(in.getBytes())); System.out.println(parsed); Assert.assertNull(parsed.get("field1")); Assert.assertNull(parsed.get("field2")); Assert.assertNull(parsed.get("field3")); Assert.assertNull(parsed.get("contents")); }
### Question: XPathProcessor { public String getString(String xpathExpression) { return (String) evaluate(document, xpathExpression, XPathConstants.STRING); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); }### Answer: @Test public void testGetString() throws IOException { Assert.assertEquals("abcd", processor.getString("/root/a/string")); Assert.assertEquals("abcd", processor.getString(processor.getNode("/root/a"), "string")); }
### Question: XPathProcessor { public Boolean getBoolean(String xpathExpression) { return (Boolean) evaluate(document, xpathExpression, XPathConstants.BOOLEAN); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); }### Answer: @Test public void testGetBoolean() throws IOException { Assert.assertEquals(Boolean.TRUE, processor.getBoolean("/root/a/boolean")); Assert.assertEquals(Boolean.TRUE, processor.getBoolean(processor.getNode("/root/a"), "boolean")); }
### Question: XPathProcessor { public Number getNumber(String xpathExpression) { return (Number) evaluate(document, xpathExpression, XPathConstants.NUMBER); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); }### Answer: @Test public void testGetNumber() throws IOException { Assert.assertEquals(3.45d, processor.getNumber("/root/a/double")); Assert.assertEquals(3.45d, processor.getNumber(processor.getNode("/root/a"), "double")); }
### Question: XPathProcessor { public String getXml(Node node) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getXml(node, outputStream); return new String(outputStream.toByteArray()); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); }### Answer: @Test public void testGetXml() { Node node = processor.getNode("/root/b"); String xml = processor.getXml(node); ByteArrayOutputStream out = new ByteArrayOutputStream(); processor.getXml(node, out); Assert.assertEquals(xml, out.toString()); }
### Question: XPathProcessor { public Text newText(String tagName) { Text text = document.createTextNode(tagName); return text; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); }### Answer: @Test public void testNewText() { Text text = processor.newText("data"); Assert.assertEquals("data", text.getData()); }
### Question: ImageProcessor { public ImageProcessor fitToHeight(Integer maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); if (height > maxHeight) { height = maxHeight; width = Math.round(((float) maxHeight / height) * width); } return resize(width, height); } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath, boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight, int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); }### Answer: @Test public void testFitToHeight() throws IOException { File targetFile = new File(targetFolder, "desert-height-100.jpg"); ImageProcessor ip = getSource(targetFile); ip.fitToHeight(100); ImageMetaData metaData = new ImageProcessor(ip.getImage(), null, true).getMetaData(); assertDimensions(133, 100, metaData); }
### Question: XPathProcessor { public CDATASection newCDATA(String tagName) { CDATASection cdata = document.createCDATASection(tagName); return cdata; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); }### Answer: @Test public void testNewCDATA() { Text text = processor.newCDATA("data"); Assert.assertEquals("data", text.getData()); }
### Question: XPathProcessor { public Element newElement(String tagName) { Element element = document.createElement(tagName); return element; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); }### Answer: @Test public void testNewElement() { Element el = processor.newElement("data"); Assert.assertEquals("data", el.getTagName()); }
### Question: XPathProcessor { public Attr newAttribute(String name, String value) { Attr attribute = document.createAttribute(name); attribute.setNodeValue(value); return attribute; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); }### Answer: @Test public void testNewAttribute() { Attr attr = processor.newAttribute("name", "value"); Assert.assertEquals("name", attr.getName()); Assert.assertEquals("value", attr.getValue()); }
### Question: RequestDataBinder extends DataBinder { @SuppressWarnings("unchecked") public T bind() { MutablePropertyValues mpvs = new MutablePropertyValues(); for (String name : request.getParameterNames()) { addValue(mpvs, name, request.getParameterList(name)); } for (String name : request.getFormUploads().keySet()) { addValue(mpvs, name, request.getFormUploads(name)); } doBind(mpvs); return (T) getTarget(); } RequestDataBinder(T target, Request request); RequestDataBinder(T target, Request request, ConversionService conversionService); protected RequestDataBinder(T target); @SuppressWarnings("unchecked") T bind(); }### Answer: @Test public void doTest() { MockitoAnnotations.initMocks(this); Map<String, List<String>> paramters = new HashMap<>(); paramters.put(NAME, Arrays.asList("Doe")); paramters.put(INTEGER_LIST, Arrays.asList("1", "2", "3")); paramters.put(BIRTH_DATE, Arrays.asList("14.05.1944")); Mockito.when(request.getParameterNames()).thenReturn(paramters.keySet()); Mockito.when(request.getParameterList(Mockito.anyString())).then(new Answer<List<String>>() { public List<String> answer(InvocationOnMock invocation) throws Throwable { return paramters.get(invocation.getArgumentAt(0, String.class)); } }); Map<String, List<FormUpload>> formUploads = getFormUploads(); List<FormUpload> pictures = formUploads.get(PICTURE); Mockito.when(request.getFormUploads()).thenReturn(formUploads); Mockito.when(request.getFormUploads(PICTURE)).thenReturn(pictures); Mockito.when(request.getFormUploads(MORE_PICTURES)).thenReturn(pictures); ConfigurableConversionService conversionService = getConversionService(); RequestDataBinder<Person> requestDataBinder = new RequestDataBinder<Person>(new Person(), request, conversionService); Person person = requestDataBinder.bind(); validate(pictures, person); }
### Question: DataContainer { public void setItem(Object item) { this.item = item; setSingleResult(true); initItem(); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Collection<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); }### Answer: @Test public void testSetItem() { dataContainer.setItem(persons.get(0)); Assert.assertEquals(fieldProcessor, dataContainer.getFieldProcessor()); Assert.assertEquals(persons.get(0), dataContainer.getItem()); Assert.assertNull(dataContainer.getPageable()); Assert.assertNull(dataContainer.getPage()); Assert.assertTrue(dataContainer.isSingleResult()); Assert.assertNull(dataContainer.getItems()); Assert.assertNull(dataContainer.getWrappedData().isPaginate()); }
### Question: DataContainer { public void setPage(Collection<?> items, Pageable pageable) { setPage(items, pageable, false); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Collection<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); }### Answer: @Test public void testSetPage() { dataContainer.setPage(page); Assert.assertNull(dataContainer.getPageable()); Assert.assertEquals(page, dataContainer.getPage()); Assert.assertFalse(dataContainer.isSingleResult()); Assert.assertNull(dataContainer.getItems()); Assert.assertNull(dataContainer.getWrappedData().isPaginate()); }
### Question: DataContainer { public void setItems(Collection<?> items) { this.items = items; setSingleResult(false); initItems(items); setPageable(null); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Collection<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); }### Answer: @Test public void testSetItems() { dataContainer.setItems(persons); Assert.assertNull(dataContainer.getPageable()); Assert.assertNull(dataContainer.getPage()); Assert.assertFalse(dataContainer.isSingleResult()); Assert.assertEquals(persons, dataContainer.getItems()); Assert.assertFalse(dataContainer.getWrappedData().isPaginate()); }
### Question: AuthTools { public static String getMd5Digest(String input) { return getDigest(input, MessageDigestAlgorithms.MD5); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static String getSha1Digest(String input); static String getSha512Digest(String input); }### Answer: @Test public void testMd5Digest() { String md5Digest = AuthTools.getMd5Digest(testPattern); Assert.assertEquals("7C2AD50DBEA658E2F87DDE1609114237", md5Digest); }
### Question: AuthTools { public static String getSha1Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_1); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static String getSha1Digest(String input); static String getSha512Digest(String input); }### Answer: @Test public void testSha1Digest() { String sha1Digest = AuthTools.getSha1Digest(testPattern); Assert.assertEquals("746BDF044C80DD81336A522BF27D8C661947D3EF", sha1Digest); }
### Question: AuthTools { public static String getSha512Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_512); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static String getSha1Digest(String input); static String getSha512Digest(String input); }### Answer: @Test public void testSha512Digest() { String sha512Digest = AuthTools.getSha512Digest(testPattern); Assert.assertEquals( "AB9D85DC074D06B675DAEE7FA4A70C7D0BD8F9A284713DAA0E5689DAA9367DD10258E331D3494053B4F5A1084D7881455DB5AADB84BDFAF5638677ED1D1C4881", sha512Digest); }
### Question: ImageProcessor { public ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); float ratioWidth = (float) maxwidth / width; float ratioHeight = (float) maxHeight / height; float ratio = Math.min(ratioWidth, ratioHeight); int scaledWidth = Math.round(width * ratio); int scaledHeight = Math.round(height * ratio); return resize(scaledWidth, scaledHeight); } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath, boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight, int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); }### Answer: @Test public void testFitToWidthAndHeight() throws IOException { ImageProcessor ip = getSource(new File(targetFolder, "desert-512x384.jpg")); ip.fitToWidthAndHeight(512, 512); ImageMetaData metaData = new ImageProcessor(ip.getImage(), null, true).getMetaData(); assertDimensions(512, 384, metaData); }
### Question: PropertyHolder implements Properties { public String getString(String name, String defaultValue) { Property property = getProperty(name); if (null != property) { return property.getString(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); }### Answer: @Test public void testCustomString() { Assert.assertEquals("custom", propertyHolder.getString("customString")); Assert.assertEquals("string", propertyHolder.getString("emptyCustomString")); }
### Question: PropertyHolder implements Properties { public Boolean getBoolean(String name) { return getBoolean(name, null); } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); }### Answer: @Test public void testBoolean() { Assert.assertEquals(true, propertyHolder.getBoolean("boolean")); Assert.assertEquals(false, propertyHolder.getBoolean("bla", false)); }
### Question: PropertyHolder implements Properties { public Float getFloat(String name, Float defaultValue) { Property property = getProperty(name); if (null != property) { return property.getFloat(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); }### Answer: @Test public void testFloat() { Assert.assertEquals(Float.valueOf(4.5f), propertyHolder.getFloat("float")); Assert.assertEquals(Float.valueOf(1.2f), propertyHolder.getFloat("bla", 1.2f)); }
### Question: PropertyHolder implements Properties { public Double getDouble(String name, Double defaultValue) { Property property = getProperty(name); if (null != property) { return property.getDouble(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); }### Answer: @Test public void testDouble() { Assert.assertEquals(Double.valueOf(7.9d), propertyHolder.getDouble("double")); Assert.assertEquals(Double.valueOf(1.2d), propertyHolder.getDouble("bla", 1.2d)); }
### Question: PropertyHolder implements Properties { public List<String> getList(String name, String defaultValue, String delimiter) { List<String> result = new ArrayList<>(); String string = getString(name, defaultValue); if (null != string && string.length() > 0) { String[] splitted = string.split(delimiter); for (String value : splitted) { result.add(value.trim()); } } return Collections.unmodifiableList(result); } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); }### Answer: @Test public void testList() { Assert.assertEquals(Arrays.asList("1", "2"), propertyHolder.getList("list", ",")); Assert.assertEquals(Arrays.asList("3", "4"), propertyHolder.getList("bla", "3,4", ",")); }
### Question: PropertyHolder implements Properties { public java.util.Properties getProperties(String name) { String clob = getClob(name); if (null != clob) { java.util.Properties properties = new java.util.Properties(); try { properties.load(new ByteArrayInputStream(clob.getBytes())); } catch (IOException e) { throw new IllegalArgumentException("failed converting property '" + name + "' to java.util.Properties", e); } return properties; } return null; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); }### Answer: @Test public void testProperties() { Properties props = new Properties(); props.put("a", "1"); props.put("b", "2"); Assert.assertEquals(props, propertyHolder.getProperties("properties")); Assert.assertEquals(null, propertyHolder.getProperties("bla")); }
### Question: ImageProcessor { public ImageMetaData getMetaData() throws IOException { ImageInputStream input = new FileImageInputStream(sourceFile); Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(input); if (imageReaders.hasNext()) { ImageReader reader = imageReaders.next(); reader.setInput(input); ImageMetaData imageMetaData = new ImageMetaData(sourceFile, reader.getWidth(0), reader.getHeight(0)); input.close(); return imageMetaData; } else { input.close(); throw new IOException("no ImageReader found for " + sourceFile.getAbsolutePath()); } } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath, boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight, int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); }### Answer: @Test public void testMetaData() throws IOException { ImageProcessor ip = new ImageProcessor(sourceFile, null, true); ImageMetaData metaData = ip.getMetaData(); Assert.assertEquals(1024, metaData.getWidth()); Assert.assertEquals(768, metaData.getHeight()); Assert.assertEquals(845941L, metaData.getFileSize(), 0.0d); }
### Question: PropertyHolder implements Properties { public java.util.Properties getPlainProperties() { java.util.Properties props = new java.util.Properties(); Set<String> propertyNames = getPropertyNames(); for (String name : propertyNames) { Property property = getProperty(name); if (null != property) { String value = property.getString(); if (null == value) { value = property.getClob(); } if (null != value) { String shortName = name.substring(name.lastIndexOf(".") + 1); props.put(shortName, value); } } } return props; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); }### Answer: @Test public void testPlainProperties() { Properties plainProperties = propertyHolder.getPlainProperties(); Assert.assertEquals(plainProperties, propertyHolder.getPlainProperties()); }
### Question: ElementHelper { MetaData getFilteredMetaData(ApplicationRequest request, MetaData metaData, boolean write) { MetaData result = new MetaData(); if (null != metaData) { result.setBinding(metaData.getBinding()); result.setResultSelector(metaData.getResultSelector()); result.setBindClass(metaData.getBindClass()); result.setValidation(metaData.getValidation()); List<FieldDef> fieldDefinitions = metaData.getFields(); List<FieldDef> fields = filterFieldDefinitions(request, fieldDefinitions, write); result.getFields().addAll(fields); } return result; } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container, String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; }### Answer: @Test public void testNoData() { MetaData metaData2 = elementHelper.getFilteredMetaData(applicationRequest, metaData, false); Assert.assertTrue(metaData2.getFields().isEmpty()); metaData2 = elementHelper.getFilteredMetaData(applicationRequest, metaData, true); Assert.assertTrue(metaData2.getFields().isEmpty()); } @Test public void testRead() { FieldDef dateField = addField(metaData, "dateField"); dateField.setType(FieldType.DATE); dateField.setFormat("${i18n.message('dateFormat')}"); Mockito.when(applicationRequest.getMessage("dateFormat")).thenReturn("yyyy-MM-dd"); FieldDef field = addField(metaData, "readableField"); Label tooltip = new Label(); tooltip.setId("tooltip"); field.setTooltip(tooltip); FieldDef fieldNoPermission = addField(metaData, "fieldNoRead"); FieldDef conditionFalse = addField(metaData, "conditionFalse", "${1 eq 2}"); FieldDef conditionTrue = addField(metaData, "conditionTrue", "${1 eq 1}"); FieldDef conditionCurrent = addField(metaData, "conditionCurrent", "${current.id gt 5}"); Mockito.when(permissionProcessor.hasReadPermission(dateField)).thenReturn(true); Mockito.when(permissionProcessor.hasReadPermission(field)).thenReturn(true); Mockito.when(permissionProcessor.hasReadPermission(conditionFalse)).thenReturn(true); Mockito.when(permissionProcessor.hasReadPermission(conditionTrue)).thenReturn(true); Mockito.when(permissionProcessor.hasReadPermission(conditionCurrent)).thenReturn(true); Mockito.when(permissionProcessor.hasReadPermission(fieldNoPermission)).thenReturn(false); MetaData readableFields = elementHelper.getFilteredMetaData(applicationRequest, metaData, false); XmlValidator.validate(readableFields); } @Test public void testWrite() { FieldDef field = addField(metaData, "writeableField"); FieldDef fieldNoPermission = addField(metaData, "fieldNoWrite"); Mockito.when(permissionProcessor.hasWritePermission(field)).thenReturn(true); Mockito.when(permissionProcessor.hasWritePermission(fieldNoPermission)).thenReturn(false); Action action = new Action(); DatasourceRef dsRef = new DatasourceRef(); dsRef.setId("dsId"); action.setDatasource(dsRef); Mockito.when(pcp.getAction("eventId", "actionId")).thenReturn(action); MetaData writeableFields = elementHelper.getFilteredMetaData(applicationRequest, metaData, true); XmlValidator.validate(writeableFields); }
### Question: ElementHelper { public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Linkpanel navigation = applicationRequest.getApplicationConfig().getApplicationRootConfig().getNavigation(); if (null != navigation) { navigation = initLinkpanel(applicationRequest, pathInfo, navigation, parameterSupport); if (!(null == pageLinks || null == navigation)) { List<Link> links = navigation.getLinks(); for (Link link : links) { pageLinks.getLinks().add(link); } pageConfig.setLinkpanel(pageLinks); } else { pageConfig.setLinkpanel(navigation); } } } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container, String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; }### Answer: @Test public void testInitNavigation() { Linkpanel linkpanel = new Linkpanel(); linkpanel.setId("panel"); linkpanel.setLocation(PanelLocation.TOP); addLink(linkpanel, "link1", "target", "${1 eq 1}"); addLink(linkpanel, "link2", "target", "${1 eq 2}"); rootCfg.setNavigation(linkpanel); PageConfig pageConfig = new PageConfig(); pageConfig.setLinkpanel(new Linkpanel()); Mockito.when(permissionProcessor.hasPermissions(Mockito.any(PermissionOwner.class))).thenReturn(true); elementHelper.initNavigation(applicationRequest, path, pageConfig); XmlValidator.validate(pageConfig.getLinkpanel()); } @Test public void testInitNavigationNoPermission() { Linkpanel linkpanel = new Linkpanel(); Permissions permissions = new Permissions(); Permission p1 = new Permission(); p1.setRef("foo"); permissions.getPermissionList().add(p1); linkpanel.setPermissions(permissions); linkpanel.setId("panel"); linkpanel.setLocation(PanelLocation.TOP); addLink(linkpanel, "link1", "target", "${1 eq 1}"); addLink(linkpanel, "link2", "target", "${1 eq 2}"); rootCfg.setNavigation(linkpanel); PageConfig pageConfig = new PageConfig(); Linkpanel pageLinks = new Linkpanel(); pageLinks.setPermissions(new Permissions()); Link page = new Link(); page.setMode(Linkmode.INTERN); page.setLabel(new Label()); pageLinks.getLinks().add(page); pageConfig.setLinkpanel(pageLinks); Mockito.when(permissionProcessor.hasPermissions(Mockito.any(PermissionOwner.class))).thenReturn(true, false); elementHelper.initNavigation(applicationRequest, path, pageConfig); Assert.assertNull(pageConfig.getLinkpanel()); }
### Question: ElementHelper { Options getOptions(List<BeanOption> beanOptions) { OptionsImpl options = new OptionsImpl(); if (null != beanOptions) { for (BeanOption beanOption : beanOptions) { OptionImpl opt = new OptionImpl(beanOption.getName()); Map<QName, String> attributes = beanOption.getOtherAttributes(); for (Entry<QName, String> entry : attributes.entrySet()) { String optionName = entry.getKey().getLocalPart(); opt.addAttribute(optionName, entry.getValue()); } options.addOption(opt); } } return options; } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container, String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; }### Answer: @Test public void testGetOptions() { List<BeanOption> beanOptions = getOptions(); Options options = elementHelper.getOptions(beanOptions); BeanOption option = beanOptions.get(0); Assert.assertEquals("foobar", option.getOtherAttributes().get(new QName("id"))); Assert.assertEquals("${foo}", option.getOtherAttributes().get(new QName("id2"))); Assert.assertEquals("foobar", options.getOptionValue("action", "id")); Assert.assertEquals("${foo}", options.getOptionValue("action", "id2")); }
### Question: ElementHelper { void initOptions(List<BeanOption> beanOptions) { if (null != beanOptions) { for (BeanOption beanOption : beanOptions) { Map<QName, String> attributes = beanOption.getOtherAttributes(); for (Entry<QName, String> entry : attributes.entrySet()) { String value = expressionEvaluator.evaluate(entry.getValue(), String.class); entry.setValue(value); } } } } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container, String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; }### Answer: @Test public void testInitOptions() throws ProcessingException { Params referenceParams = new Params(); addParam(referenceParams, "foo", null, null); Params executionParams = new Params(); addParam(executionParams, "foo", "foobar", null); elementHelper.initializeParameters(DATASOURCE_TEST, applicationRequest, parameterSupport, referenceParams, executionParams); List<BeanOption> beanOptions = getOptions(); elementHelper.initOptions(beanOptions); BeanOption option = beanOptions.get(0); Assert.assertEquals("foobar", option.getOtherAttributes().get(new QName("id"))); Assert.assertEquals("foobar", option.getOtherAttributes().get(new QName("id2"))); }
### Question: ElementHelper { boolean conditionMatches(Condition condition) { return conditionMatches(getExpressionEvaluator(), condition); } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container, String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; }### Answer: @Test public void testConditionMatches() { Assert.assertTrue(elementHelper.conditionMatches(null)); Condition condition = new Condition(); Assert.assertTrue(elementHelper.conditionMatches(condition)); condition.setExpression("${1<2}"); Assert.assertTrue(elementHelper.conditionMatches(condition)); condition.setExpression("${1>2}"); Assert.assertFalse(elementHelper.conditionMatches(condition)); }
### Question: ElementHelper { public static Messages addMessages(Environment environment, Messages messages) { Messages messagesFromSession = environment.getAttribute(SESSION, Session.Environment.MESSAGES); if (messages.getMessageList().size() > 0) { if (null == messagesFromSession) { messagesFromSession = new Messages(); } messagesFromSession.getMessageList().addAll(messages.getMessageList()); environment.setAttribute(SESSION, Session.Environment.MESSAGES, messagesFromSession); if (LOGGER.isDebugEnabled()) { LOGGER.debug("messages : {}", messagesFromSession.getMessageList()); } } return messagesFromSession; } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container, String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; }### Answer: @Test public void testAddMessages() { Messages messages = new Messages(); Message firstMessage = new Message(); messages.getMessageList().add(firstMessage); Environment env = Mockito.mock(Environment.class); Messages sessionMessages = new Messages(); Message sessionMessage = new Message(); sessionMessages.getMessageList().add(sessionMessage); Mockito.when(env.getAttribute(Scope.SESSION, Session.Environment.MESSAGES)).thenReturn(sessionMessages); Messages addMessages = ElementHelper.addMessages(env, messages); Assert.assertEquals(sessionMessages, addMessages); Assert.assertTrue(addMessages.getMessageList().contains(firstMessage)); Assert.assertTrue(addMessages.getMessageList().contains(sessionMessage)); Mockito.verify(env).setAttribute(Scope.SESSION, Session.Environment.MESSAGES, sessionMessages); }
### Question: Command { public static int execute(String command, StreamConsumer<?> outputConsumer, StreamConsumer<?> errorConsumer) { try { LOGGER.debug("executing: '{}'", command); Process process = Runtime.getRuntime().exec(command); if (null != outputConsumer) { outputConsumer.consume(process.getInputStream()); } if (null != errorConsumer) { errorConsumer.consume(process.getErrorStream()); } return process.waitFor(); } catch (Exception e) { LOGGER.warn(String.format("error while executing: %s", command), e); } return ERROR; } static int execute(String command, StreamConsumer<?> outputConsumer, StreamConsumer<?> errorConsumer); static int execute(OperatingSystem os, String command, StreamConsumer<?> outputConsumer, StreamConsumer<?> errorConsumer); static final int ERROR; static final int WRONG_OS; }### Answer: @Test public void testDirectoryListing() { StringConsumer outputConsumer = new StringConsumer(); if (OperatingSystem.isWindows()) { Command.execute("dir /b /on", outputConsumer, null); } else { Command.execute("ls", outputConsumer, null); } List<String> result = outputConsumer.getResult(); if (null != result) { Assert.assertEquals(Arrays.asList("pom.xml", "src", "target"), result); } } @Test public void testWrongOs() { int result = 0; if (OperatingSystem.isWindows()) { result = Command.execute(OperatingSystem.LINUX, "dummy", null, null); } else { result = Command.execute(OperatingSystem.WINDOWS, "dummy", null, null); } Assert.assertEquals(Command.WRONG_OS, result); }
### Question: ElementHelper { void setSelectionTitles(Data data, ApplicationRequest applicationRequest) { setSelectionTitles(data.getSelections(), applicationRequest); for (SelectionGroup group : data.getSelectionGroups()) { setSelectionTitles(group.getSelections(), applicationRequest); } } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container, String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; }### Answer: @Test public void testSetSelectionTitles() { Data data = new Data(); Selection selection1 = new Selection(); Selection selection2 = new Selection(); data.getSelections().add(selection1); Label l2 = new Label(); Label l1 = new Label(); Label l3 = new Label(); l1.setId("id1"); l3.setId("id3"); l2.setId("id2"); selection1.setTitle(l1); selection2.setTitle(l2); OptionGroup optionGroup = new OptionGroup(); optionGroup.setLabel(l3); selection2.getOptionGroups().add(optionGroup); SelectionGroup selectionGroup = new SelectionGroup(); selectionGroup.getSelections().add(selection2); data.getSelectionGroups().add(selectionGroup); elementHelper.setSelectionTitles(data, applicationRequest); Assert.assertEquals("id1", l1.getValue()); Assert.assertEquals("id2", l2.getValue()); Assert.assertEquals("id3", l3.getValue()); }
### Question: ElementHelper { void addTemplates(ApplicationConfigProvider applicationConfigProvider, Config config) { List<Template> templates = config.getTemplates(); if (null != templates) { applicationConfigProvider.getApplicationRootConfig().getConfig().getTemplates().addAll(templates); } } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container, String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; }### Answer: @Test public void testAddTemplates() { Config config = new Config(); Template t1 = new Template(); t1.setOutputType("html"); t1.setPath("t1.xsl"); Template t2 = new Template(); t2.setOutputType("html"); t2.setPath("t2.xsl"); config.getTemplates().add(t1); config.getTemplates().add(t2); rootCfg.setConfig(new ApplicationConfig()); elementHelper.addTemplates(configProvider, config); Assert.assertEquals(config.getTemplates(), rootCfg.getConfig().getTemplates()); }
### Question: ElementHelper { public String getOutputPrefix(Environment env) { if (Boolean.TRUE.equals(env.removeAttribute(REQUEST, EnvironmentKeys.EXPLICIT_FORMAT))) { Path pathInfo = env.getAttribute(REQUEST, EnvironmentKeys.PATH_INFO); StringBuilder prefix = new StringBuilder().append(pathInfo.getGuiPath()); prefix.append(pathInfo.getOutputPrefix()).append(Path.SEPARATOR).append(pathInfo.getSiteName()); return prefix.append(Path.SEPARATOR).toString(); } return null; } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container, String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; }### Answer: @Test public void testGetOutputPrefix() { Environment env = Mockito.mock(Environment.class); Mockito.when(env.removeAttribute(Scope.REQUEST, EnvironmentKeys.EXPLICIT_FORMAT)).thenReturn(true); Path pathMock = Mockito.mock(Path.class); Mockito.when(pathMock.getGuiPath()).thenReturn("/manager"); Mockito.when(pathMock.getOutputPrefix()).thenReturn("/_html/_nonav"); Mockito.when(pathMock.getSiteName()).thenReturn("site"); Mockito.when(env.getAttribute(Scope.REQUEST, EnvironmentKeys.PATH_INFO)).thenReturn(pathMock); String outputPrefix = elementHelper.getOutputPrefix(env); Assert.assertEquals("/manager/_html/_nonav/site/", outputPrefix); }
### Question: ElementHelper { public Class<?>[] getValidationGroups(MetaData metaData, Object bindObject) { List<Class<?>> groups = new ArrayList<>(); ValidationGroups validationGroups = metaData.getValidation(); if (null != validationGroups) { getExpressionEvaluator().setVariable(AdapterBase.CURRENT, bindObject); for (ValidationGroups.Group group : new ArrayList<ValidationGroups.Group>(validationGroups.getGroups())) { String expression = group.getCondition(); Condition condition = new Condition(); condition.setExpression(expression); if (StringUtils.isBlank(expression) || conditionMatches(condition)) { try { groups.add(site.getSiteClassLoader().loadClass(group.getClazz())); } catch (ClassNotFoundException e) { LOGGER.error("validation group {} not found!", group.getClazz()); } } else { validationGroups.getGroups().remove(group); } } } return groups.toArray(new Class<?>[groups.size()]); } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container, String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; }### Answer: @Test public void testGetValidationGroups() { ValidationGroups groups = new ValidationGroups(); ValidationGroups.Group groupA = new ValidationGroups.Group(); groupA.setClazz(Serializable.class.getName()); groups.getGroups().add(groupA); ValidationGroups.Group groupB = new ValidationGroups.Group(); groupB.setClazz(Closeable.class.getName()); String condition = "${current eq 'foo'}"; groupB.setCondition(condition); groups.getGroups().add(groupB); metaData.setValidation(groups); Class<?>[] validationGroups = elementHelper.getValidationGroups(metaData, "foo"); Assert.assertArrayEquals(new Class[] { Serializable.class, Closeable.class }, validationGroups); Assert.assertEquals(condition, groupB.getCondition()); }
### Question: LabelSupport { public final void setLabels(Config config, ExpressionEvaluator expressionEvaluator, ParameterSupport fieldParameters) { if (null != config) { setLabel(config.getTitle(), expressionEvaluator, fieldParameters); setLabel(config.getDescription(), expressionEvaluator, fieldParameters); setLabels(config.getLabels(), expressionEvaluator, fieldParameters); } } LabelSupport(MessageSource messageSource, Locale locale); final void setLabels(Config config, ExpressionEvaluator expressionEvaluator, ParameterSupport fieldParameters); final void setLabels(Labels labels, ExpressionEvaluator expressionEvaluator, ParameterSupport fieldParameters); final void setLabel(Label label, ExpressionEvaluator expressionEvaluator, ParameterSupport fieldParameters); }### Answer: @Test public void testLabels() { LabelSupport labelSupport = getLabelSupport(); Labels labels = new Labels(); Config config = new Config(); config.setLabels(labels); Label l1 = new Label(); l1.setId(KEY); l1.setParams("foo,'bar',${id}"); labels.getLabels().add(l1); Label l2 = new Label(); l2.setId("key2"); labels.getLabels().add(l2); labelSupport.setLabels(config, expressionEvaluator, null); Assert.assertEquals(RESULT, l1.getValue()); Assert.assertEquals("some value", l2.getValue()); }
### Question: SelectionFactory extends OptionFactory<SelectionFactory.Selection> { public Selection getDateSelection(String id, String title, String value, String dateFormat) { Selection selection = getSimpleSelection(id, title, value, SelectionType.DATE); selection.setFormat(dateFormat); return selection; } Selection getTextSelection(String id, String title, String value); Selection getDateSelection(String id, String title, String value, String dateFormat); Selection getDateSelection(String id, String title, Date value, FastDateFormat dateFormat); Selection getSimpleSelection(String id, String title, String value, SelectionType type); }### Answer: @Test public void testGetDateSelection() { Selection selection = selectionFactory.getDateSelection("id", "title", "03.12.2015", "dd.MM.yyyy"); Assert.assertEquals("id", selection.getId()); Assert.assertEquals("title", selection.getTitle().getId()); Assert.assertEquals("id", selection.getOptions().get(0).getName()); Assert.assertEquals("03.12.2015", selection.getOptions().get(0).getValue()); Assert.assertEquals(SelectionType.DATE, selection.getType()); Assert.assertEquals("dd.MM.yyyy", selection.getFormat()); } @Test public void testGetDateSelectionFastDateFormat() throws ParseException { FastDateFormat fdf = FastDateFormat.getInstance("dd.MM.yyyy"); Date date = fdf.parse("17.01.2017"); Selection selection = selectionFactory.getDateSelection("id", "title", date, fdf); Assert.assertEquals("id", selection.getId()); Assert.assertEquals("title", selection.getTitle().getId()); Assert.assertEquals("id", selection.getOptions().get(0).getName()); Assert.assertEquals(fdf.format(date), selection.getOptions().get(0).getValue()); Assert.assertEquals(SelectionType.DATE, selection.getType()); Assert.assertEquals("dd.MM.yyyy", selection.getFormat()); }
### Question: SelectionFactory extends OptionFactory<SelectionFactory.Selection> { public Selection getTextSelection(String id, String title, String value) { return getSimpleSelection(id, title, value, SelectionType.TEXT); } Selection getTextSelection(String id, String title, String value); Selection getDateSelection(String id, String title, String value, String dateFormat); Selection getDateSelection(String id, String title, Date value, FastDateFormat dateFormat); Selection getSimpleSelection(String id, String title, String value, SelectionType type); }### Answer: @Test public void testGetTextSelection() { Selection selection = selectionFactory.getTextSelection("id", "title", "abc"); Assert.assertEquals("id", selection.getId()); Assert.assertEquals("title", selection.getTitle().getId()); Assert.assertEquals("id", selection.getOptions().get(0).getName()); Assert.assertEquals("abc", selection.getOptions().get(0).getValue()); Assert.assertEquals(SelectionType.TEXT, selection.getType()); }
### Question: AttributeWrapper implements Serializable { public String getSiteName() { return siteName; } AttributeWrapper(); AttributeWrapper(String siteName, Object value); Object getValue(); String getSiteName(); @Override String toString(); }### Answer: @Test public void test() { Assert.assertEquals("appng", new AttributeWrapper("appng", "foo").getSiteName()); SiteClassLoader siteClassLoader = new SiteClassLoader("thesite"); AttributeWrapper attributeWrapper = new AttributeWrapper("appng", new Permission()) { private static final long serialVersionUID = 1L; protected ClassLoader getClassloader(Object value) { return siteClassLoader; } }; Assert.assertEquals(siteClassLoader.getSiteName(), attributeWrapper.getSiteName()); }
### Question: DefaultFieldConverter extends ConverterBase { @Override public void setObject(FieldWrapper field, RequestContainer request) { String value = stripNonPrintableCharacter(request.getParameter(field.getBinding())); Object object = null; Class<?> targetClass = field.getTargetClass(); if (null != targetClass) { boolean notBlank = StringUtils.isNotBlank(value); if (!targetClass.isPrimitive() || notBlank) { object = conversionService.convert(value, targetClass); Object logValue = object; if (notBlank && FieldType.PASSWORD.equals(field.getType())) { logValue = value.replaceAll(".", "*"); } logSetObject(field, logValue); field.setObject(object); } } } DefaultFieldConverter(ExpressionEvaluator expressionEvaluator, ConversionService conversionService, Environment environment, MessageSource messageSource); @Override void setObject(FieldWrapper field, RequestContainer request); }### Answer: @Test public void testSetObject() throws Exception { fieldConverter.setObject(fieldWrapper, request); Assert.assertEquals(Boolean.TRUE, fieldWrapper.getObject()); } @Test public void testSetObjectEmptyValue() throws Exception { Mockito.when(request.getParameter(OBJECT)).thenReturn(""); fieldConverter.setObject(fieldWrapper, request); Assert.assertEquals(null, fieldWrapper.getObject()); } @Test(expected = ConversionException.class) public void testSetObjectInvalidValue() throws Exception { Mockito.when(request.getParameter(OBJECT)).thenReturn("blaa"); fieldConverter.setObject(fieldWrapper, request); } @Test public void testSetObjectNull() throws Exception { Mockito.when(request.getParameter(OBJECT)).thenReturn(null); fieldConverter.setObject(fieldWrapper, request); Assert.assertNull(fieldWrapper.getObject()); }
### Question: XHTML { public static String removeAttr(String tag, String attr) { String pattern = getAttributeExpression(attr); Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(tag); if (m.find()) { tag = tag.replaceAll(pattern, ""); } return tag; } static String removeAttr(String tag, String attr); static String setAttr(String tag, String attr, String value); static String getBody(String tag, String content); static String setBody(String tag, String value); static String getAttr(String tag, String attr); static String getTag(String tag); }### Answer: @Test public void testRemoveAttr() { String attr = "id"; String content = "<body id=\"top\" background=\"blue\">"; String expResult = "<body background=\"blue\">"; String result = XHTML.removeAttr(content, attr); assertEquals(expResult, result); attr = "body"; content = "<body>"; expResult = "<body>"; result = XHTML.removeAttr(content, attr); assertEquals(expResult, result); }
### Question: DefaultFieldConverter extends ConverterBase { static String stripNonPrintableCharacter(String value) { return StringNormalizer.removeNonPrintableCharacters(value); } DefaultFieldConverter(ExpressionEvaluator expressionEvaluator, ConversionService conversionService, Environment environment, MessageSource messageSource); @Override void setObject(FieldWrapper field, RequestContainer request); }### Answer: @Test public void testRemovalOfNonPrintableControlCharacter() { for (int c = 0; c < 32; c++) { if (c != 9 && c != 10 && c != 13) { String s = Character.toString((char) c); Assert.assertEquals("", DefaultFieldConverter.stripNonPrintableCharacter(s)); } } int[] allowedContrChar = { 9, 10, 13 }; for (int c : allowedContrChar) { String s = Character.toString((char) c); Assert.assertEquals(s, DefaultFieldConverter.stripNonPrintableCharacter(s)); } for (int c = 32; c < 127; c++) { String s = Character.toString((char) c); Assert.assertEquals(s, DefaultFieldConverter.stripNonPrintableCharacter(s)); } for (int c = 127; c < 160; c++) { String s = Character.toString((char) c); Assert.assertEquals("", DefaultFieldConverter.stripNonPrintableCharacter(s)); } for (int c = 160; c < 65535; c++) { String s = Character.toString((char) c); Assert.assertEquals(s, DefaultFieldConverter.stripNonPrintableCharacter(s)); } }
### Question: ListFieldConverter extends ConverterBase { @Override public void setObject(FieldWrapper field, RequestContainer request) { String name = field.getBinding(); BeanWrapper wrapper = field.getBeanWrapper(); wrapper.setAutoGrowNestedPaths(true); List<String> values = request.getParameterList(name); Class<?> propertyType = getType(wrapper, name); if (null != values && wrapper.isReadableProperty(name)) { if (FieldType.LIST_OBJECT.equals(field.getType())) { List<FieldDef> innerFields = new ArrayList<>(field.getFields()); field.getFields().clear(); int maxIndex = 0; Pattern pattern = Pattern.compile("^" + Pattern.quote(field.getBinding()) + "\\[(\\d+)\\]\\..+$"); for (String paramName : request.getParameterNames()) { Matcher matcher = pattern.matcher(paramName); if (matcher.matches()) { Integer index = Integer.parseInt(matcher.group(1)); maxIndex = Math.max(maxIndex, index); } } for (int i = 0; i <= maxIndex; i++) { addNestedFields(field, innerFields, i); } } else if (conversionService.canConvert(String.class, propertyType)) { if (isCollection(wrapper, name)) { values.forEach(value -> { Object result = conversionService.convert(value, propertyType); if (null != result) { addCollectionValue(wrapper, name, result); } }); logSetObject(field, wrapper.getPropertyValue(name)); } else if (values.size() == 1) { Object result = conversionService.convert(values.get(0), propertyType); logSetObject(field, result); field.setObject(result); } } else { LOGGER.debug("can not convert from {} to {}", String.class, propertyType); } } } ListFieldConverter(ConversionService conversionService); @Override void setString(FieldWrapper field); @Override void setObject(FieldWrapper field, RequestContainer request); @Override Datafield addField(DatafieldOwner dataFieldOwner, FieldWrapper fieldWrapper); }### Answer: @Test public void testSetObject() throws Exception { fieldConverter.setObject(fieldWrapper, request); Assert.assertEquals(numbers, fieldWrapper.getObject()); } @Test public void testSetObjectEmptyValue() { Mockito.when(request.getParameterList(OBJECT)).thenReturn(Arrays.asList("")); fieldConverter.setObject(fieldWrapper, request); Assert.assertEquals(EMPTY_LIST, fieldWrapper.getObject()); } @Test(expected = ConversionException.class) public void testSetObjectInvalidValue() { Mockito.when(request.getParameterList(OBJECT)).thenReturn(Arrays.asList("assdsd")); fieldConverter.setObject(fieldWrapper, request); Assert.assertEquals(EMPTY_LIST, fieldWrapper.getObject()); String content = fieldWrapper.getMessages().getMessageList().get(0).getContent(); Assert.assertEquals(IntegerFieldConverter.ERROR_KEY, content); } @Test public void testSetObjectNull() { Mockito.when(request.getParameterList(OBJECT)).thenReturn(null); fieldConverter.setObject(fieldWrapper, request); Assert.assertEquals(EMPTY_LIST, fieldWrapper.getObject()); }
### Question: XHTML { public static String setAttr(String tag, String attr, String value) { Pattern p = Pattern.compile(getAttributeExpression(attr)); Matcher m = p.matcher(tag); if (m.find()) { tag = tag.replaceFirst(getAttributeExpression(attr), " " + attr + "=\"" + value + "\""); } else { p = Pattern.compile("(<\\w+?)([\\s|>])"); m = p.matcher(tag); if (m.find()) { String suffix = (m.group(2).equals(">")) ? ">" : " "; tag = m.replaceFirst(m.group(1) + " " + attr + "=\"" + value + "\"" + suffix); } } return tag; } static String removeAttr(String tag, String attr); static String setAttr(String tag, String attr, String value); static String getBody(String tag, String content); static String setBody(String tag, String value); static String getAttr(String tag, String attr); static String getTag(String tag); }### Answer: @Test public void testSetAttr() { String attr = "background"; String value = "blue"; String content = "<body>"; String expResult = "<body background=\"blue\">"; String result = XHTML.setAttr(content, attr, value); assertEquals(expResult, result); content = "<body id=\"foo\">"; expResult = "<body background=\"blue\" id=\"foo\">"; result = XHTML.setAttr(content, attr, value); assertEquals(expResult, result); content = "<body id=\"foo\">"; expResult = "<body id=\"bar\">"; result = XHTML.setAttr(content, "id", "bar"); assertEquals(expResult, result); }
### Question: AnnualPercentageYield implements MonetaryOperator { public static AnnualPercentageYield of(Rate rate, int periods){ return new AnnualPercentageYield(rate, periods); } private AnnualPercentageYield(Rate rate, int periods); int getPeriods(); Rate getRate(); static AnnualPercentageYield of(Rate rate, int periods); static Rate calculate(Rate rate, int periods); static MonetaryAmount calculate(MonetaryAmount amount, Rate rate, int periods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer: @Test public void of_notNull() throws Exception { AnnualPercentageYield ci = AnnualPercentageYield.of( Rate.of(0.05),1 ); assertNotNull(ci); } @Test public void calculate_zeroPeriods() throws Exception { AnnualPercentageYield ci = AnnualPercentageYield.of( Rate.of(0.05),0 ); } @Test public void calculate_twoPeriods() throws Exception { AnnualPercentageYield ci = AnnualPercentageYield.of( Rate.of(0.05),2 ); assertEquals(Money.of(1,"CHF").with(ci),Money.of(0.050625,"CHF")); assertEquals(Money.of(0,"CHF").with(ci),Money.of(0.0,"CHF")); assertEquals(Money.of(-1,"CHF").with(ci),Money.of(-0.050625,"CHF")); }
### Question: PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer: @Test public void getPeriods() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.03,3654) ); assertEquals(val.getPeriods(), 3654); } @Test public void of_Period1() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.05, 1) ); assertNotNull(val); } @Test public void of_Period0() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.08,0) ); assertNotNull(val); } @Test public void calculate_Periods0() throws Exception { Money m = Money.of(10, "CHF"); PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.05, 0) ); assertEquals(Money.of(0,"CHF"), m.with(val)); val = PresentValueOfAnnuity.of( RateAndPeriods.of(-0.05, 0) ); assertEquals(Money.of(0,"CHF"), m.with(val)); } @Test public void calculate_Periods1() throws Exception { Money m = Money.of(10, "CHF"); PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.05, 1) ); assertEquals(Money.of(9.523809523809524,"CHF").getNumber().doubleValue(), m.with(val).getNumber().doubleValue(),0.000001d); val = PresentValueOfAnnuity.of( RateAndPeriods.of(-0.05, 1) ); assertEquals(Money.of(10.5263157894736842105263,"CHF").getNumber().doubleValue(), m.with(val).getNumber().doubleValue(), 0.00001d); } @Test public void calculate_PeriodsN() throws Exception { Money m = Money.of(10, "CHF"); PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.05, 10) ); assertEquals(Money.of(77.21734929184812,"CHF").getNumber().numberValue(BigDecimal.class) .doubleValue(), m.with(val).getNumber().numberValue(BigDecimal.class) .doubleValue(), 0.00000000000001d); val = PresentValueOfAnnuity.of( RateAndPeriods.of(-0.05, 10) ); assertEquals(Money.of(134.0365140230186,"CHF").getNumber().numberValue(BigDecimal.class).doubleValue(), m.with(val).getNumber().numberValue(BigDecimal.class).doubleValue(), 0.000000000000001d); } @Test public void getRate() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.03,1) ); assertEquals(val.getRate(), Rate.of(0.03)); }
### Question: PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer: @Test public void apply() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.08, 10) ); Money m = Money.of(10, "CHF"); assertEquals(val.apply(m), m.with(val)); }
### Question: PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValueOfAnnuity{" + "\n " + rateAndPeriods + '}'; } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer: @Test public void toStringTest() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.05, 10) ); assertEquals("PresentValueOfAnnuity{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=10}}", val.toString()); }
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { public Rate getDiscountRate() { return discountRate; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); Rate getDiscountRate(); Rate getGrowthRate(); int getPeriods(); static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods); static MonetaryAmount calculate(MonetaryAmount firstPayment, Rate discountRate, Rate growthRate, int periods); @Override MonetaryAmount apply(MonetaryAmount firstPayment); @Override String toString(); }### Answer: @Test public void getDiscountRate() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.01),Rate.of(0.03),1 ); assertEquals(val.getDiscountRate(), Rate.of(0.01)); }
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { public Rate getGrowthRate() { return growthRate; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); Rate getDiscountRate(); Rate getGrowthRate(); int getPeriods(); static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods); static MonetaryAmount calculate(MonetaryAmount firstPayment, Rate discountRate, Rate growthRate, int periods); @Override MonetaryAmount apply(MonetaryAmount firstPayment); @Override String toString(); }### Answer: @Test public void getGrowthRate() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.01),Rate.of(0.03),1 ); assertEquals(val.getGrowthRate(), Rate.of(0.03)); }
### Question: BalloonLoanPayment extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amountPV) { if(!balloonAmount.getCurrency().equals(amountPV.getCurrency())){ throw new MonetaryException("Currency mismatch: " + balloonAmount.getCurrency() + " <> "+amountPV.getCurrency()); } return calculate(amountPV, balloonAmount, rateAndPeriods); } private BalloonLoanPayment(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount); MonetaryAmount getBalloonAmount(); static BalloonLoanPayment of(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount); @Override MonetaryAmount apply(MonetaryAmount amountPV); @Override String toString(); static MonetaryAmount calculate(MonetaryAmount amountPV, MonetaryAmount balloonAmount, RateAndPeriods rateAndPeriods); }### Answer: @Test public void apply() throws Exception { BalloonLoanPayment ci = BalloonLoanPayment.of( RateAndPeriods.of(0.05,2), Money.of(5, "CHF") ); assertEquals(ci.apply(Money.of(1,"CHF")).with(Monetary.getDefaultRounding()),Money.of(-1.9,"CHF")); }
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { public int getPeriods() { return periods; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); Rate getDiscountRate(); Rate getGrowthRate(); int getPeriods(); static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods); static MonetaryAmount calculate(MonetaryAmount firstPayment, Rate discountRate, Rate growthRate, int periods); @Override MonetaryAmount apply(MonetaryAmount firstPayment); @Override String toString(); }### Answer: @Test public void getPeriods() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.01),Rate.of(0.03),3654 ); assertEquals(val.getPeriods(), 3654); }
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); Rate getDiscountRate(); Rate getGrowthRate(); int getPeriods(); static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods); static MonetaryAmount calculate(MonetaryAmount firstPayment, Rate discountRate, Rate growthRate, int periods); @Override MonetaryAmount apply(MonetaryAmount firstPayment); @Override String toString(); }### Answer: @Test public void of_Period1() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.07), Rate.of(0.05), 1 ); assertNotNull(val); } @Test public void of_Period0() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.07),Rate.of(0.08),0 ); assertNotNull(val); } @Test public void calculate_Periods0() throws Exception { Money m = Money.of(10, "CHF"); FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(-0.05), Rate.of(0.05), 0 ); assertEquals(Money.of(0,"CHF"), m.with(val)); val = FutureValueGrowingAnnuity.of( Rate.of(0.05), Rate.of(-0.05), 0 ); assertEquals(Money.of(0,"CHF"), m.with(val)); } @Test(expected = MonetaryException.class) public void of_InvalidWithEqualRates() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.05), Rate.of(0.05), 0 ); } @Test public void calculate_Periods1() throws Exception { Money m = Money.of(10, "CHF"); FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(-0.05), Rate.of(0.05), 1 ); assertEquals(Money.of(0,"CHF"), m.with(val)); val = FutureValueGrowingAnnuity.of( Rate.of(0.05), Rate.of(-0.05), 1 ); assertEquals(Money.of(10,"CHF"), m.with(val)); } @Test public void calculate_PeriodsN() throws Exception { Money m = Money.of(10, "CHF"); FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(-0.05), Rate.of(0.05), 10 ); assertEquals(Money.of(0.0,"CHF").getNumber().numberValue(BigDecimal.class) .doubleValue(), m.with(val).getNumber().numberValue(BigDecimal.class) .doubleValue(), 0.00000000000001d); val = FutureValueGrowingAnnuity.of( Rate.of(0.05), Rate.of(-0.05), 10 ); assertEquals(Money.of(103.0157687539062,"CHF").getNumber().numberValue(BigDecimal.class).doubleValue(), m.with(val).getNumber().numberValue(BigDecimal.class).doubleValue(), 0.000000000000001d); }
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount firstPayment) { return calculate(firstPayment, discountRate, growthRate, periods); } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); Rate getDiscountRate(); Rate getGrowthRate(); int getPeriods(); static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods); static MonetaryAmount calculate(MonetaryAmount firstPayment, Rate discountRate, Rate growthRate, int periods); @Override MonetaryAmount apply(MonetaryAmount firstPayment); @Override String toString(); }### Answer: @Test public void apply() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.07), Rate.of(0.08), 10 ); Money m = Money.of(10, "CHF"); assertEquals(val.apply(m), m.with(val)); }
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { @Override public String toString() { return "FutureValueGrowingAnnuity{" + "discountRate=" + discountRate + ", growthRate=" + growthRate + ", periods=" + periods + '}'; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); Rate getDiscountRate(); Rate getGrowthRate(); int getPeriods(); static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods); static MonetaryAmount calculate(MonetaryAmount firstPayment, Rate discountRate, Rate growthRate, int periods); @Override MonetaryAmount apply(MonetaryAmount firstPayment); @Override String toString(); }### Answer: @Test public void toStringTest() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.07), Rate.of(0.05), 10 ); assertEquals("FutureValueGrowingAnnuity{discountRate=Rate[0.07], growthRate=Rate[0.05], periods=10}", val.toString()); }
### Question: PresentValue extends AbstractRateAndPeriodBasedOperator { public static PresentValue of(RateAndPeriods rateAndPeriods) { return new PresentValue(rateAndPeriods); } private PresentValue(RateAndPeriods rateAndPeriods); static PresentValue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer: @Test public void testOfAndApply() throws Exception { MonetaryAmountFactory fact = Monetary.getDefaultAmountFactory(); MonetaryAmount money = fact.setCurrency("CHF").setNumber(100).create(); MonetaryOperator rounding = Monetary.getRounding(RoundingQueryBuilder.of().setScale(2).set(RoundingMode.HALF_EVEN) .build()); assertEquals(fact.setNumber(95.24).create(), money.with(PresentValue.of(RateAndPeriods.of(0.05, 1))).with(rounding)); assertEquals(fact.setNumber(90.70).create(), money.with(PresentValue.of(RateAndPeriods.of(0.05, 2))).with(rounding)); assertEquals(fact.setNumber(47.51).create(), money.with(PresentValue.of(RateAndPeriods.of(0.07, 11))).with(rounding)); assertEquals(fact.setNumber(100.00).create(), money.with(PresentValue.of(RateAndPeriods.of(0.05, 0))).with(rounding)); assertEquals(fact.setNumber(100.00).create(), money.with(PresentValue.of(RateAndPeriods.of(-0.05, 0))).with(rounding)); assertEquals(fact.setNumber(105.26).create(), money.with(PresentValue.of(RateAndPeriods.of(-0.05, 1))).with(rounding)); assertEquals(fact.setNumber(110.80).create(), money.with(PresentValue.of(RateAndPeriods.of(-0.05, 2))).with(rounding)); assertEquals(fact.setNumber(222.17).create(), money.with(PresentValue.of(RateAndPeriods.of(-0.07, 11))).with(rounding)); }
### Question: ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); } private ContinuousCompoundInterest(RateAndPeriods rateAndPeriods); static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer: @Test public void of_notNull() throws Exception { ContinuousCompoundInterest ci = ContinuousCompoundInterest.of( RateAndPeriods.of(0.05,1) ); assertNotNull(ci); } @Test public void of_correctRate() throws Exception { ContinuousCompoundInterest ci = ContinuousCompoundInterest.of( RateAndPeriods.of(0.0234,1) ); assertNotNull(ci.getRate()); assertEquals(ci.getRate(), Rate.of(0.0234)); ci = ContinuousCompoundInterest.of( RateAndPeriods.of(0.05,1) ); assertNotNull(ci.getRate()); assertEquals(ci.getRate(), Rate.of(0.05)); } @Test public void of_correctPeriods() throws Exception { ContinuousCompoundInterest ci = ContinuousCompoundInterest.of( RateAndPeriods.of(0.05,1) ); assertEquals(ci.getPeriods(), 1); ci = ContinuousCompoundInterest.of( RateAndPeriods.of(0.05,234) ); assertEquals(ci.getPeriods(), 234); } @Test public void calculate_zeroPeriods() throws Exception { ContinuousCompoundInterest ci = ContinuousCompoundInterest.of( RateAndPeriods.of(0.05,0) ); assertEquals(Money.of(10.03,"CHF").with(ci), Money.of(0,"CHF")); assertEquals(Money.of(0,"CHF").with(ci), Money.of(0,"CHF")); assertEquals(Money.of(-20.45,"CHF").with(ci), Money.of(0,"CHF")); } @Test public void calculate_onePeriods() throws Exception { ContinuousCompoundInterest ci = ContinuousCompoundInterest.of( RateAndPeriods.of(0.05,1) ); assertEquals(Money.of(1,"CHF").with(ci).getNumber().doubleValue(), 0.0512d, 0.0001d); assertEquals(Money.of(0,"CHF").with(ci).getNumber().doubleValue(), 0.0d, 0.000d); assertEquals(Money.of(-1,"CHF").with(ci).getNumber().doubleValue(), -0.0512d, 0.0001d); } @Test public void calculate_twoPeriods() throws Exception { ContinuousCompoundInterest ci = ContinuousCompoundInterest.of( RateAndPeriods.of(0.05,2) ); assertEquals(Money.of(1,"CHF").with(ci).getNumber().doubleValue(), 0.10517064178387361, 0.000000001d); assertEquals(Money.of(0,"CHF").with(ci).getNumber().doubleValue(),0d, 0.0d); assertEquals(Money.of(-1,"CHF").with(ci).getNumber().doubleValue(), -0.10517064178387361, 0.000000001d); }
### Question: PresentValue extends AbstractRateAndPeriodBasedOperator { public static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods){ Objects.requireNonNull(amount, "Amount required"); Objects.requireNonNull(rateAndPeriods, "RateAndPeriods required"); return amount.divide(PresentValueFactor.calculate(rateAndPeriods)); } private PresentValue(RateAndPeriods rateAndPeriods); static PresentValue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer: @Test public void testCalculate() throws Exception { MonetaryAmountFactory fact = Monetary.getDefaultAmountFactory(); MonetaryAmount money = fact.setNumber(100).setCurrency("CHF").create(); MonetaryOperator rounding = Monetary.getRounding(RoundingQueryBuilder.of().setScale(2).set(RoundingMode.HALF_EVEN) .build()); assertEquals(fact.setNumber(95.24).create(), PresentValue.calculate(money, RateAndPeriods.of(0.05, 1)).with(rounding)); assertEquals(fact.setNumber(90.70).create(), PresentValue.calculate(money, RateAndPeriods.of(0.05, 2)).with(rounding)); assertEquals(fact.setNumber(47.51).create(), PresentValue.calculate(money, RateAndPeriods.of(0.07, 11)).with(rounding)); }
### Question: PresentValue extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValue{" + "\n " + rateAndPeriods + '}'; } private PresentValue(RateAndPeriods rateAndPeriods); static PresentValue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer: @Test public void testToString() throws Exception { assertEquals("PresentValue{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=1}}", PresentValue.of(RateAndPeriods.of(0.05, 1)).toString()); assertEquals("PresentValue{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=2}}", PresentValue.of(RateAndPeriods.of(0.05, 2)).toString()); assertEquals("PresentValue{\n" + " RateAndPeriods{\n" + " rate=Rate[0.07]\n" + " periods=11}}", PresentValue.of(RateAndPeriods.of(0.07, 11)).toString()); }
### Question: PresentValueOfAnnuityPaymentFactor { public static BigDecimal calculate(RateAndPeriods rateAndPeriods) { Objects.requireNonNull(rateAndPeriods, "Rate required."); if(rateAndPeriods.getPeriods()==0){ return BigDecimal.ZERO; } BigDecimal fact1 = one().add(rateAndPeriods.getRate().get()).pow(-rateAndPeriods.getPeriods(), mathContext()); BigDecimal counter = one().subtract(fact1); return counter.divide(rateAndPeriods.getRate().get(), mathContext()); } private PresentValueOfAnnuityPaymentFactor(); static BigDecimal calculate(RateAndPeriods rateAndPeriods); }### Answer: @Test public void calculate_periods0() throws Exception { assertEquals(BigDecimal.valueOf(0), PresentValueOfAnnuityPaymentFactor.calculate(RateAndPeriods.of(0.05, 0))); assertEquals(BigDecimal.valueOf(0), PresentValueOfAnnuityPaymentFactor.calculate(RateAndPeriods.of(-0.05, 0))); } @Test public void calculate_periods1() throws Exception { assertEquals(BigDecimal.valueOf(0.952380952380952), PresentValueOfAnnuityPaymentFactor.calculate(RateAndPeriods.of(0.05, 1))); assertEquals(BigDecimal.valueOf(1.05263157894736), PresentValueOfAnnuityPaymentFactor.calculate(RateAndPeriods.of(-0.05, 1))); } @Test public void calculate_periods10() throws Exception { assertEquals(BigDecimal.valueOf(7.721734929184812), PresentValueOfAnnuityPaymentFactor.calculate(RateAndPeriods.of(0.05, 10))); assertEquals(BigDecimal.valueOf(13.40365140230186), PresentValueOfAnnuityPaymentFactor.calculate(RateAndPeriods.of(-0.05, 10))); }
### Question: PriceToBookValue { public static BigDecimal calculate(MonetaryAmount marketPricePerShare, MonetaryAmount bookValuePerShare) { BigDecimal marketPricePerShareValue = BigDecimal.valueOf(marketPricePerShare.getNumber().doubleValueExact()); BigDecimal bookValuePerShareValue = BigDecimal.valueOf(bookValuePerShare.getNumber().doubleValueExact()); return marketPricePerShareValue.divide(bookValuePerShareValue, MathContext.DECIMAL64); } private PriceToBookValue(); static BigDecimal calculate(MonetaryAmount marketPricePerShare, MonetaryAmount bookValuePerShare); }### Answer: @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.5), PriceToBookValue.calculate(MARKET_PRICE_PER_SHARE, BOOK_VALUE_PER_SHARE)); }
### Question: DividendPayoutRatio { public static BigDecimal calculate(MonetaryAmount dividends, MonetaryAmount netIncome) { BigDecimal dividendsValue = BigDecimal.valueOf(dividends.getNumber().doubleValueExact()); BigDecimal netIncomeValue = BigDecimal.valueOf(netIncome.getNumber().doubleValueExact()); return dividendsValue.divide(netIncomeValue, MathContext.DECIMAL64); } private DividendPayoutRatio(); static BigDecimal calculate(MonetaryAmount dividends, MonetaryAmount netIncome); }### Answer: @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.8), DividendPayoutRatio.calculate(DIVIDENDS, NET_INCOME)); }
### Question: GeometricMeanReturn { public static double calculate(List<Rate> ratesOfReturn) { BigDecimal product = BigDecimal.ONE; for (Rate rateOfReturn : ratesOfReturn) { if (rateOfReturn == null) { throw new IllegalArgumentException("The list of rates cannot contain null elements"); } product = product.multiply(rateOfReturn.get().add(BigDecimal.ONE)); } return Math.pow(product.doubleValue(), 1 / (double) ratesOfReturn.size()) - 1; } private GeometricMeanReturn(); static double calculate(List<Rate> ratesOfReturn); }### Answer: @Test public void testCalculate() { assertEquals(0.0871, GeometricMeanReturn.calculate(RATES_OF_RETURN), 0.0001); } @Test(expected = IllegalArgumentException.class) public void testCalculateWithNullRatesThrowsException() { GeometricMeanReturn.calculate(Arrays.asList(Rate.of(0.1), Rate.of(0.1), null, Rate.of(0.5))); }
### Question: NetAssetValue { public static MonetaryAmount calculate(MonetaryAmount fundAssets, MonetaryAmount fundLiabilities, double outstandingShares) { return fundAssets.subtract(fundLiabilities).divide(outstandingShares); } private NetAssetValue(); static MonetaryAmount calculate(MonetaryAmount fundAssets, MonetaryAmount fundLiabilities, double outstandingShares); }### Answer: @Test public void testCalculate() { assertEquals(Money.of(9, "GBP"), NetAssetValue.calculate(ASSETS, FUND_LIABILITIES, OUTSTANDING_SHARES)); }
### Question: CapitalGainsYield { public static BigDecimal calculate(MonetaryAmount initialStockPrice, MonetaryAmount stockPriceAfterFirstPeriod) { BigDecimal initialStockPriceValue = BigDecimal.valueOf(initialStockPrice.getNumber().doubleValueExact()); BigDecimal stockValueAfterFirstPeriod = BigDecimal.valueOf(stockPriceAfterFirstPeriod.getNumber().doubleValueExact()); return stockValueAfterFirstPeriod.subtract(initialStockPriceValue).divide(initialStockPriceValue, MathContext.DECIMAL64); } private CapitalGainsYield(); static BigDecimal calculate(MonetaryAmount initialStockPrice, MonetaryAmount stockPriceAfterFirstPeriod); }### Answer: @Test public void testCalculate() { assertEquals(0.81301, CapitalGainsYield.calculate(INITIAL_STOCK_PRICE, STOCK_PRICE_AFTER_FIRST_PERIOD).doubleValue(), 0.00001); }
### Question: CurrentYield { public static BigDecimal calculate(MonetaryAmount annualCoupons, MonetaryAmount currentBondPrice) { BigDecimal annualCouponsValue = BigDecimal.valueOf(annualCoupons.getNumber().doubleValueExact()); BigDecimal currentBondPriceValue = BigDecimal.valueOf(currentBondPrice.getNumber().doubleValueExact()); return annualCouponsValue.divide(currentBondPriceValue, MathContext.DECIMAL64); } private CurrentYield(); static BigDecimal calculate(MonetaryAmount annualCoupons, MonetaryAmount currentBondPrice); }### Answer: @Test public void testCalculate() { assertEquals(0.1111, CurrentYield.calculate(ANNUAL_COUPONS, CURRENT_BOND_PRICE).doubleValue(), 0.0001); }
### Question: DilutedEarningsPerShare { public static MonetaryAmount calculate(MonetaryAmount netIncome, BigDecimal averageShares, BigDecimal otherConvertibleInstruments) { return netIncome.divide(averageShares.add(otherConvertibleInstruments)); } private DilutedEarningsPerShare(); static MonetaryAmount calculate(MonetaryAmount netIncome, BigDecimal averageShares, BigDecimal otherConvertibleInstruments); }### Answer: @Test public void testCalculate() { assertEquals(Money.of(11, "GBP"), DilutedEarningsPerShare.calculate(NET_INCOME, AVERAGE_SHARES, OTHER_CONVERTIBLE_INSTRUMENTS)); }
### Question: DividendYield { public static BigDecimal calculate(MonetaryAmount dividends, MonetaryAmount initialPrice) { BigDecimal dividendsValue = BigDecimal.valueOf(dividends.getNumber().doubleValueExact()); BigDecimal initialPriceValue = BigDecimal.valueOf(initialPrice.getNumber().doubleValueExact()); return dividendsValue.divide(initialPriceValue, MathContext.DECIMAL64); } private DividendYield(); static BigDecimal calculate(MonetaryAmount dividends, MonetaryAmount initialPrice); }### Answer: @Test public void testCalculate() { assertEquals(0.04, DividendYield.calculate(DIVIDENDS, INITIAL_PRICE).doubleValue()); }
### Question: PriceToSalesRatio { public static BigDecimal calculate(MonetaryAmount sharePrice, MonetaryAmount salesPerShare) { BigDecimal sharePriceValue = BigDecimal.valueOf(sharePrice.getNumber().doubleValueExact()); BigDecimal salesPerShareValue = BigDecimal.valueOf(salesPerShare.getNumber().doubleValueExact()); return sharePriceValue.divide(salesPerShareValue, MathContext.DECIMAL64); } private PriceToSalesRatio(); static BigDecimal calculate(MonetaryAmount sharePrice, MonetaryAmount salesPerShare); }### Answer: @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.2), PriceToSalesRatio.calculate(SHARE_PRICE, SALES_PER_SHARE)); }
### Question: BookValuePerShare { public static MonetaryAmount calculate(MonetaryAmount equity, int numberOfCommonShares) { return equity.divide(numberOfCommonShares); } private BookValuePerShare(); static MonetaryAmount calculate(MonetaryAmount equity, int numberOfCommonShares); }### Answer: @Test public void testCalculate() { assertEquals(Money.of(10, "GBP"), BookValuePerShare.calculate(EQUITY, NUMBER_OF_COMMON_SHARES)); }
### Question: RiskPremium { public static BigDecimal calculate(Rate assetReturn, Rate riskFreeReturn) { return assetReturn.get().subtract(riskFreeReturn.get()); } private RiskPremium(); static BigDecimal calculate(Rate assetReturn, Rate riskFreeReturn); static BigDecimal calculateWithCAPM(BigDecimal beta, Rate marketReturn, Rate riskFreeReturn); }### Answer: @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.04), RiskPremium.calculate(ASSET_RETURN, RISK_FREE_RETURN)); }
### Question: RiskPremium { public static BigDecimal calculateWithCAPM(BigDecimal beta, Rate marketReturn, Rate riskFreeReturn) { return beta.multiply(marketReturn.get().subtract(riskFreeReturn.get())); } private RiskPremium(); static BigDecimal calculate(Rate assetReturn, Rate riskFreeReturn); static BigDecimal calculateWithCAPM(BigDecimal beta, Rate marketReturn, Rate riskFreeReturn); }### Answer: @Test public void testCalculateWithCAPM() { assertEquals(BigDecimal.valueOf(0.025), RiskPremium.calculateWithCAPM(BETA, MARKET_RETURN, RISK_FREE_RETURN)); }
### Question: BidAskSpread { public static MonetaryAmount calculate(MonetaryAmount askPrice, MonetaryAmount bidPrice) { return askPrice.subtract(bidPrice); } private BidAskSpread(); static MonetaryAmount calculate(MonetaryAmount askPrice, MonetaryAmount bidPrice); }### Answer: @Test public void testCalculate() { assertEquals(Money.of(0.05, "GBP"), BidAskSpread.calculate(ASK_PRICE, BID_PRICE)); }
### Question: EarningsPerShare { public static MonetaryAmount calculate(MonetaryAmount netIncome, double weightedAverageOfOutstandingShares) { return netIncome.divide(weightedAverageOfOutstandingShares); } private EarningsPerShare(); static MonetaryAmount calculate(MonetaryAmount netIncome, double weightedAverageOfOutstandingShares); }### Answer: @Test public void testCalculate() { assertEquals(Money.of(4, "GBP"), EarningsPerShare.calculate(NET_INCOME, WEIGHTED_AVERAGE_OF_OUTSTANDING_SHARES)); }
### Question: DividendsPerShare { public static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares) { return dividends.divide(numberOfShares); } private DividendsPerShare(); static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares); }### Answer: @Test public void testCalculate() { assertEquals(Money.of(25, "GBP"), DividendsPerShare.calculate(DIVIDENDS, NUMBER_OF_SHARES)); }
### Question: PriceToEarningsRatio { public static BigDecimal calculate(MonetaryAmount pricePerShare, MonetaryAmount earningsPerShare) { BigDecimal pricePerShareValue = BigDecimal.valueOf(pricePerShare.getNumber().doubleValueExact()); BigDecimal earningsPerShareValue = BigDecimal.valueOf(earningsPerShare.getNumber().doubleValueExact()); return pricePerShareValue.divide(earningsPerShareValue, MathContext.DECIMAL64); } private PriceToEarningsRatio(); static BigDecimal calculate(MonetaryAmount pricePerShare, MonetaryAmount earningsPerShare); }### Answer: @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.25), PriceToEarningsRatio.calculate(PRICE_PER_SHARE, EARNINGS_PER_SHARE)); }
### Question: StockPresentValue implements MonetaryOperator { public static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate) { return estimatedDividends.divide(requiredRateOfReturn.get().subtract(growthRate.get())); } private StockPresentValue(Rate requiredRateOfReturn, Rate growthRate); Rate getRequiredRateOfReturn(); Rate getGrowthRate(); static StockPresentValue of(Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn); @Override MonetaryAmount apply(MonetaryAmount estimatedDividends); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testCalculateForConstantGrowth() { assertEquals(Money.of(1700, "GBP"), StockPresentValue.calculateForConstantGrowth(ESTIMATED_DIVIDENDS, REQUIRED_RATE_OF_RETURN, GROWTH_RATE)); }
### Question: StockPresentValue implements MonetaryOperator { public static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, Rate.ZERO); } private StockPresentValue(Rate requiredRateOfReturn, Rate growthRate); Rate getRequiredRateOfReturn(); Rate getGrowthRate(); static StockPresentValue of(Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn); @Override MonetaryAmount apply(MonetaryAmount estimatedDividends); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testCalculateForZeroGrowth() { assertEquals(Money.of(680, "GBP"), StockPresentValue.calculateForZeroGrowth(ESTIMATED_DIVIDENDS, REQUIRED_RATE_OF_RETURN)); }
### Question: StockPresentValue implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount estimatedDividends) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, growthRate); } private StockPresentValue(Rate requiredRateOfReturn, Rate growthRate); Rate getRequiredRateOfReturn(); Rate getGrowthRate(); static StockPresentValue of(Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn); @Override MonetaryAmount apply(MonetaryAmount estimatedDividends); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testApply() { assertEquals(Money.of(1700, "GBP"), ESTIMATED_DIVIDENDS.with(StockPresentValue.of(REQUIRED_RATE_OF_RETURN, GROWTH_RATE))); }
### Question: TaxEquivalentYield { public static BigDecimal calculate(Rate taxFreeYield, Rate taxRate) { return taxFreeYield.get().divide(BigDecimal.ONE.subtract(taxRate.get()), MathContext.DECIMAL64); } private TaxEquivalentYield(); static BigDecimal calculate(Rate taxFreeYield, Rate taxRate); }### Answer: @Test public void testCalculate() { assertEquals(0.0597, TaxEquivalentYield.calculate(TAX_FREE_YIELD, TAX_RATE).doubleValue(), 0.0001); }
### Question: HoldingPeriodReturn { public static BigDecimal calculate(List<Rate> returns) { BigDecimal product = BigDecimal.ONE; for (Rate rateOfReturn : returns) { if (rateOfReturn == null) { throw new IllegalArgumentException("The list of returns cannot contain null elements"); } product = product.multiply(rateOfReturn.get().add(BigDecimal.ONE)); } return product.subtract(BigDecimal.ONE); } private HoldingPeriodReturn(); static BigDecimal calculate(List<Rate> returns); static BigDecimal calculateForSameReturn(Rate periodicRate, int numberOfPeriods); }### Answer: @Test public void testCalculate() { assertEquals(0.1319, HoldingPeriodReturn.calculate(RATES_OF_RETURN).doubleValue(), 0.00001); } @Test(expected = IllegalArgumentException.class) public void testCalculateWithNullReturnsThrowsException() { HoldingPeriodReturn.calculate(Arrays.asList(Rate.of(0.1), Rate.of(0.1), null, Rate.of(0.5))); }
### Question: HoldingPeriodReturn { public static BigDecimal calculateForSameReturn(Rate periodicRate, int numberOfPeriods) { if (periodicRate == null) { throw new IllegalArgumentException("The list of returns cannot contain null elements"); } if (numberOfPeriods <= 0) { throw new IllegalArgumentException("The number of periods should be positive"); } BigDecimal product = BigDecimal.ONE; final BigDecimal multiplicand = periodicRate.get().add(BigDecimal.ONE); for (int i = 0; i < numberOfPeriods; i++) { product = product.multiply(multiplicand); } return product.subtract(BigDecimal.ONE); } private HoldingPeriodReturn(); static BigDecimal calculate(List<Rate> returns); static BigDecimal calculateForSameReturn(Rate periodicRate, int numberOfPeriods); }### Answer: @Test public void testCalculateForSameReturn() { assertEquals(0.728, HoldingPeriodReturn.calculateForSameReturn(PERIODIC_RATE, NUMBER_OF_PERIODS).doubleValue(), 0.0001); } @Test(expected = IllegalArgumentException.class) public void testCalculateForSameReturnWithNullRateThrowsException() { HoldingPeriodReturn.calculateForSameReturn(null, NUMBER_OF_PERIODS); } @Test(expected = IllegalArgumentException.class) public void testCalculateForSameReturnWithNegativeNumberOfPeriodsThrowsException() { HoldingPeriodReturn.calculateForSameReturn(PERIODIC_RATE, -1); }
### Question: ZeroCouponBondYield { public static double calculate(MonetaryAmount faceAmount, MonetaryAmount presentAmount, int numberOfPeriods) { final BigDecimal faceValue = BigDecimal.valueOf(faceAmount.getNumber().doubleValueExact()); final BigDecimal presentValue = BigDecimal.valueOf(presentAmount.getNumber().doubleValueExact()); final double fraction = faceValue.divide(presentValue, MathContext.DECIMAL64).doubleValue(); return Math.pow(fraction, 1 / (double) numberOfPeriods) - 1; } private ZeroCouponBondYield(); static double calculate(MonetaryAmount faceAmount, MonetaryAmount presentAmount, int numberOfPeriods); }### Answer: @Test public void testCalculate() { assertEquals(0.2974, ZeroCouponBondYield.calculate(FACE_AMOUNT, PRESENT_AMOUNT, NUMBER_OF_PERIODS), 0.0001); }
### Question: BondEquivalentYield { public static BigDecimal calculate(MonetaryAmount faceValue, MonetaryAmount priceAmount, int numberOfDaysToMaturity) { BigDecimal face = BigDecimal.valueOf(faceValue.getNumber().doubleValueExact()); BigDecimal price = BigDecimal.valueOf(priceAmount.getNumber().doubleValueExact()); BigDecimal returnOnInvestment = (face.subtract(price)).divide(price, MathContext.DECIMAL64); BigDecimal maturity = BigDecimal.valueOf(365).divide(BigDecimal.valueOf(numberOfDaysToMaturity), MathContext.DECIMAL64); return returnOnInvestment.multiply(maturity); } private BondEquivalentYield(); static BigDecimal calculate(MonetaryAmount faceValue, MonetaryAmount priceAmount, int numberOfDaysToMaturity); }### Answer: @Test public void testCalculate() { assertEquals(0.40556, BondEquivalentYield.calculate(FACE_AMOUNT, PRICE_AMOUNT, NUMBER_OF_DAYS_TO_MATURITY).doubleValue(), 0.00001); }
### Question: TotalStockReturn { public static BigDecimal calculate(MonetaryAmount initialPrice, MonetaryAmount endingPrice, MonetaryAmount dividends) { BigDecimal initialPriceValue = BigDecimal.valueOf(initialPrice.getNumber().doubleValueExact()); BigDecimal endingPriceValue = BigDecimal.valueOf(endingPrice.getNumber().doubleValueExact()); BigDecimal dividendsValue = BigDecimal.valueOf(dividends.getNumber().doubleValueExact()); return (endingPriceValue.subtract(initialPriceValue).add(dividendsValue)).divide(initialPriceValue, MathContext.DECIMAL64); } private TotalStockReturn(); static BigDecimal calculate(MonetaryAmount initialPrice, MonetaryAmount endingPrice, MonetaryAmount dividends); }### Answer: @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.04), TotalStockReturn.calculate(INITIAL_PRICE, ENDING_PRICE, DIVIDENDS)); }
### Question: EquityMultiplier { public static BigDecimal calculate(MonetaryAmount totalAssets, MonetaryAmount equity) { BigDecimal totalAssetValue = BigDecimal.valueOf(totalAssets.getNumber().doubleValueExact()); BigDecimal equityValue = BigDecimal.valueOf(equity.getNumber().doubleValueExact()); return totalAssetValue.divide(equityValue, MathContext.DECIMAL64); } private EquityMultiplier(); static BigDecimal calculate(MonetaryAmount totalAssets, MonetaryAmount equity); }### Answer: @Test public void testCalculate() { assertEquals(0.5, EquityMultiplier.calculate(TOTAL_ASSETS, EQUITY).doubleValue()); }
### Question: CapitalAssetPricingModelFormula { public static Rate calculate(Rate riskFreeRate, BigDecimal beta, Rate marketReturn) { return calculate(riskFreeRate, beta, marketReturn, BigDecimal.ZERO); } private CapitalAssetPricingModelFormula(); static Rate calculate(Rate riskFreeRate, BigDecimal beta, Rate marketReturn); static Rate calculate(Rate riskFreeRate, BigDecimal beta, Rate marketReturn, BigDecimal epsilon); }### Answer: @Test public void testCalculateWithRegression() { assertEquals(Rate.of(0.301), CapitalAssetPricingModelFormula.calculate(RISKFREE_RATE, BETA, MARKET_RETURN, EPSILON)); } @Test public void testCalculate() { assertEquals(Rate.of(0.3), CapitalAssetPricingModelFormula.calculate(RISKFREE_RATE, BETA, MARKET_RETURN)); }
### Question: PreferredStock implements MonetaryOperator { public static MonetaryAmount calculate(MonetaryAmount dividend, Rate discountRate) { return dividend.divide(discountRate.get()); } private PreferredStock(Rate discountRate); Rate getDiscountRate(); static PreferredStock of(Rate discountRate); static MonetaryAmount calculate(MonetaryAmount dividend, Rate discountRate); @Override MonetaryAmount apply(MonetaryAmount dividend); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testCalculate() { assertEquals(Money.of(400, "GBP"), PreferredStock.calculate(DIVIDEND, DISCOUNT_RATE)); }
### Question: PreferredStock implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount dividend) { return calculate(dividend, discountRate); } private PreferredStock(Rate discountRate); Rate getDiscountRate(); static PreferredStock of(Rate discountRate); static MonetaryAmount calculate(MonetaryAmount dividend, Rate discountRate); @Override MonetaryAmount apply(MonetaryAmount dividend); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testApply() { assertEquals(Money.of(400, "GBP"), DIVIDEND.with(PreferredStock.of(DISCOUNT_RATE))); }
### Question: ZeroCouponBondValue implements MonetaryOperator { public static MonetaryAmount calculate(MonetaryAmount face, Rate rate, int numberOfYearsToMaturity) { return face.divide(BigDecimal.ONE.add(rate.get()).pow(numberOfYearsToMaturity)); } private ZeroCouponBondValue(Rate rate, int numberOfYearsToMaturity); Rate getRate(); int getNumberOfYearsToMaturity(); static ZeroCouponBondValue of(Rate rate, int numberOfYearsToMaturity); static MonetaryAmount calculate(MonetaryAmount face, Rate rate, int numberOfYearsToMaturity); @Override MonetaryAmount apply(MonetaryAmount face); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testCalculate() { assertEquals(Money.of(100, "GBP"), ZeroCouponBondValue.calculate(FACE, RATE, NUMBER_OF_YEARS_TO_MATURITY)); }
### Question: ZeroCouponBondValue implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount face) { return calculate(face, rate, numberOfYearsToMaturity); } private ZeroCouponBondValue(Rate rate, int numberOfYearsToMaturity); Rate getRate(); int getNumberOfYearsToMaturity(); static ZeroCouponBondValue of(Rate rate, int numberOfYearsToMaturity); static MonetaryAmount calculate(MonetaryAmount face, Rate rate, int numberOfYearsToMaturity); @Override MonetaryAmount apply(MonetaryAmount face); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testApply() { assertEquals(Money.of(100, "GBP"), FACE.with(ZeroCouponBondValue.of(RATE, NUMBER_OF_YEARS_TO_MATURITY))); }
### Question: YieldToMaturity { public static BigDecimal calculate(MonetaryAmount couponPaymentAmount, MonetaryAmount faceAmount, MonetaryAmount priceAmount, int numberOfYearsToMaturity) { final BigDecimal coupon = BigDecimal.valueOf(couponPaymentAmount.getNumber().doubleValueExact()); final BigDecimal face = BigDecimal.valueOf(faceAmount.getNumber().doubleValueExact()); final BigDecimal price = BigDecimal.valueOf(priceAmount.getNumber().doubleValueExact()); final BigDecimal averagedDifference = face.subtract(price).divide(BigDecimal.valueOf(numberOfYearsToMaturity), MathContext.DECIMAL64); final BigDecimal averagePrice = face.add(price).divide(BigDecimal.valueOf(2), MathContext.DECIMAL64); return coupon.add(averagedDifference).divide(averagePrice, MathContext.DECIMAL64); } private YieldToMaturity(); static BigDecimal calculate(MonetaryAmount couponPaymentAmount, MonetaryAmount faceAmount, MonetaryAmount priceAmount, int numberOfYearsToMaturity); }### Answer: @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.1125), YieldToMaturity.calculate(COUPON_PAYMENT_AMOUNT, FACE_AMOUNT, PRICE_AMOUNT, NUMBER_OF_YEARS_TO_MATURITY)); }