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 rati... | @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 elementHelpe... | @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!"); ... |
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(); PropertyHolde... | @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... | @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 se... | @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(); PropertyHolde... | @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 : s... | @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 IllegalArgu... | @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 image... | @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.ge... | @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.se... | @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... |
ElementHelper { public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Li... | @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 PageCo... |
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, Str... | @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().ge... |
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()... | @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, parameter... |
ElementHelper { boolean conditionMatches(Condition condition) { return conditionMatches(getExpressionEvaluator(), condition); } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicati... | @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.setExpressio... |
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(); } messages... | @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.getMessageLis... |
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 != err... | @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.... |
ElementHelper { void setSelectionTitles(Data data, ApplicationRequest applicationRequest) { setSelectionTitles(data.getSelections(), applicationRequest); for (SelectionGroup group : data.getSelectionGroups()) { setSelectionTitles(group.getSelections(), applicationRequest); } } ElementHelper(Site site, Application appli... | @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... |
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 a... | @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 Application... |
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> referenceParame... | @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, "p... |
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(pathInf... | @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.get... |
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 (ValidationGro... | @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(Close... |
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 != ... | @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() { Lab... |
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.getLab... | @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.getLa... |
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())... | @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(Reque... |
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 getTextSelect... | @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()); Ass... |
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, Str... | @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... |
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 ... |
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 notBl... | @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(fieldWra... |
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... | @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.re... |
DefaultFieldConverter extends ConverterBase { static String stripNonPrintableCharacter(String value) { return StringNormalizer.removeNonPrintableCharacters(value); } DefaultFieldConverter(ExpressionEvaluator expressionEvaluator, ConversionService conversionService,
Environment environment, MessageSource messageSourc... | @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 : allowedContrC... |
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 = g... | @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(fieldWrappe... |
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|>])");... | @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=... |
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... | @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() t... |
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods); st... | @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) ); assertNotN... |
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods); static MonetaryAmou... | @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 c... | @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 ... | @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 grow... | @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 cal... | @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,... | @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 getDi... | @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 ); assert... |
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 getGrowthRat... | @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 get... | @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 ... | @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()); ass... |
ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); } private ContinuousCompoundInterest(RateAndPeriods rateAndPeriods); static ContinuousCompoundInterest of(RateAndPe... | @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) ); assertNot... |
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(... | @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()); asse... |
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, Rate... | @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(RateA... |
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(), ... | @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(... |
PriceToBookValue { public static BigDecimal calculate(MonetaryAmount marketPricePerShare, MonetaryAmount bookValuePerShare) { BigDecimal marketPricePerShareValue = BigDecimal.valueOf(marketPricePerShare.getNumber().doubleValueExact()); BigDecimal bookValuePerShareValue = BigDecimal.valueOf(bookValuePerShare.getNumber()... | @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(... | @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(... | @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 fundL... | @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(stockPriceAfterFirstP... | @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()); ret... | @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 net... | @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.divi... | @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 sharePric... | @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 ri... | @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(B... | @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... | @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 requiredRate... | @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 growthR... | @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(); Ra... | @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(... | @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, Ra... |
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 shou... | @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.calculate... |
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()... | @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 retur... | @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().doubleValueE... | @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(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 ... | @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... | @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 divide... | @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();... | @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(Ra... | @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(face... | @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 ... | @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); stat... | @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 rate... | @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)... |
PresentValueOfAnnuityDue extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private PresentValueOfAnnuityDue(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuityDue of(RateAndPeriods rateAndPeriods); static Mon... | @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 Mone... | @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(); s... | @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.getR... |
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 rate... | @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... | @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 = Pre... |
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, Rat... | @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 rateAndPe... | @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) ); ... |
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 cal... | @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 Moneta... | @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 Monetary... | @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(); ... | @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(Rate... |
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 Doublin... | @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, DoublingTimeWith... |
BalloonLoanPayment extends AbstractRateAndPeriodBasedOperator { public static BalloonLoanPayment of(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount){ return new BalloonLoanPayment(rateAndPeriods, balloonAmount); } private BalloonLoanPayment(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount); Mone... | @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") ); a... |
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 ... | @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... | @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(o... | @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 community queries yet
The top public SQL queries from the community will appear here once available.