method2testcases
stringlengths
118
6.63k
### Question: ApplicationStartup { protected static void replaceInFile(File file, String search, String replacement) throws IOException { Path path = file.toPath(); Charset charset = StandardCharsets.UTF_8; String content = new String(Files.readAllBytes(path), charset); content = content.replaceAll(Pattern.quote(search...
### Question: DatabaseController extends ControllerBase { @PostMapping(value = "/platform/database/initialize") public ResponseEntity<Database> initialize( @RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged) throws Exception { DatabaseConnection platformConnection = databaseServ...
### Question: AppNGizer implements AppNGizerClient { static String encode(String segment) { try { return UriUtils.encodePathSegment(segment, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return segment; } } AppNGizer(String endpoint, String sharedSecret); Home welcome(); Home login(); Subje...
### Question: AppNGizer implements AppNGizerClient { public Package uploadPackage(String name, File archive) throws IOException { MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>(); multipartRequest.add("file", new FileSystemResource(archive)); HttpHeaders headers = getHeaders(); headers.setCo...
### Question: StyleSheetProvider { public StyleSheetProvider() { } StyleSheetProvider(); void init(); void setMasterSource(InputStream masterXsl, String templateRoot); void addStyleSheet(InputStream styleSheet, String reference); byte[] getStyleSheet(boolean deleteIncludes); byte[] getStyleSheet(boolean deleteIncludes,...
### Question: ApplicationPropertyConstantCreator { public static void main(String[] args) throws IOException, JAXBException { if (args.length < 3) { throw new IllegalArgumentException("need 3 params (filePath, targetClass, outFolder)"); } String filePath = args[0]; String targetClass = args[1]; String outfolder = args[...
### Question: ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> ...
### Question: XPathProcessor { public String getString(String xpathExpression) { return (String) evaluate(document, xpathExpression, XPathConstants.STRING); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, Strin...
### Question: XPathProcessor { public Boolean getBoolean(String xpathExpression) { return (Boolean) evaluate(document, xpathExpression, XPathConstants.BOOLEAN); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, S...
### Question: XPathProcessor { public Number getNumber(String xpathExpression) { return (Number) evaluate(document, xpathExpression, XPathConstants.NUMBER); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, Strin...
### Question: XPathProcessor { public String getXml(Node node) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getXml(node, outputStream); return new String(outputStream.toByteArray()); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document ...
### Question: XPathProcessor { public Text newText(String tagName) { Text text = document.createTextNode(tagName); return text; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(N...
### Question: ImageProcessor { public ImageProcessor fitToHeight(Integer maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); if (height > maxHeight) { height = maxHeight; width = Math.round(((float) maxHeight / height) * width); } r...
### Question: XPathProcessor { public CDATASection newCDATA(String tagName) { CDATASection cdata = document.createCDATASection(tagName); return cdata; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String name...
### Question: XPathProcessor { public Element newElement(String tagName) { Element element = document.createElement(tagName); return element; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); S...
### Question: XPathProcessor { public Attr newAttribute(String name, String value) { Attr attribute = document.createAttribute(name); attribute.setNodeValue(value); return attribute; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setName...
### Question: RequestDataBinder extends DataBinder { @SuppressWarnings("unchecked") public T bind() { MutablePropertyValues mpvs = new MutablePropertyValues(); for (String name : request.getParameterNames()) { addValue(mpvs, name, request.getParameterList(name)); } for (String name : request.getFormUploads().keySet()) ...
### Question: DataContainer { public void setItem(Object item) { this.item = item; setSingleResult(true); initItem(); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Co...
### Question: DataContainer { public void setPage(Collection<?> items, Pageable pageable) { setPage(items, pageable, false); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void set...
### Question: DataContainer { public void setItems(Collection<?> items) { this.items = items; setSingleResult(false); initItems(items); setPageable(null); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(...
### Question: AuthTools { public static String getMd5Digest(String input) { return getDigest(input, MessageDigestAlgorithms.MD5); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); s...
### Question: AuthTools { public static String getSha1Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_1); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input)...
### Question: AuthTools { public static String getSha512Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_512); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String in...
### Question: ImageProcessor { public ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); float ratioWidth = (float) maxwidth / width; float ratioHeight = (float) maxHeight / heig...
### Question: PropertyHolder implements Properties { public String getString(String name, String defaultValue) { Property property = getProperty(name); if (null != property) { return property.getString(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder();...
### Question: PropertyHolder implements Properties { public Boolean getBoolean(String name) { return getBoolean(name, null); } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Proper...
### Question: PropertyHolder implements Properties { public Float getFloat(String name, Float defaultValue) { Property property = getProperty(name); if (null != property) { return property.getFloat(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); Pro...
### Question: PropertyHolder implements Properties { public Double getDouble(String name, Double defaultValue) { Property property = getProperty(name); if (null != property) { return property.getDouble(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder();...
### Question: PropertyHolder implements Properties { public List<String> getList(String name, String defaultValue, String delimiter) { List<String> result = new ArrayList<>(); String string = getString(name, defaultValue); if (null != string && string.length() > 0) { String[] splitted = string.split(delimiter); for (St...
### Question: PropertyHolder implements Properties { public java.util.Properties getProperties(String name) { String clob = getClob(name); if (null != clob) { java.util.Properties properties = new java.util.Properties(); try { properties.load(new ByteArrayInputStream(clob.getBytes())); } catch (IOException e) { throw n...
### Question: ImageProcessor { public ImageMetaData getMetaData() throws IOException { ImageInputStream input = new FileImageInputStream(sourceFile); Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(input); if (imageReaders.hasNext()) { ImageReader reader = imageReaders.next(); reader.setInput(input); Image...
### Question: PropertyHolder implements Properties { public java.util.Properties getPlainProperties() { java.util.Properties props = new java.util.Properties(); Set<String> propertyNames = getPropertyNames(); for (String name : propertyNames) { Property property = getProperty(name); if (null != property) { String value...
### Question: ElementHelper { MetaData getFilteredMetaData(ApplicationRequest request, MetaData metaData, boolean write) { MetaData result = new MetaData(); if (null != metaData) { result.setBinding(metaData.getBinding()); result.setResultSelector(metaData.getResultSelector()); result.setBindClass(metaData.getBindClass...
### Question: ElementHelper { public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), paramet...
### Question: ElementHelper { Options getOptions(List<BeanOption> beanOptions) { OptionsImpl options = new OptionsImpl(); if (null != beanOptions) { for (BeanOption beanOption : beanOptions) { OptionImpl opt = new OptionImpl(beanOption.getName()); Map<QName, String> attributes = beanOption.getOtherAttributes(); for (En...
### Question: ElementHelper { void initOptions(List<BeanOption> beanOptions) { if (null != beanOptions) { for (BeanOption beanOption : beanOptions) { Map<QName, String> attributes = beanOption.getOtherAttributes(); for (Entry<QName, String> entry : attributes.entrySet()) { String value = expressionEvaluator.evaluate(en...
### Question: ElementHelper { boolean conditionMatches(Condition condition) { return conditionMatches(getExpressionEvaluator(), condition); } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationReq...
### Question: ElementHelper { public static Messages addMessages(Environment environment, Messages messages) { Messages messagesFromSession = environment.getAttribute(SESSION, Session.Environment.MESSAGES); if (messages.getMessageList().size() > 0) { if (null == messagesFromSession) { messagesFromSession = new Messages...
### Question: Command { public static int execute(String command, StreamConsumer<?> outputConsumer, StreamConsumer<?> errorConsumer) { try { LOGGER.debug("executing: '{}'", command); Process process = Runtime.getRuntime().exec(command); if (null != outputConsumer) { outputConsumer.consume(process.getInputStream()); } i...
### Question: ElementHelper { void setSelectionTitles(Data data, ApplicationRequest applicationRequest) { setSelectionTitles(data.getSelections(), applicationRequest); for (SelectionGroup group : data.getSelectionGroups()) { setSelectionTitles(group.getSelections(), applicationRequest); } } ElementHelper(Site site, App...
### Question: ElementHelper { void addTemplates(ApplicationConfigProvider applicationConfigProvider, Config config) { List<Template> templates = config.getTemplates(); if (null != templates) { applicationConfigProvider.getApplicationRootConfig().getConfig().getTemplates().addAll(templates); } } ElementHelper(Site site,...
### Question: ElementHelper { public String getOutputPrefix(Environment env) { if (Boolean.TRUE.equals(env.removeAttribute(REQUEST, EnvironmentKeys.EXPLICIT_FORMAT))) { Path pathInfo = env.getAttribute(REQUEST, EnvironmentKeys.PATH_INFO); StringBuilder prefix = new StringBuilder().append(pathInfo.getGuiPath()); prefix....
### Question: ElementHelper { public Class<?>[] getValidationGroups(MetaData metaData, Object bindObject) { List<Class<?>> groups = new ArrayList<>(); ValidationGroups validationGroups = metaData.getValidation(); if (null != validationGroups) { getExpressionEvaluator().setVariable(AdapterBase.CURRENT, bindObject); for ...
### Question: LabelSupport { public final void setLabels(Config config, ExpressionEvaluator expressionEvaluator, ParameterSupport fieldParameters) { if (null != config) { setLabel(config.getTitle(), expressionEvaluator, fieldParameters); setLabel(config.getDescription(), expressionEvaluator, fieldParameters); setLabels...
### Question: SelectionFactory extends OptionFactory<SelectionFactory.Selection> { public Selection getDateSelection(String id, String title, String value, String dateFormat) { Selection selection = getSimpleSelection(id, title, value, SelectionType.DATE); selection.setFormat(dateFormat); return selection; } Selection...
### Question: SelectionFactory extends OptionFactory<SelectionFactory.Selection> { public Selection getTextSelection(String id, String title, String value) { return getSimpleSelection(id, title, value, SelectionType.TEXT); } Selection getTextSelection(String id, String title, String value); Selection getDateSelection(...
### Question: AttributeWrapper implements Serializable { public String getSiteName() { return siteName; } AttributeWrapper(); AttributeWrapper(String siteName, Object value); Object getValue(); String getSiteName(); @Override String toString(); }### Answer: @Test public void test() { Assert.assertEquals("appng", new ...
### Question: DefaultFieldConverter extends ConverterBase { @Override public void setObject(FieldWrapper field, RequestContainer request) { String value = stripNonPrintableCharacter(request.getParameter(field.getBinding())); Object object = null; Class<?> targetClass = field.getTargetClass(); if (null != targetClass) {...
### Question: XHTML { public static String removeAttr(String tag, String attr) { String pattern = getAttributeExpression(attr); Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(tag); if (m.find()) { tag = tag.replaceAll(pattern, ""); } return tag; } static String removeAttr(String tag, String attr); static ...
### Question: DefaultFieldConverter extends ConverterBase { static String stripNonPrintableCharacter(String value) { return StringNormalizer.removeNonPrintableCharacters(value); } DefaultFieldConverter(ExpressionEvaluator expressionEvaluator, ConversionService conversionService, Environment environment, MessageSourc...
### Question: ListFieldConverter extends ConverterBase { @Override public void setObject(FieldWrapper field, RequestContainer request) { String name = field.getBinding(); BeanWrapper wrapper = field.getBeanWrapper(); wrapper.setAutoGrowNestedPaths(true); List<String> values = request.getParameterList(name); Class<?> pr...
### Question: XHTML { public static String setAttr(String tag, String attr, String value) { Pattern p = Pattern.compile(getAttributeExpression(attr)); Matcher m = p.matcher(tag); if (m.find()) { tag = tag.replaceFirst(getAttributeExpression(attr), " " + attr + "=\"" + value + "\""); } else { p = Pattern.compile("(<\\w+...
### Question: AnnualPercentageYield implements MonetaryOperator { public static AnnualPercentageYield of(Rate rate, int periods){ return new AnnualPercentageYield(rate, periods); } private AnnualPercentageYield(Rate rate, int periods); int getPeriods(); Rate getRate(); static AnnualPercentageYield of(Rate rate, int pe...
### Question: PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuity of(RateAndPeriods rateA...
### Question: PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods); stati...
### Question: PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValueOfAnnuity{" + "\n " + rateAndPeriods + '}'; } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods); static Mo...
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { public Rate getDiscountRate() { return discountRate; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); Rate getDiscountRate(); Rate getGrowthRate(); int getPeriods(); static FutureValueGrowingAnnuity of(Rate disco...
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { public Rate getGrowthRate() { return growthRate; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); Rate getDiscountRate(); Rate getGrowthRate(); int getPeriods(); static FutureValueGrowingAnnuity of(Rate discountR...
### Question: BalloonLoanPayment extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amountPV) { if(!balloonAmount.getCurrency().equals(amountPV.getCurrency())){ throw new MonetaryException("Currency mismatch: " + balloonAmount.getCurrency() + " <> "+amountPV.getCurrency())...
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { public int getPeriods() { return periods; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); Rate getDiscountRate(); Rate getGrowthRate(); int getPeriods(); static FutureValueGrowingAnnuity of(Rate discountRate, Ra...
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int period...
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount firstPayment) { return calculate(firstPayment, discountRate, growthRate, periods); } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); Rate getDiscountRate(); Rat...
### Question: FutureValueGrowingAnnuity implements MonetaryOperator { @Override public String toString() { return "FutureValueGrowingAnnuity{" + "discountRate=" + discountRate + ", growthRate=" + growthRate + ", periods=" + periods + '}'; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int peri...
### Question: PresentValue extends AbstractRateAndPeriodBasedOperator { public static PresentValue of(RateAndPeriods rateAndPeriods) { return new PresentValue(rateAndPeriods); } private PresentValue(RateAndPeriods rateAndPeriods); static PresentValue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(M...
### Question: ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); } private ContinuousCompoundInterest(RateAndPeriods rateAndPeriods); static ContinuousCompoundInteres...
### Question: PresentValue extends AbstractRateAndPeriodBasedOperator { public static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods){ Objects.requireNonNull(amount, "Amount required"); Objects.requireNonNull(rateAndPeriods, "RateAndPeriods required"); return amount.divide(PresentValueFac...
### Question: PresentValue extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValue{" + "\n " + rateAndPeriods + '}'; } private PresentValue(RateAndPeriods rateAndPeriods); static PresentValue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmoun...
### Question: PresentValueOfAnnuityPaymentFactor { public static BigDecimal calculate(RateAndPeriods rateAndPeriods) { Objects.requireNonNull(rateAndPeriods, "Rate required."); if(rateAndPeriods.getPeriods()==0){ return BigDecimal.ZERO; } BigDecimal fact1 = one().add(rateAndPeriods.getRate().get()).pow(-rateAndPeriods....
### Question: PriceToBookValue { public static BigDecimal calculate(MonetaryAmount marketPricePerShare, MonetaryAmount bookValuePerShare) { BigDecimal marketPricePerShareValue = BigDecimal.valueOf(marketPricePerShare.getNumber().doubleValueExact()); BigDecimal bookValuePerShareValue = BigDecimal.valueOf(bookValuePerSha...
### Question: DividendPayoutRatio { public static BigDecimal calculate(MonetaryAmount dividends, MonetaryAmount netIncome) { BigDecimal dividendsValue = BigDecimal.valueOf(dividends.getNumber().doubleValueExact()); BigDecimal netIncomeValue = BigDecimal.valueOf(netIncome.getNumber().doubleValueExact()); return dividend...
### Question: GeometricMeanReturn { public static double calculate(List<Rate> ratesOfReturn) { BigDecimal product = BigDecimal.ONE; for (Rate rateOfReturn : ratesOfReturn) { if (rateOfReturn == null) { throw new IllegalArgumentException("The list of rates cannot contain null elements"); } product = product.multiply(rat...
### Question: NetAssetValue { public static MonetaryAmount calculate(MonetaryAmount fundAssets, MonetaryAmount fundLiabilities, double outstandingShares) { return fundAssets.subtract(fundLiabilities).divide(outstandingShares); } private NetAssetValue(); static MonetaryAmount calculate(MonetaryAmount fundAssets, Moneta...
### Question: CapitalGainsYield { public static BigDecimal calculate(MonetaryAmount initialStockPrice, MonetaryAmount stockPriceAfterFirstPeriod) { BigDecimal initialStockPriceValue = BigDecimal.valueOf(initialStockPrice.getNumber().doubleValueExact()); BigDecimal stockValueAfterFirstPeriod = BigDecimal.valueOf(stockPr...
### Question: CurrentYield { public static BigDecimal calculate(MonetaryAmount annualCoupons, MonetaryAmount currentBondPrice) { BigDecimal annualCouponsValue = BigDecimal.valueOf(annualCoupons.getNumber().doubleValueExact()); BigDecimal currentBondPriceValue = BigDecimal.valueOf(currentBondPrice.getNumber().doubleValu...
### Question: DilutedEarningsPerShare { public static MonetaryAmount calculate(MonetaryAmount netIncome, BigDecimal averageShares, BigDecimal otherConvertibleInstruments) { return netIncome.divide(averageShares.add(otherConvertibleInstruments)); } private DilutedEarningsPerShare(); static MonetaryAmount calculate(Mone...
### Question: DividendYield { public static BigDecimal calculate(MonetaryAmount dividends, MonetaryAmount initialPrice) { BigDecimal dividendsValue = BigDecimal.valueOf(dividends.getNumber().doubleValueExact()); BigDecimal initialPriceValue = BigDecimal.valueOf(initialPrice.getNumber().doubleValueExact()); return divid...
### Question: PriceToSalesRatio { public static BigDecimal calculate(MonetaryAmount sharePrice, MonetaryAmount salesPerShare) { BigDecimal sharePriceValue = BigDecimal.valueOf(sharePrice.getNumber().doubleValueExact()); BigDecimal salesPerShareValue = BigDecimal.valueOf(salesPerShare.getNumber().doubleValueExact()); re...
### Question: BookValuePerShare { public static MonetaryAmount calculate(MonetaryAmount equity, int numberOfCommonShares) { return equity.divide(numberOfCommonShares); } private BookValuePerShare(); static MonetaryAmount calculate(MonetaryAmount equity, int numberOfCommonShares); }### Answer: @Test public void testCa...
### Question: RiskPremium { public static BigDecimal calculate(Rate assetReturn, Rate riskFreeReturn) { return assetReturn.get().subtract(riskFreeReturn.get()); } private RiskPremium(); static BigDecimal calculate(Rate assetReturn, Rate riskFreeReturn); static BigDecimal calculateWithCAPM(BigDecimal beta, Rate marketR...
### Question: RiskPremium { public static BigDecimal calculateWithCAPM(BigDecimal beta, Rate marketReturn, Rate riskFreeReturn) { return beta.multiply(marketReturn.get().subtract(riskFreeReturn.get())); } private RiskPremium(); static BigDecimal calculate(Rate assetReturn, Rate riskFreeReturn); static BigDecimal calcu...
### Question: BidAskSpread { public static MonetaryAmount calculate(MonetaryAmount askPrice, MonetaryAmount bidPrice) { return askPrice.subtract(bidPrice); } private BidAskSpread(); static MonetaryAmount calculate(MonetaryAmount askPrice, MonetaryAmount bidPrice); }### Answer: @Test public void testCalculate() { asse...
### Question: EarningsPerShare { public static MonetaryAmount calculate(MonetaryAmount netIncome, double weightedAverageOfOutstandingShares) { return netIncome.divide(weightedAverageOfOutstandingShares); } private EarningsPerShare(); static MonetaryAmount calculate(MonetaryAmount netIncome, double weightedAverageOfOut...
### Question: DividendsPerShare { public static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares) { return dividends.divide(numberOfShares); } private DividendsPerShare(); static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares); }### Answer: @Test public void testCalcu...
### Question: PriceToEarningsRatio { public static BigDecimal calculate(MonetaryAmount pricePerShare, MonetaryAmount earningsPerShare) { BigDecimal pricePerShareValue = BigDecimal.valueOf(pricePerShare.getNumber().doubleValueExact()); BigDecimal earningsPerShareValue = BigDecimal.valueOf(earningsPerShare.getNumber().do...
### Question: StockPresentValue implements MonetaryOperator { public static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate) { return estimatedDividends.divide(requiredRateOfReturn.get().subtract(growthRate.get())); } private StockPresentValue(Rat...
### Question: StockPresentValue implements MonetaryOperator { public static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, Rate.ZERO); } private StockPresentValue(Rate requiredRateOfReturn...
### Question: StockPresentValue implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount estimatedDividends) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, growthRate); } private StockPresentValue(Rate requiredRateOfReturn, Rate growthRate); Rate getRequiredRate...
### Question: TaxEquivalentYield { public static BigDecimal calculate(Rate taxFreeYield, Rate taxRate) { return taxFreeYield.get().divide(BigDecimal.ONE.subtract(taxRate.get()), MathContext.DECIMAL64); } private TaxEquivalentYield(); static BigDecimal calculate(Rate taxFreeYield, Rate taxRate); }### Answer: @Test pub...
### Question: HoldingPeriodReturn { public static BigDecimal calculate(List<Rate> returns) { BigDecimal product = BigDecimal.ONE; for (Rate rateOfReturn : returns) { if (rateOfReturn == null) { throw new IllegalArgumentException("The list of returns cannot contain null elements"); } product = product.multiply(rateOfRet...
### Question: HoldingPeriodReturn { public static BigDecimal calculateForSameReturn(Rate periodicRate, int numberOfPeriods) { if (periodicRate == null) { throw new IllegalArgumentException("The list of returns cannot contain null elements"); } if (numberOfPeriods <= 0) { throw new IllegalArgumentException("The number o...
### Question: ZeroCouponBondYield { public static double calculate(MonetaryAmount faceAmount, MonetaryAmount presentAmount, int numberOfPeriods) { final BigDecimal faceValue = BigDecimal.valueOf(faceAmount.getNumber().doubleValueExact()); final BigDecimal presentValue = BigDecimal.valueOf(presentAmount.getNumber().doub...
### Question: BondEquivalentYield { public static BigDecimal calculate(MonetaryAmount faceValue, MonetaryAmount priceAmount, int numberOfDaysToMaturity) { BigDecimal face = BigDecimal.valueOf(faceValue.getNumber().doubleValueExact()); BigDecimal price = BigDecimal.valueOf(priceAmount.getNumber().doubleValueExact()); Bi...
### Question: TotalStockReturn { public static BigDecimal calculate(MonetaryAmount initialPrice, MonetaryAmount endingPrice, MonetaryAmount dividends) { BigDecimal initialPriceValue = BigDecimal.valueOf(initialPrice.getNumber().doubleValueExact()); BigDecimal endingPriceValue = BigDecimal.valueOf(endingPrice.getNumber(...
### Question: EquityMultiplier { public static BigDecimal calculate(MonetaryAmount totalAssets, MonetaryAmount equity) { BigDecimal totalAssetValue = BigDecimal.valueOf(totalAssets.getNumber().doubleValueExact()); BigDecimal equityValue = BigDecimal.valueOf(equity.getNumber().doubleValueExact()); return totalAssetValue...
### Question: CapitalAssetPricingModelFormula { public static Rate calculate(Rate riskFreeRate, BigDecimal beta, Rate marketReturn) { return calculate(riskFreeRate, beta, marketReturn, BigDecimal.ZERO); } private CapitalAssetPricingModelFormula(); static Rate calculate(Rate riskFreeRate, BigDecimal beta, Rate marketRe...
### Question: PreferredStock implements MonetaryOperator { public static MonetaryAmount calculate(MonetaryAmount dividend, Rate discountRate) { return dividend.divide(discountRate.get()); } private PreferredStock(Rate discountRate); Rate getDiscountRate(); static PreferredStock of(Rate discountRate); static MonetaryAm...
### Question: PreferredStock implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount dividend) { return calculate(dividend, discountRate); } private PreferredStock(Rate discountRate); Rate getDiscountRate(); static PreferredStock of(Rate discountRate); static MonetaryAmount calculate(Monetar...
### Question: ZeroCouponBondValue implements MonetaryOperator { public static MonetaryAmount calculate(MonetaryAmount face, Rate rate, int numberOfYearsToMaturity) { return face.divide(BigDecimal.ONE.add(rate.get()).pow(numberOfYearsToMaturity)); } private ZeroCouponBondValue(Rate rate, int numberOfYearsToMaturity); R...
### Question: ZeroCouponBondValue implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount face) { return calculate(face, rate, numberOfYearsToMaturity); } private ZeroCouponBondValue(Rate rate, int numberOfYearsToMaturity); Rate getRate(); int getNumberOfYearsToMaturity(); static ZeroCouponB...
### Question: YieldToMaturity { public static BigDecimal calculate(MonetaryAmount couponPaymentAmount, MonetaryAmount faceAmount, MonetaryAmount priceAmount, int numberOfYearsToMaturity) { final BigDecimal coupon = BigDecimal.valueOf(couponPaymentAmount.getNumber().doubleValueExact()); final BigDecimal face = BigDecima...