src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
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(); } | @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); } |
CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); Action getAction(); FieldProcessor perform(); FieldProcessor perform(boolean isSectionHidden); boolean doInclude(); boolean doExecute(); boolean hasErrors(); String getOnSuccess(); boolean doForward(); @Override String toString(); } | @Test public void testPerformException() { ApplicationRequest applicationRequest = initApplication(false); Mockito.when(config.getLinkpanel()).thenReturn(null); try { CallableAction action = new CallableAction(site, application, applicationRequest, actionRef); action.perform(); fail("ProcessingException must occur!"); } catch (ProcessingException e) { String message = e.getMessage(); assertTrue(message.matches("error performing action 'myAction' of event 'myEvent', ID: \\d{6,12}")); } }
@Test public void testPerformWithErrorFromDataProvider() throws ProcessingException { ApplicationRequest applicationRequest = initApplication(true); AtomicReference<Messages> envMessages = new AtomicReference<Messages>(new Messages()); AtomicReference<Messages> actionMessages = new AtomicReference<Messages>(new Messages()); mockMessages(envMessages, actionMessages, false); Mockito.doAnswer(i -> { FieldProcessor fp = i.getArgumentAt(5, FieldProcessor.class); DataContainer dataContainer = new DataContainer(fp); dataContainer.setItem(new Object()); fp.addErrorMessage("Error!"); return dataContainer; }).when(dataProvider).getData(Mockito.eq(site), Mockito.eq(application), Mockito.eq(environment), Mockito.any(), Mockito.eq(applicationRequest), Mockito.any()); CallableAction action = new CallableAction(site, application, applicationRequest, actionRef); action.perform(); Assert.assertNull(envMessages.get()); Assert.assertNotNull(actionMessages.get()); Message message = actionMessages.get().getMessageList().get(0); Assert.assertEquals("Error!", message.getContent()); Assert.assertEquals(MessageType.ERROR, message.getClazz()); }
@Test public void testPerformWithErrorFromAction() throws ProcessingException { ApplicationRequest applicationRequest = initApplication(true); AtomicReference<Messages> envMessages = new AtomicReference<Messages>(new Messages()); AtomicReference<Messages> actionMessages = new AtomicReference<Messages>(new Messages()); mockMessages(envMessages, actionMessages, true); Mockito.doAnswer(i -> { FieldProcessor fp = i.getArgumentAt(5, FieldProcessor.class); DataContainer dataContainer = new DataContainer(fp); dataContainer.setItem(new Object()); return dataContainer; }).when(dataProvider).getData(Mockito.eq(site), Mockito.eq(application), Mockito.eq(environment), Mockito.any(), Mockito.eq(applicationRequest), Mockito.any()); Mockito.doAnswer(i -> { FieldProcessor fp = i.getArgumentAt(6, FieldProcessor.class); fp.addErrorMessage("BOOOOM!"); return null; }).when(actionProvider).perform(Mockito.eq(site), Mockito.eq(application), Mockito.eq(environment), Mockito.any(), Mockito.eq(applicationRequest), Mockito.any(), Mockito.any()); CallableAction action = new CallableAction(site, application, applicationRequest, actionRef); action.perform(); Assert.assertNull(envMessages.get()); Assert.assertNotNull(actionMessages.get()); List<Message> messageList = actionMessages.get().getMessageList(); Assert.assertEquals("BOOOOM!", messageList.get(0).getContent()); Assert.assertEquals(MessageType.ERROR, messageList.get(0).getClazz()); }
@Test public void testPerform() throws ProcessingException { ApplicationRequest applicationRequest = initApplication(true); AtomicReference<Messages> envMessages = new AtomicReference<Messages>(new Messages()); AtomicReference<Messages> actionMessages = new AtomicReference<Messages>(new Messages()); mockMessages(envMessages, actionMessages, false); Mockito.doAnswer(i -> { FieldProcessor fp = i.getArgumentAt(5, FieldProcessor.class); DataContainer dataContainer = new DataContainer(fp); dataContainer.setItem(new Object()); fp.addOkMessage("Done!"); return dataContainer; }).when(dataProvider).getData(Mockito.eq(site), Mockito.eq(application), Mockito.eq(environment), Mockito.any(), Mockito.eq(applicationRequest), Mockito.any()); Mockito.doAnswer(i -> { FieldProcessor fp = i.getArgumentAt(6, FieldProcessor.class); fp.addOkMessage("ACTION!"); return null; }).when(actionProvider).perform(Mockito.eq(site), Mockito.eq(application), Mockito.eq(environment), Mockito.any(), Mockito.eq(applicationRequest), Mockito.any(), Mockito.any()); CallableAction action = new CallableAction(site, application, applicationRequest, actionRef); action.perform(); Assert.assertNotNull(envMessages.get()); Assert.assertNull(actionMessages.get()); List<Message> messageList = envMessages.get().getMessageList(); Assert.assertEquals("Done!", messageList.get(0).getContent()); Assert.assertEquals(MessageType.OK, messageList.get(0).getClazz()); Assert.assertEquals("ACTION!", messageList.get(1).getContent()); Assert.assertEquals(MessageType.OK, messageList.get(1).getClazz()); } |
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); } | @Test public void testCustomString() { Assert.assertEquals("custom", propertyHolder.getString("customString")); Assert.assertEquals("string", propertyHolder.getString("emptyCustomString")); } |
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); } | @Test public void testBoolean() { Assert.assertEquals(true, propertyHolder.getBoolean("boolean")); Assert.assertEquals(false, propertyHolder.getBoolean("bla", false)); } |
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); } | @Test public void testFloat() { Assert.assertEquals(Float.valueOf(4.5f), propertyHolder.getFloat("float")); Assert.assertEquals(Float.valueOf(1.2f), propertyHolder.getFloat("bla", 1.2f)); } |
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); } | @Test public void testDouble() { Assert.assertEquals(Double.valueOf(7.9d), propertyHolder.getDouble("double")); Assert.assertEquals(Double.valueOf(1.2d), propertyHolder.getDouble("bla", 1.2d)); } |
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); } | @Test public void testList() { Assert.assertEquals(Arrays.asList("1", "2"), propertyHolder.getList("list", ",")); Assert.assertEquals(Arrays.asList("3", "4"), propertyHolder.getList("bla", "3,4", ",")); } |
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); } | @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")); } |
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(); } | @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); } |
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); } | @Test public void testPlainProperties() { Properties plainProperties = propertyHolder.getPlainProperties(); Assert.assertEquals(plainProperties, propertyHolder.getPlainProperties()); } |
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; } | @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); } |
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; } | @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()); } |
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; } | @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")); } |
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; } | @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"))); } |
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; } | @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)); } |
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; } | @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); } |
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; } | @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); } |
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; } | @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()); } |
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; } | @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()); } |
ElementHelper { Map<String, String> initializeParameters(String reference, ApplicationRequest applicationRequest, ParameterSupport parameterSupport, Params referenceParams, Params executionParams) throws ProcessingException { Map<String, String> executionParameters = new HashMap<>(); Map<String, String> referenceParameters = new HashMap<>(); if (null != referenceParams) { for (Param p : referenceParams.getParam()) { String newValue = parameterSupport.replaceParameters(p.getValue()); if (StringUtils.isEmpty(newValue) && StringUtils.isNotEmpty(p.getDefault())) { newValue = p.getDefault(); } p.setValue(newValue); if (null != newValue) { referenceParameters.put(p.getName(), newValue); } } if (null != executionParams) { for (Param p : executionParams.getParam()) { String value = p.getValue(); if (StringUtils.isEmpty(value)) { value = referenceParameters.get(p.getName()); if (StringUtils.isEmpty(value) && StringUtils.isNotEmpty(p.getDefault())) { value = p.getDefault(); } } p.setValue(value); if (null != value) { executionParameters.put(p.getName(), value); } } } } if (applicationRequest.isPost()) { Map<String, List<String>> parametersList = applicationRequest.getParametersList(); for (String param : parametersList.keySet()) { String postParam = StringUtils.join(parametersList.get(param), "|"); String existingValue = executionParameters.get(param); if (null == existingValue) { executionParameters.put(param, postParam); } else { if (!existingValue.equals(postParam)) { String message = String.format( "the parameter '%s' is ambiguous, since it's a execution parameter for '%s' (value: '%s') " + "and also POST-parameter (value: '%s''). Avoid such overlapping parameters!", param, reference, existingValue, postParam); LOGGER.warn(message); } } } } this.expressionEvaluator = new ExpressionEvaluator(executionParameters); expressionEvaluator.setVariable(ApplicationRequest.I18N_VAR, new I18n(applicationRequest)); return executionParameters; } 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; } | @Test public void testDefaultParameters() throws ProcessingException { Params referenceParams = new Params(); addParam(referenceParams, "p1", null, null); addParam(referenceParams, "p2", null, null); addParam(referenceParams, "p3", null, "bar"); addParam(referenceParams, "p4", null, "bar"); addParam(referenceParams, "p5", "foo", null); addParam(referenceParams, "p6", "foo", null); addParam(referenceParams, "p7", "foo", "bar"); addParam(referenceParams, "p8", "foo", "bar"); addParam(referenceParams, "p9", "foo", "bar"); Params executionParams = new Params(); addParam(executionParams, "p1", null, null); addParam(executionParams, "p2", "jin", null); addParam(executionParams, "p3", null, null); addParam(executionParams, "p4", "jin", null); addParam(executionParams, "p5", null, null); addParam(executionParams, "p6", "jin", null); addParam(executionParams, "p7", null, null); addParam(executionParams, "p8", "jin", null); addParam(executionParams, "p9", null, "fizz"); DollarParameterSupport parameterSupport = new DollarParameterSupport(new HashMap<>()); Map<String, String> actual = elementHelper.initializeParameters(DATASOURCE_TEST, applicationRequest, parameterSupport, referenceParams, executionParams); Assert.assertNull(actual.get("p1")); Assert.assertEquals("jin", actual.get("p2")); Assert.assertEquals("bar", actual.get("p3")); Assert.assertEquals("bar", actual.get("p4")); Assert.assertEquals("foo", actual.get("p5")); Assert.assertEquals("foo", actual.get("p6")); Assert.assertEquals("bar", actual.get("p7")); Assert.assertEquals("bar", actual.get("p8")); Assert.assertEquals("fizz", actual.get("p9")); }
@Test @Ignore("APPNG-442") public void testOverlappingParams() { Map<String, List<String>> postParameters = new HashMap<>(); postParameters.put("p5", Arrays.asList("a")); Mockito.when(applicationRequest.getParametersList()).thenReturn(postParameters); Mockito.when(applicationRequest.isPost()).thenReturn(true); Params referenceParams = new Params(); addParam(referenceParams, "p5", null, "foo"); Params executionParams = new Params(); addParam(executionParams, "p5", null, "b"); DollarParameterSupport parameterSupport = new DollarParameterSupport(new HashMap<>()); try { elementHelper.initializeParameters(DATASOURCE_TEST, applicationRequest, parameterSupport, referenceParams, executionParams); Assert.fail("should throw ProcessingException"); } catch (ProcessingException e) { Assert.assertEquals( "the parameter 'p5' is ambiguous, since it's a execution parameter for datasource 'test' (value: 'b') and also" + " POST-parameter (value: 'a'). Avoid such overlapping parameters!", e.getMessage()); } }
@Test public void testInitializeParameters() throws ProcessingException { Map<String, List<String>> postParameters = new HashMap<>(); postParameters.put("postParam1", Arrays.asList("a")); postParameters.put("postParam2", Arrays.asList("b")); postParameters.put("postParam3", Arrays.asList("x", "y", "z")); Mockito.when(applicationRequest.getParametersList()).thenReturn(postParameters); Mockito.when(applicationRequest.isPost()).thenReturn(true); Params referenceParams = new Params(); addParam(referenceParams, "p0", null, null); addParam(referenceParams, "p1", null, "${req_1}"); addParam(referenceParams, "p2", "2", "${req_2}"); addParam(referenceParams, "p3", "3", "7"); addParam(referenceParams, "p4", "6", null); Params executionParams = new Params(); addParam(executionParams, "p0", "7", null); addParam(executionParams, "p1", null, null); addParam(executionParams, "p2", "4", null); addParam(executionParams, "p3", "9", "18"); addParam(executionParams, "p4", null, null); Map<String, String> parameters = new HashMap<>(); parameters.put("req_1", "42"); DollarParameterSupport parameterSupport = new DollarParameterSupport(parameters); Map<String, String> result = elementHelper.initializeParameters(DATASOURCE_TEST, applicationRequest, parameterSupport, referenceParams, executionParams); Assert.assertEquals("7", result.get("p0")); Assert.assertEquals("42", result.get("p1")); Assert.assertEquals("2", result.get("p2")); Assert.assertEquals("18", result.get("p3")); Assert.assertEquals("6", result.get("p4")); Assert.assertEquals("a", result.get("postParam1")); Assert.assertEquals("b", result.get("postParam2")); Assert.assertEquals("x|y|z", result.get("postParam3")); } |
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; } | @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); } |
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; } | @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()); } |
LabelSupport { public final void setLabel(Label label, ExpressionEvaluator expressionEvaluator, ParameterSupport fieldParameters) { if (null != label) { String key = label.getId(); String value = label.getValue(); if (StringUtils.isNotBlank(value) && value.startsWith(EXPR_PREFIX)) { String message = value; if (null != fieldParameters) { message = fieldParameters.replaceParameters(message); } message = expressionEvaluator.evaluate(message, String.class); label.setValue(message); } else { if (StringUtils.isBlank(key) && StringUtils.isNotBlank(value) && !StringUtils.startsWith(value, LABEL_PREFIX)) { key = value; } setLabelFromKey(label, expressionEvaluator, fieldParameters, key); } } } 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); } | @Test public void testLabelParams() { LabelSupport labelSupport = getLabelSupport(); Label label = new Label(); label.setId(KEY); label.setParams("foo,'bar',${id}"); labelSupport.setLabel(label, expressionEvaluator, null); Assert.assertEquals(RESULT, label.getValue()); }
@Test public void testLabelParamsCurrent() { LabelSupport labelSupport = getLabelSupport(); Label label = new Label(); label.setId(KEY); label.setParams("foo,'bar',${current.toString()}"); labelSupport.setLabel(label, expressionEvaluator, null); Assert.assertEquals(RESULT.replace("5", "${current.toString()}"), label.getValue()); expressionEvaluator.setVariable(AdapterBase.CURRENT, "5"); labelSupport.setLabel(label, expressionEvaluator, null); Assert.assertEquals(RESULT, label.getValue()); }
@Test public void testFieldParams() { LabelSupport labelSupport = getLabelSupport(); Map<String, String> params = new HashMap<>(); params.put("name", "foo"); params.put("name.with.dots", "foo"); Label label = new Label(); label.setId(KEY); label.setParams("#{name},'bar',${id}"); HashParameterSupport fieldParameters = new HashParameterSupport(params); labelSupport.setLabel(label, expressionEvaluator, fieldParameters); Assert.assertEquals(RESULT, label.getValue()); label.setParams("#{name.with.dots},'bar',${id}"); labelSupport.setLabel(label, expressionEvaluator, fieldParameters); Assert.assertEquals(RESULT.replace("foo", "#{name.with.dots}"), label.getValue()); fieldParameters.allowDotInName(); labelSupport.setLabel(label, expressionEvaluator, fieldParameters); Assert.assertEquals(RESULT, label.getValue()); }
@Test public void testI18n() { LabelSupport labelSupport = getLabelSupport(); Map<String, String> params = new HashMap<>(); params.put("name", "foo"); Label label = new Label(); label.setId(KEY); label.setValue("${i18n.message('key','#{name}','bar',id)}"); HashParameterSupport fieldParameters = new HashParameterSupport(params); labelSupport.setLabel(label, expressionEvaluator, fieldParameters); Assert.assertEquals(RESULT, label.getValue()); label.setValue("${i18n.formatDate(date,i18n.message('dateFormat'))}"); labelSupport.setLabel(label, expressionEvaluator, fieldParameters); Assert.assertEquals("2013-03-08", label.getValue()); label.setValue("${i18n.formatNumber(number,'0,000,000.00')}"); labelSupport.setLabel(label, expressionEvaluator, fieldParameters); Assert.assertEquals("42.000.000,42", label.getValue()); label.setValue("${i18n.format('%1$td.%1$tm.%1$tY %2$,.2f %3$s', date, number, 'foo')}"); labelSupport.setLabel(label, expressionEvaluator, fieldParameters); Assert.assertEquals("08.03.2013 42.000.000,42 foo", label.getValue()); }
@Test public void testLabelNoKey() { LabelSupport labelSupport = getLabelSupport(); Label label = new Label(); label.setValue("key2"); labelSupport.setLabel(label, expressionEvaluator, null); Assert.assertEquals("some value", label.getValue()); }
@Test public void testLabelValueIsSet() { LabelSupport labelSupport = getLabelSupport(); Label label = new Label(); label.setValue("some value"); label.setId("key2"); labelSupport.setLabel(label, expressionEvaluator, null); Assert.assertEquals("some value", label.getValue()); } |
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); } | @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()); } |
ApplicationRequest implements Request { public ApplicationPath applicationPath() { Path path = getEnvironment().getAttribute(Scope.REQUEST, EnvironmentKeys.PATH_INFO); List<String> urlParameters = path.getApplicationUrlParameters(); return new ApplicationPath('/' + StringUtils.join(urlParameters, '/'), getParameters()); } ApplicationRequest(); ApplicationRequest(org.appng.forms.Request request, PermissionProcessor permissionProcessor,
RequestSupport requestSupport); PermissionProcessor getPermissionProcessor(); void setPermissionProcessor(PermissionProcessor permissionProcessor); LabelSupport getLabelSupport(); void setLabelSupport(LabelSupport labelSupport); org.appng.forms.Request getWrappedRequest(); void setWrappedRequest(org.appng.forms.Request wrappedRequest); Environment getEnvironment(); RequestSupport getRequestSupport(); void setRequestSupport(RequestSupport requestSupport); String getRedirectTarget(); void setRedirectTarget(String redirectTarget); boolean canConvert(Class<?> sourceType, Class<?> targetType); void handleException(FieldProcessor fp, Exception e); void addErrorMessage(FieldProcessor fp, MessageParam localizable); void addErrorMessage(FieldProcessor fp, MessageParam localizable, String fieldBinding); T convert(Object source, Class<T> targetType); void setPropertyValues(T source, T target, MetaData metaData); void setPropertyValue(T source, T target, String property); boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType); Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType); Object getBindObject(FieldProcessor fp, RequestContainer container, ClassLoader classLoader); void fillBindObject(Object instance, FieldProcessor fp, RequestContainer container, ClassLoader classLoader); String getMessage(String key, Object... args); MessageSource getMessageSource(); String getHost(); Map<String, List<String>> getParametersList(); Map<String, String> getParameters(); String getParameter(String name); HttpServletRequest getHttpServletRequest(); Set<String> getParameterNames(); String getEncoding(); boolean hasParameter(String name); void setEncoding(String encoding); List<String> getParameterList(String name); boolean isMultiPart(); boolean isPost(); Map<String, List<FormUpload>> getFormUploads(); boolean isGet(); boolean isValid(); void setTempDir(File tempDir); List<FormUpload> getFormUploads(String name); void setMaxSize(long maxSize); void setMaxSize(long maxSize, boolean strict); void setAcceptedTypes(String uploadName, String... types); List<String> getAcceptedTypes(String uploadName); void addParameters(Map<String, String> singleParameters); void addParameter(String key, String value); Subject getSubject(); Locale getLocale(); ExpressionEvaluator getExpressionEvaluator(); ParameterSupport getParameterSupportDollar(); @Override boolean isRedirect(); void setLabels(Config config); final void setLabels(Config config, ParameterSupport fieldParameters); void setLabel(Label label); void setLabels(Labels labels); FieldConverter getFieldConverter(); ApplicationConfigProvider getApplicationConfig(); void setApplicationConfig(ApplicationConfigProvider applicationConfigProvider); ValidationProvider getValidationProvider(); void setValidationProvider(ValidationProvider validationProvider); List<String> getUrlParameters(); void setUrlParameters(List<String> urlParameters); void validateBean(Object bean, FieldProcessor fp, Class<?>... groups); void validateBean(Object bean, FieldProcessor fp, String[] excludeBindings, Class<?>... groups); void validateField(Object bean, FieldProcessor fp, String fieldBinding, Class<?>... groups); void addValidationMetaData(MetaData metaData, ClassLoader classLoader, Class<?>... groups); HttpHeaders headers(); ApplicationPath applicationPath(); static final String I18N_VAR; } | @Test public void testApplicationPath() { Request request = Mockito.mock(Request.class); HashMap<String, String> params = new HashMap<>(); params.put("entity", "item"); params.put("action", "update"); params.put("id", "2"); Mockito.when(request.getParameters()).thenReturn(params); RequestSupport rs = Mockito.mock(RequestSupport.class); Environment env = Mockito.mock(Environment.class); Mockito.when(rs.getEnvironment()).thenReturn(env); Path path = Mockito.mock(Path.class); Mockito.when(path.getApplicationUrlParameters()).thenReturn(Arrays.asList("item", "update", "2")); Mockito.when(env.getAttribute(Scope.REQUEST, EnvironmentKeys.PATH_INFO)).thenReturn(path); ApplicationRequest ar = new ApplicationRequest(request, Mockito.mock(PermissionProcessor.class), rs); ApplicationPath applicationPath = ar.applicationPath(); Map<String, Object> conditionsParams = new HashMap<>(params); conditionsParams.put(ApplicationPath.PATH_VAR, applicationPath); ExpressionEvaluator ee = new ExpressionEvaluator(conditionsParams); params.keySet().forEach(k -> Assert.assertTrue(applicationPath.hasParam(k))); Assert.assertFalse(applicationPath.hasParam("foo")); Assert.assertTrue(ee.evaluate("${ PATH.isEqual('/item', '/update/', id) }")); Assert.assertTrue(ee.evaluate("${ PATH.isEqual('/item/update/2') }")); Assert.assertTrue(ee.evaluate("${ PATH.starts('/item', '/update/', id) }")); Assert.assertTrue(ee.evaluate("${ PATH.ends('/item/update/', id) }")); Assert.assertTrue(ee.evaluate("${ PATH.contains('/item', '/update/', id) }")); Assert.assertTrue(ee.evaluate("${ PATH.matches('/item/update/','\\\\d+') }")); } |
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); } | @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()); } |
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); } | @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()); } |
AttributeWrapper implements Serializable { public String getSiteName() { return siteName; } AttributeWrapper(); AttributeWrapper(String siteName, Object value); Object getValue(); String getSiteName(); @Override String toString(); } | @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()); } |
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); } | @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()); } |
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); } | @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); } |
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); } | @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)); } } |
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); } | @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()); } |
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); } | @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); } |
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(); } | @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")); } |
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(); } | @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)); } |
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(); } | @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)); } |
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(); } | @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()); } |
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(); } | @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)); } |
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(); } | @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)); } |
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); } | @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")); } |
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(); } | @Test public void getPeriods() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.01),Rate.of(0.03),3654 ); assertEquals(val.getPeriods(), 3654); } |
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(); } | @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); } |
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(); } | @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)); } |
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(); } | @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()); } |
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(); } | @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)); } |
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(); } | @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); } |
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(); } | @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)); } |
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(); } | @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()); } |
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); } | @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))); } |
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); } | @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.5), PriceToBookValue.calculate(MARKET_PRICE_PER_SHARE, BOOK_VALUE_PER_SHARE)); } |
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); } | @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.8), DividendPayoutRatio.calculate(DIVIDENDS, NET_INCOME)); } |
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); } | @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))); } |
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); } | @Test public void testCalculate() { assertEquals(Money.of(9, "GBP"), NetAssetValue.calculate(ASSETS, FUND_LIABILITIES, OUTSTANDING_SHARES)); } |
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); } | @Test public void testCalculate() { assertEquals(0.81301, CapitalGainsYield.calculate(INITIAL_STOCK_PRICE, STOCK_PRICE_AFTER_FIRST_PERIOD).doubleValue(), 0.00001); } |
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); } | @Test public void testCalculate() { assertEquals(0.1111, CurrentYield.calculate(ANNUAL_COUPONS, CURRENT_BOND_PRICE).doubleValue(), 0.0001); } |
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); } | @Test public void testCalculate() { assertEquals(Money.of(11, "GBP"), DilutedEarningsPerShare.calculate(NET_INCOME, AVERAGE_SHARES, OTHER_CONVERTIBLE_INSTRUMENTS)); } |
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); } | @Test public void testCalculate() { assertEquals(0.04, DividendYield.calculate(DIVIDENDS, INITIAL_PRICE).doubleValue()); } |
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); } | @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.2), PriceToSalesRatio.calculate(SHARE_PRICE, SALES_PER_SHARE)); } |
BookValuePerShare { public static MonetaryAmount calculate(MonetaryAmount equity, int numberOfCommonShares) { return equity.divide(numberOfCommonShares); } private BookValuePerShare(); static MonetaryAmount calculate(MonetaryAmount equity, int numberOfCommonShares); } | @Test public void testCalculate() { assertEquals(Money.of(10, "GBP"), BookValuePerShare.calculate(EQUITY, NUMBER_OF_COMMON_SHARES)); } |
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); } | @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.04), RiskPremium.calculate(ASSET_RETURN, RISK_FREE_RETURN)); } |
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); } | @Test public void testCalculateWithCAPM() { assertEquals(BigDecimal.valueOf(0.025), RiskPremium.calculateWithCAPM(BETA, MARKET_RETURN, RISK_FREE_RETURN)); } |
BidAskSpread { public static MonetaryAmount calculate(MonetaryAmount askPrice, MonetaryAmount bidPrice) { return askPrice.subtract(bidPrice); } private BidAskSpread(); static MonetaryAmount calculate(MonetaryAmount askPrice, MonetaryAmount bidPrice); } | @Test public void testCalculate() { assertEquals(Money.of(0.05, "GBP"), BidAskSpread.calculate(ASK_PRICE, BID_PRICE)); } |
EarningsPerShare { public static MonetaryAmount calculate(MonetaryAmount netIncome, double weightedAverageOfOutstandingShares) { return netIncome.divide(weightedAverageOfOutstandingShares); } private EarningsPerShare(); static MonetaryAmount calculate(MonetaryAmount netIncome, double weightedAverageOfOutstandingShares); } | @Test public void testCalculate() { assertEquals(Money.of(4, "GBP"), EarningsPerShare.calculate(NET_INCOME, WEIGHTED_AVERAGE_OF_OUTSTANDING_SHARES)); } |
DividendsPerShare { public static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares) { return dividends.divide(numberOfShares); } private DividendsPerShare(); static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares); } | @Test public void testCalculate() { assertEquals(Money.of(25, "GBP"), DividendsPerShare.calculate(DIVIDENDS, NUMBER_OF_SHARES)); } |
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); } | @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.25), PriceToEarningsRatio.calculate(PRICE_PER_SHARE, EARNINGS_PER_SHARE)); } |
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(); } | @Test public void testCalculateForConstantGrowth() { assertEquals(Money.of(1700, "GBP"), StockPresentValue.calculateForConstantGrowth(ESTIMATED_DIVIDENDS, REQUIRED_RATE_OF_RETURN, GROWTH_RATE)); } |
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(); } | @Test public void testCalculateForZeroGrowth() { assertEquals(Money.of(680, "GBP"), StockPresentValue.calculateForZeroGrowth(ESTIMATED_DIVIDENDS, REQUIRED_RATE_OF_RETURN)); } |
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(); } | @Test public void testApply() { assertEquals(Money.of(1700, "GBP"), ESTIMATED_DIVIDENDS.with(StockPresentValue.of(REQUIRED_RATE_OF_RETURN, GROWTH_RATE))); } |
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); } | @Test public void testCalculate() { assertEquals(0.0597, TaxEquivalentYield.calculate(TAX_FREE_YIELD, TAX_RATE).doubleValue(), 0.0001); } |
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); } | @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))); } |
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); } | @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); } |
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); } | @Test public void testCalculate() { assertEquals(0.2974, ZeroCouponBondYield.calculate(FACE_AMOUNT, PRESENT_AMOUNT, NUMBER_OF_PERIODS), 0.0001); } |
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); } | @Test public void testCalculate() { assertEquals(0.40556, BondEquivalentYield.calculate(FACE_AMOUNT, PRICE_AMOUNT, NUMBER_OF_DAYS_TO_MATURITY).doubleValue(), 0.00001); } |
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); } | @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.04), TotalStockReturn.calculate(INITIAL_PRICE, ENDING_PRICE, DIVIDENDS)); } |
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); } | @Test public void testCalculate() { assertEquals(0.5, EquityMultiplier.calculate(TOTAL_ASSETS, EQUITY).doubleValue()); } |
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); } | @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)); } |
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(); } | @Test public void testCalculate() { assertEquals(Money.of(400, "GBP"), PreferredStock.calculate(DIVIDEND, DISCOUNT_RATE)); } |
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(); } | @Test public void testApply() { assertEquals(Money.of(400, "GBP"), DIVIDEND.with(PreferredStock.of(DISCOUNT_RATE))); } |
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(); } | @Test public void testCalculate() { assertEquals(Money.of(100, "GBP"), ZeroCouponBondValue.calculate(FACE, RATE, NUMBER_OF_YEARS_TO_MATURITY)); } |
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(); } | @Test public void testApply() { assertEquals(Money.of(100, "GBP"), FACE.with(ZeroCouponBondValue.of(RATE, NUMBER_OF_YEARS_TO_MATURITY))); } |
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); } | @Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.1125), YieldToMaturity.calculate(COUPON_PAYMENT_AMOUNT, FACE_AMOUNT, PRICE_AMOUNT, NUMBER_OF_YEARS_TO_MATURITY)); } |
EstimatedEarnings { public static MonetaryAmount calculate(MonetaryAmount forecastedSales, MonetaryAmount forecastedExpenses) { return forecastedSales.subtract(forecastedExpenses); } private EstimatedEarnings(); static MonetaryAmount calculate(MonetaryAmount forecastedSales, MonetaryAmount forecastedExpenses); static MonetaryAmount calculate(MonetaryAmount projectedSales, BigDecimal projectedNetProfitMargin); } | @Test public void testCalculate() { assertEquals(Money.of(200, "GBP"), EstimatedEarnings.calculate(FORECASTED_SALES, FORECASTED_EXPENSES)); }
@Test public void testCalculateWithProfitMarginFormula() { assertEquals(Money.of(2, "GBP"), EstimatedEarnings.calculate(PROJECTED_SALES, PROJECTED_NET_PROFIT_MARGIN)); } |
ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, 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(); } | @Test public void apply() throws Exception { ContinuousCompoundInterest ci = ContinuousCompoundInterest.of( RateAndPeriods.of(0.1,2) ); assertEquals(ci.apply(Money.of(1000,"CHF")) .getNumber().doubleValue(), Money.of(221.401536766165,"CHF").getNumber().doubleValue(), 0.00d); } |
PresentValueOfAnnuityDue extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuityDue of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuityDue(rateAndPeriods); } private PresentValueOfAnnuityDue(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuityDue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } | @Test public void getRate() throws Exception { PresentValueOfAnnuityDue val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(0.03,1) ); assertEquals(val.getRate(), Rate.of(0.03)); }
@Test public void getPeriods() throws Exception { PresentValueOfAnnuityDue val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(0.03,3654) ); assertEquals(val.getPeriods(), 3654); }
@Test public void of_Period1() throws Exception { PresentValueOfAnnuityDue val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 1) ); assertNotNull(val); }
@Test public void of_Period0() throws Exception { PresentValueOfAnnuityDue val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(0.08,0) ); assertNotNull(val); }
@Test public void calculate_Periods0() throws Exception { Money m = Money.of(100, "CHF"); PresentValueOfAnnuityDue val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 0) ); assertEquals(Money.of(0,"CHF"), m.with(val)); val = PresentValueOfAnnuityDue.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(100, "CHF"); PresentValueOfAnnuityDue val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 1) ); assertEquals(Money.of(100,"CHF"), m.with(val)); val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(-0.05, 1) ); assertEquals(Money.of(100,"CHF"), m.with(val)); }
@Test public void calculate_PeriodsN() throws Exception { Money m = Money.of(100, "CHF"); PresentValueOfAnnuityDue val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 10) ); assertEquals(Money.of(810.7821675644053,"CHF").getNumber().numberValue(BigDecimal.class) .doubleValue(), m.with(val).getNumber().numberValue(BigDecimal.class) .doubleValue(), 0.00000000000001d); val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(-0.05, 10) ); assertEquals(Money.of(1273.3468832186768,"CHF").getNumber().numberValue(BigDecimal.class).doubleValue(), m.with(val).getNumber().numberValue(BigDecimal.class).doubleValue(), 0.000000000000001d); } |
PresentValueOfAnnuityDue extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private PresentValueOfAnnuityDue(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuityDue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } | @Test public void apply() throws Exception { PresentValueOfAnnuityDue val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(0.08, 10) ); Money m = Money.of(100, "CHF"); assertEquals(val.apply(m), m.with(val)); } |
PresentValueOfAnnuityDue extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValueOfAnnuityDue{" + "\n " + rateAndPeriods + '}'; } private PresentValueOfAnnuityDue(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuityDue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } | @Test public void toStringTest() throws Exception { PresentValueOfAnnuityDue val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 10) ); assertEquals("PresentValueOfAnnuityDue{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=10}}", val.toString()); } |
CompoundInterest extends AbstractRateAndPeriodBasedOperator { public static CompoundInterest of(RateAndPeriods rateAndPeriods, int timesCompounded) { return new CompoundInterest(rateAndPeriods, timesCompounded); } private CompoundInterest(RateAndPeriods rateAndPeriods, int timesCompounded); int getTimesCompounded(); static CompoundInterest of(RateAndPeriods rateAndPeriods, int timesCompounded); static CompoundInterest of(RateAndPeriods rateAndperiods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods, int timesCompounded); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } | @Test public void of_notNull() throws Exception { CompoundInterest ci = CompoundInterest.of( RateAndPeriods.of(0.05,1) ); assertNotNull(ci); }
@Test public void of_correctRate() throws Exception { CompoundInterest ci = CompoundInterest.of( RateAndPeriods.of(0.0234,1) ); assertNotNull(ci.getRate()); assertEquals(ci.getRate(), Rate.of(0.0234)); ci = CompoundInterest.of( RateAndPeriods.of(0.05,1) ); assertNotNull(ci.getRate()); assertEquals(ci.getRate(), Rate.of(0.05)); }
@Test public void of_correctPeriods() throws Exception { CompoundInterest ci = CompoundInterest.of( RateAndPeriods.of(0.05,1) ); assertEquals(ci.getPeriods(), 1); ci = CompoundInterest.of( RateAndPeriods.of(0.05,234) ); assertEquals(ci.getPeriods(), 234); }
@Test public void calculate_zeroPeriods() throws Exception { CompoundInterest ci = CompoundInterest.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 { CompoundInterest ci = CompoundInterest.of( RateAndPeriods.of(0.05,1) ); assertEquals(Money.of(1,"CHF").with(ci),Money.of(0.05,"CHF")); assertEquals(Money.of(0,"CHF").with(ci),Money.of(0,"CHF")); assertEquals(Money.of(-1,"CHF").with(ci),Money.of(-0.05,"CHF")); }
@Test public void calculate_twoPeriods() throws Exception { CompoundInterest ci = CompoundInterest.of( RateAndPeriods.of(0.05,2) ); assertEquals(Money.of(1,"CHF").with(ci),Money.of(0.1025,"CHF")); assertEquals(Money.of(0,"CHF").with(ci),Money.of(0,"CHF")); assertEquals(Money.of(-1,"CHF").with(ci),Money.of(-0.1025,"CHF")); } |
CompoundInterest extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private CompoundInterest(RateAndPeriods rateAndPeriods, int timesCompounded); int getTimesCompounded(); static CompoundInterest of(RateAndPeriods rateAndPeriods, int timesCompounded); static CompoundInterest of(RateAndPeriods rateAndperiods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods, int timesCompounded); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } | @Test public void apply() throws Exception { CompoundInterest ci = CompoundInterest.of( RateAndPeriods.of(0.05,2) ); assertEquals(ci.apply(Money.of(1,"CHF")),Money.of(0.1025,"CHF")); } |
PresentValueOfPerpetuity implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rate); } private PresentValueOfPerpetuity(Rate rate); Rate getRate(); static PresentValueOfPerpetuity of(Rate rate); static MonetaryAmount calculate(MonetaryAmount amount, Rate rate); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } | @Test public void testApply(){ PresentValueOfPerpetuity op = PresentValueOfPerpetuity.of(Rate.of(0.05)); assertEquals(Money.of(2000, "CHF"), Money.of(100, "CHF").with(op)); assertEquals(Money.of(2000, "CHF"), op.apply(Money.of(100, "CHF"))); assertEquals(Money.of(-2000, "CHF"), Money.of(-100, "CHF").with(op)); op = PresentValueOfPerpetuity.of(Rate.of(-0.05)); assertEquals(Money.of(-2000, "CHF"), op.apply(Money.of(100, "CHF"))); } |
PresentValueOfPerpetuity implements MonetaryOperator { @Override public String toString() { return "PresentValueOfPerpetuity{" + "rate=" + rate + '}'; } private PresentValueOfPerpetuity(Rate rate); Rate getRate(); static PresentValueOfPerpetuity of(Rate rate); static MonetaryAmount calculate(MonetaryAmount amount, Rate rate); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } | @Test public void testToString(){ PresentValueOfPerpetuity op = PresentValueOfPerpetuity.of(Rate.of(0.056778)); assertEquals("PresentValueOfPerpetuity{rate=Rate[0.056778]}", op.toString()); } |
FutureValueOfAnnuityDue extends AbstractRateAndPeriodBasedOperator { public static FutureValueOfAnnuityDue of(RateAndPeriods rateAndPeriods) { return new FutureValueOfAnnuityDue(rateAndPeriods); } private FutureValueOfAnnuityDue(RateAndPeriods rateAndPeriods); static FutureValueOfAnnuityDue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } | @Test public void getRate() throws Exception { FutureValueOfAnnuityDue val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(0.03,1) ); assertEquals(val.getRate(), Rate.of(0.03)); }
@Test public void getPeriods() throws Exception { FutureValueOfAnnuityDue val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(0.03,3654) ); assertEquals(val.getPeriods(), 3654); }
@Test public void of_Period1() throws Exception { FutureValueOfAnnuityDue val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 1) ); assertNotNull(val); }
@Test public void of_Period0() throws Exception { FutureValueOfAnnuityDue val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(0.08,0) ); assertNotNull(val); }
@Test public void calculate_Periods0() throws Exception { Money m = Money.of(10, "CHF"); FutureValueOfAnnuityDue val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 0) ); assertEquals(Money.of(0,"CHF"), m.with(val)); val = FutureValueOfAnnuityDue.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"); FutureValueOfAnnuityDue val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 1) ); assertEquals(Money.of(10.50,"CHF"), m.with(val)); val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(-0.05, 1) ); assertEquals(Money.of(9.5,"CHF"), m.with(val)); }
@Test public void calculate_PeriodsN() throws Exception { Money m = Money.of(10, "CHF"); FutureValueOfAnnuityDue val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 10) ); assertEquals(Money.of(132.06787162326262,"CHF").getNumber().numberValue(BigDecimal.class) .doubleValue(), m.with(val).getNumber().numberValue(BigDecimal.class) .doubleValue(), 0.00000000000001d); val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(-0.05, 10) ); assertEquals(Money.of(76.23998154470802,"CHF").getNumber().numberValue(BigDecimal.class).doubleValue(), m.with(val).getNumber().numberValue(BigDecimal.class).doubleValue(), 0.000000000000001d); } |
AnnualPercentageYield implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, 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(); } | @Test public void apply() throws Exception { AnnualPercentageYield ci = AnnualPercentageYield.of( Rate.of(0.05),2 ); assertEquals(ci.apply(Money.of(1,"CHF")),Money.of(0.050625,"CHF")); } |
FutureValueOfAnnuityDue extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private FutureValueOfAnnuityDue(RateAndPeriods rateAndPeriods); static FutureValueOfAnnuityDue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } | @Test public void apply() throws Exception { FutureValueOfAnnuityDue val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(0.08, 10) ); Money m = Money.of(10, "CHF"); assertEquals(val.apply(m), m.with(val)); } |
FutureValueOfAnnuityDue extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "FutureValueOfAnnuityDue{" + "\n " + rateAndPeriods + '}'; } private FutureValueOfAnnuityDue(RateAndPeriods rateAndPeriods); static FutureValueOfAnnuityDue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); } | @Test public void toStringTest() throws Exception { FutureValueOfAnnuityDue val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 10) ); assertEquals("FutureValueOfAnnuityDue{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=10}}", val.toString()); } |
FutureValueFactor { public static BigDecimal calculate(RateAndPeriods rateAndPeriods) { Objects.requireNonNull(rateAndPeriods); BigDecimal base = CalculationContext.one().add(rateAndPeriods.getRate().get()); return base.pow(rateAndPeriods.getPeriods(), CalculationContext.mathContext()); } private FutureValueFactor(); static BigDecimal calculate(RateAndPeriods rateAndPeriods); } | @Test public void calculate_PositiveRates() throws Exception { assertEquals(1.0, FutureValueFactor.calculate(RateAndPeriods.of(0.05,0)).doubleValue(), 0.0d); assertEquals(1.0500, FutureValueFactor.calculate(RateAndPeriods.of(0.05,1)).doubleValue(), 0.0d); assertEquals(1.628894626777441, FutureValueFactor.calculate(RateAndPeriods.of(0.05,10)).doubleValue(), 0.0d); }
@Test public void calculate_NegativeRates() throws Exception { assertEquals(1.0, FutureValueFactor.calculate(RateAndPeriods.of(-0.05,0)).doubleValue(), 0.0d); assertEquals(0.9500, FutureValueFactor.calculate(RateAndPeriods.of(-0.05,1)).doubleValue(), 0.0d); assertEquals(0.5987369392383789, FutureValueFactor.calculate(RateAndPeriods.of(-0.05,10)).doubleValue(), 0.0d); }
@Test public void calculate_Invalid(){ assertEquals(1.0, FutureValueFactor.calculate(RateAndPeriods.of(0,0)).doubleValue(), 0.0d); } |
DoublingTimeWithContCompounding { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTimeWithCompounding with a rate=zero"); } return BigDecimal.valueOf(Math.log(2.0d)).divide(rate.get(), CalculationContext.mathContext()); } private DoublingTimeWithContCompounding(); static BigDecimal calculate(Rate rate); } | @Test public void calculate() throws Exception { assertEquals(8.30116383904126, DoublingTimeWithContCompounding.calculate(Rate.of(0.0835)).doubleValue(), 0.0d); assertEquals(1.386294361119891, DoublingTimeWithContCompounding.calculate(Rate.of(0.5)).doubleValue(), 0.0d); assertEquals(0.6931471805599453, DoublingTimeWithContCompounding.calculate(Rate.of(1)).doubleValue(), 0.0d); assertEquals(15.4032706791099, DoublingTimeWithContCompounding.calculate(Rate.of(0.045)).doubleValue(), 0.0d); }
@Test(expected = MonetaryException.class) public void calculate_Invalid(){ DoublingTimeWithContCompounding.calculate(Rate.of(0)); } |
BalloonLoanPayment extends AbstractRateAndPeriodBasedOperator { public static BalloonLoanPayment of(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount){ return new BalloonLoanPayment(rateAndPeriods, balloonAmount); } 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); } | @Test public void of_notNull() throws Exception { BalloonLoanPayment ci = BalloonLoanPayment.of( RateAndPeriods.of(0.05,1), Money.of(5, "CHF") ); assertNotNull(ci); }
@Test public void of_correctRate() throws Exception { BalloonLoanPayment ci = BalloonLoanPayment.of( RateAndPeriods.of(0.0234,1), Money.of(5, "CHF") ); assertNotNull(ci.getRate()); assertEquals(ci.getRate(), Rate.of(0.0234)); ci = BalloonLoanPayment.of( RateAndPeriods.of(0.05,1), Money.of(5, "CHF") ); assertNotNull(ci.getRate()); assertEquals(ci.getRate(), Rate.of(0.05)); }
@Test public void of_correctPeriods() throws Exception { BalloonLoanPayment ci = BalloonLoanPayment.of( RateAndPeriods.of(0.05,1), Money.of(5, "CHF") ); assertEquals(ci.getPeriods(), 1); ci = BalloonLoanPayment.of( RateAndPeriods.of(0.05,234), Money.of(5, "CHF") ); assertEquals(ci.getPeriods(), 234); }
@Test(expected=MonetaryException.class) public void calculate_zeroPeriods() throws Exception { BalloonLoanPayment.of( RateAndPeriods.of(0.05,0), Money.of(5, "CHF") ); }
@Test public void calculate_onePeriods() throws Exception { BalloonLoanPayment ci = BalloonLoanPayment.of( RateAndPeriods.of(0.05,1), Money.of(5, "CHF") ); assertEquals(Money.of(100,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(100,"CHF")); assertEquals(Money.of(0,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(-5,"CHF")); assertEquals(Money.of(-1,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(-6.05,"CHF")); }
@Test public void calculate_twoPeriods() throws Exception { BalloonLoanPayment ci = BalloonLoanPayment.of( RateAndPeriods.of(0.05,2), Money.of(5, "CHF") ); assertEquals(Money.of(100,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(51.34,"CHF")); assertEquals(Money.of(0,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(-2.44,"CHF")); assertEquals(Money.of(-1,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(-2.98,"CHF")); } |
Rate implements MonetaryOperator, Supplier<BigDecimal> { public static Rate of(BigDecimal rate) { return new Rate(rate, null); } private Rate(BigDecimal rate, String info); static Rate zero(String info); static Rate of(BigDecimal rate); static Rate of(BigDecimal rate, String info); static Rate of(Number rate); static Rate of(Number rate, String info); @Override int hashCode(); @Override boolean equals(Object obj); @Override BigDecimal get(); String getInfo(); @Override String toString(); @Override MonetaryAmount apply(MonetaryAmount amount); static final Rate ZERO; } | @Test public void of_BD() throws Exception { Rate r = Rate.of(BigDecimal.valueOf(0.0567)); assertNotNull(r); }
@Test public void of_Num() throws Exception { Rate r = Rate.of(0.0567f); assertNotNull(r); }
@Test(expected=NullPointerException.class) public void of_Null() throws Exception { Rate.of((Number)null); } |
Rate implements MonetaryOperator, Supplier<BigDecimal> { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((rate == null) ? 0 : rate.hashCode()); result = prime * result + ((info == null) ? 0 : info.hashCode()); return result; } private Rate(BigDecimal rate, String info); static Rate zero(String info); static Rate of(BigDecimal rate); static Rate of(BigDecimal rate, String info); static Rate of(Number rate); static Rate of(Number rate, String info); @Override int hashCode(); @Override boolean equals(Object obj); @Override BigDecimal get(); String getInfo(); @Override String toString(); @Override MonetaryAmount apply(MonetaryAmount amount); static final Rate ZERO; } | @Test public void testHashCode() throws Exception { Rate r1 = Rate.of(0.0567f); Rate r2 = Rate.of(0.0567d); assertTrue(r1.hashCode()==r2.hashCode()); r2 = Rate.of(0.0568d); assertFalse(r1.hashCode()==r2.hashCode()); } |
Rate implements MonetaryOperator, Supplier<BigDecimal> { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Rate other = (Rate) obj; if (rate == null) { if (other.rate != null) return false; } else if (!rate.equals(other.rate)) return false; if (info == null) { if (other.info != null) return false; } else if (!info.equals(other.info)) return false; return true; } private Rate(BigDecimal rate, String info); static Rate zero(String info); static Rate of(BigDecimal rate); static Rate of(BigDecimal rate, String info); static Rate of(Number rate); static Rate of(Number rate, String info); @Override int hashCode(); @Override boolean equals(Object obj); @Override BigDecimal get(); String getInfo(); @Override String toString(); @Override MonetaryAmount apply(MonetaryAmount amount); static final Rate ZERO; } | @Test public void testEquals() throws Exception { Rate r1 = Rate.of(0.0567f); Rate r2 = Rate.of(0.0567d); assertEquals(r1, r2); r2 = Rate.of(0.0568d); assertNotSame(r1, r2); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.