target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@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); }
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 { 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 { 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); }
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); }
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 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); }
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 { 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 { 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); }
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); }
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 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")); }
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 { 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 { 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); }
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); }
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 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"))); }
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 { 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 { 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); }
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); }
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 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)); }
boolean conditionMatches(Condition condition) { return conditionMatches(getExpressionEvaluator(), condition); }
ElementHelper { boolean conditionMatches(Condition condition) { return conditionMatches(getExpressionEvaluator(), condition); } }
ElementHelper { boolean conditionMatches(Condition condition) { return conditionMatches(getExpressionEvaluator(), condition); } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); }
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); }
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 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); }
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 { 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 { 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); }
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); }
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 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); } }
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; }
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; } }
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; } }
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); }
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 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()); }
void setSelectionTitles(Data data, ApplicationRequest applicationRequest) { setSelectionTitles(data.getSelections(), applicationRequest); for (SelectionGroup group : data.getSelectionGroups()) { setSelectionTitles(group.getSelections(), applicationRequest); } }
ElementHelper { void setSelectionTitles(Data data, ApplicationRequest applicationRequest) { setSelectionTitles(data.getSelections(), applicationRequest); for (SelectionGroup group : data.getSelectionGroups()) { setSelectionTitles(group.getSelections(), applicationRequest); } } }
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); }
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); }
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 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()); }
void addTemplates(ApplicationConfigProvider applicationConfigProvider, Config config) { List<Template> templates = config.getTemplates(); if (null != templates) { applicationConfigProvider.getApplicationRootConfig().getConfig().getTemplates().addAll(templates); } }
ElementHelper { void addTemplates(ApplicationConfigProvider applicationConfigProvider, Config config) { List<Template> templates = config.getTemplates(); if (null != templates) { applicationConfigProvider.getApplicationRootConfig().getConfig().getTemplates().addAll(templates); } } }
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); }
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); }
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 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")); }
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 { 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 { 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); }
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); }
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 @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()); } }
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 { 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 { 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); }
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); }
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 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")); }
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 { 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 { 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); }
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); }
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 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); }
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 { 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 { 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); }
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); }
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 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()); }
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 { 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 { 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); }
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); }
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 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()); }
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 { 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 { 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); }
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); }
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 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()); }
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 { 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 { 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); }
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); }
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 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()); }
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 { 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 { 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); }
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); }
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 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); }
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; }
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; } }
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; } }
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); }
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 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()); }
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 { 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 { 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); }
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); }
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 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()); }
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 { 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 { 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); }
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); }
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 testLabelNoKey() { LabelSupport labelSupport = getLabelSupport(); Label label = new Label(); label.setValue("key2"); labelSupport.setLabel(label, expressionEvaluator, null); Assert.assertEquals("some value", label.getValue()); }
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 { 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 { 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); }
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); }
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 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()); }
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 { 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 { 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); }
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); }
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 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+') }")); }
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 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 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); }
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(); }
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 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()); }
public Selection getDateSelection(String id, String title, String value, String dateFormat) { Selection selection = getSimpleSelection(id, title, value, SelectionType.DATE); selection.setFormat(dateFormat); return selection; }
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; } }
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; } }
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); }
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 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()); }
public Selection getDateSelection(String id, String title, String value, String dateFormat) { Selection selection = getSimpleSelection(id, title, value, SelectionType.DATE); selection.setFormat(dateFormat); return selection; }
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; } }
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; } }
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); }
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 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()); }
public Selection getTextSelection(String id, String title, String value) { return getSimpleSelection(id, title, value, SelectionType.TEXT); }
SelectionFactory extends OptionFactory<SelectionFactory.Selection> { public Selection getTextSelection(String id, String title, String value) { return getSimpleSelection(id, title, value, SelectionType.TEXT); } }
SelectionFactory extends OptionFactory<SelectionFactory.Selection> { public Selection getTextSelection(String id, String title, String value) { return getSimpleSelection(id, title, value, SelectionType.TEXT); } }
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); }
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 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()); }
public String getSiteName() { return siteName; }
AttributeWrapper implements Serializable { public String getSiteName() { return siteName; } }
AttributeWrapper implements Serializable { public String getSiteName() { return siteName; } AttributeWrapper(); AttributeWrapper(String siteName, Object value); }
AttributeWrapper implements Serializable { public String getSiteName() { return siteName; } AttributeWrapper(); AttributeWrapper(String siteName, Object value); Object getValue(); String getSiteName(); @Override String toString(); }
AttributeWrapper implements Serializable { public String getSiteName() { return siteName; } AttributeWrapper(); AttributeWrapper(String siteName, Object value); Object getValue(); String getSiteName(); @Override String toString(); }
@Test public void testSetObject() throws Exception { fieldConverter.setObject(fieldWrapper, request); Assert.assertEquals(Boolean.TRUE, fieldWrapper.getObject()); }
@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 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 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); }
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); }
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 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); }
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; }
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; } }
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; } }
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); }
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 testSetObjectEmptyValue() throws Exception { Mockito.when(request.getParameter(OBJECT)).thenReturn(""); fieldConverter.setObject(fieldWrapper, request); Assert.assertEquals(null, fieldWrapper.getObject()); }
@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 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 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); }
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); }
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(expected = ConversionException.class) public void testSetObjectInvalidValue() throws Exception { Mockito.when(request.getParameter(OBJECT)).thenReturn("blaa"); fieldConverter.setObject(fieldWrapper, request); }
@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 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 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); }
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); }
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 testSetObjectNull() throws Exception { Mockito.when(request.getParameter(OBJECT)).thenReturn(null); fieldConverter.setObject(fieldWrapper, request); Assert.assertNull(fieldWrapper.getObject()); }
@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 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 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); }
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); }
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 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)); } }
static String stripNonPrintableCharacter(String value) { return StringNormalizer.removeNonPrintableCharacters(value); }
DefaultFieldConverter extends ConverterBase { static String stripNonPrintableCharacter(String value) { return StringNormalizer.removeNonPrintableCharacters(value); } }
DefaultFieldConverter extends ConverterBase { static String stripNonPrintableCharacter(String value) { return StringNormalizer.removeNonPrintableCharacters(value); } DefaultFieldConverter(ExpressionEvaluator expressionEvaluator, ConversionService conversionService, Environment environment, MessageSource messageSource); }
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); }
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 testSetObject() throws Exception { fieldConverter.setObject(fieldWrapper, request); Assert.assertEquals(numbers, fieldWrapper.getObject()); }
@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 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 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); }
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); }
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 testSetObjectEmptyValue() { Mockito.when(request.getParameterList(OBJECT)).thenReturn(Arrays.asList("")); fieldConverter.setObject(fieldWrapper, request); Assert.assertEquals(EMPTY_LIST, fieldWrapper.getObject()); }
@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 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 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); }
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); }
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(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); }
@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 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 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); }
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); }
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 testSetObjectNull() { Mockito.when(request.getParameterList(OBJECT)).thenReturn(null); fieldConverter.setObject(fieldWrapper, request); Assert.assertEquals(EMPTY_LIST, fieldWrapper.getObject()); }
@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 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 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); }
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); }
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 testSetString() throws Exception { beanWrapper.setPropertyValue(OBJECT, numbers); fieldConverter.setString(fieldWrapper); Assert.assertEquals("1,2,3", fieldWrapper.getStringValue()); }
@Override public void setString(FieldWrapper field) { if (!FieldType.LIST_OBJECT.equals(field.getType())) { super.setString(field); } }
ListFieldConverter extends ConverterBase { @Override public void setString(FieldWrapper field) { if (!FieldType.LIST_OBJECT.equals(field.getType())) { super.setString(field); } } }
ListFieldConverter extends ConverterBase { @Override public void setString(FieldWrapper field) { if (!FieldType.LIST_OBJECT.equals(field.getType())) { super.setString(field); } } ListFieldConverter(ConversionService conversionService); }
ListFieldConverter extends ConverterBase { @Override public void setString(FieldWrapper field) { if (!FieldType.LIST_OBJECT.equals(field.getType())) { super.setString(field); } } ListFieldConverter(ConversionService conversionService); @Override void setString(FieldWrapper field); @Override void setObject(FieldWrapper field, RequestContainer request); @Override Datafield addField(DatafieldOwner dataFieldOwner, FieldWrapper fieldWrapper); }
ListFieldConverter extends ConverterBase { @Override public void setString(FieldWrapper field) { if (!FieldType.LIST_OBJECT.equals(field.getType())) { super.setString(field); } } 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 testSetStringNullObject() { beanWrapper.setPropertyValue(OBJECT, null); fieldConverter.setString(fieldWrapper); Assert.assertNull(fieldWrapper.getStringValue()); }
@Override public void setString(FieldWrapper field) { if (!FieldType.LIST_OBJECT.equals(field.getType())) { super.setString(field); } }
ListFieldConverter extends ConverterBase { @Override public void setString(FieldWrapper field) { if (!FieldType.LIST_OBJECT.equals(field.getType())) { super.setString(field); } } }
ListFieldConverter extends ConverterBase { @Override public void setString(FieldWrapper field) { if (!FieldType.LIST_OBJECT.equals(field.getType())) { super.setString(field); } } ListFieldConverter(ConversionService conversionService); }
ListFieldConverter extends ConverterBase { @Override public void setString(FieldWrapper field) { if (!FieldType.LIST_OBJECT.equals(field.getType())) { super.setString(field); } } ListFieldConverter(ConversionService conversionService); @Override void setString(FieldWrapper field); @Override void setObject(FieldWrapper field, RequestContainer request); @Override Datafield addField(DatafieldOwner dataFieldOwner, FieldWrapper fieldWrapper); }
ListFieldConverter extends ConverterBase { @Override public void setString(FieldWrapper field) { if (!FieldType.LIST_OBJECT.equals(field.getType())) { super.setString(field); } } 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 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); }
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; }
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; } }
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; } }
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); }
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 of_notNull() throws Exception { AnnualPercentageYield ci = AnnualPercentageYield.of( Rate.of(0.05),1 ); assertNotNull(ci); }
public static AnnualPercentageYield of(Rate rate, int periods){ return new AnnualPercentageYield(rate, periods); }
AnnualPercentageYield implements MonetaryOperator { public static AnnualPercentageYield of(Rate rate, int periods){ return new AnnualPercentageYield(rate, periods); } }
AnnualPercentageYield implements MonetaryOperator { public static AnnualPercentageYield of(Rate rate, int periods){ return new AnnualPercentageYield(rate, periods); } private AnnualPercentageYield(Rate rate, int periods); }
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(); }
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 getPeriods() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.03,3654) ); assertEquals(val.getPeriods(), 3654); }
public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); }
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(); }
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 of_Period1() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.05, 1) ); assertNotNull(val); }
public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); }
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(); }
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 of_Period0() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( RateAndPeriods.of(0.08,0) ); assertNotNull(val); }
public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); }
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(); }
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 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)); }
public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); }
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(); }
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 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); }
public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); }
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(); }
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 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); }
public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static PresentValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new PresentValueOfAnnuity(rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); }
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(); }
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 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)); }
@Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); }
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(); }
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 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()); }
@Override public String toString() { return "PresentValueOfAnnuity{" + "\n " + rateAndPeriods + '}'; }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValueOfAnnuity{" + "\n " + rateAndPeriods + '}'; } }
PresentValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValueOfAnnuity{" + "\n " + rateAndPeriods + '}'; } private PresentValueOfAnnuity(RateAndPeriods rateAndPeriods); }
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(); }
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 getDiscountRate() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.01),Rate.of(0.03),1 ); assertEquals(val.getDiscountRate(), Rate.of(0.01)); }
public Rate getDiscountRate() { return discountRate; }
FutureValueGrowingAnnuity implements MonetaryOperator { public Rate getDiscountRate() { return discountRate; } }
FutureValueGrowingAnnuity implements MonetaryOperator { public Rate getDiscountRate() { return discountRate; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); }
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(); }
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 getGrowthRate() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.01),Rate.of(0.03),1 ); assertEquals(val.getGrowthRate(), Rate.of(0.03)); }
public Rate getGrowthRate() { return growthRate; }
FutureValueGrowingAnnuity implements MonetaryOperator { public Rate getGrowthRate() { return growthRate; } }
FutureValueGrowingAnnuity implements MonetaryOperator { public Rate getGrowthRate() { return growthRate; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); }
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(); }
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 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")); }
@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); }
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); } }
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); }
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); }
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 getPeriods() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.01),Rate.of(0.03),3654 ); assertEquals(val.getPeriods(), 3654); }
public int getPeriods() { return periods; }
FutureValueGrowingAnnuity implements MonetaryOperator { public int getPeriods() { return periods; } }
FutureValueGrowingAnnuity implements MonetaryOperator { public int getPeriods() { return periods; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); }
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(); }
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 of_Period1() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.07), Rate.of(0.05), 1 ); assertNotNull(val); }
public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); }
FutureValueGrowingAnnuity implements MonetaryOperator { public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); } }
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); }
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(); }
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_Period0() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.07),Rate.of(0.08),0 ); assertNotNull(val); }
public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); }
FutureValueGrowingAnnuity implements MonetaryOperator { public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); } }
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); }
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(); }
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 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)); }
public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); }
FutureValueGrowingAnnuity implements MonetaryOperator { public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); } }
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); }
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(); }
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(expected = MonetaryException.class) public void of_InvalidWithEqualRates() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.05), Rate.of(0.05), 0 ); }
public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); }
FutureValueGrowingAnnuity implements MonetaryOperator { public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); } }
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); }
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(); }
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 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)); }
public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); }
FutureValueGrowingAnnuity implements MonetaryOperator { public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); } }
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); }
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(); }
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 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); }
public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); }
FutureValueGrowingAnnuity implements MonetaryOperator { public static FutureValueGrowingAnnuity of(Rate discountRate, Rate growthRate, int periods) { return new FutureValueGrowingAnnuity(discountRate, growthRate, periods); } }
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); }
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(); }
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 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)); }
@Override public MonetaryAmount apply(MonetaryAmount firstPayment) { return calculate(firstPayment, discountRate, growthRate, periods); }
FutureValueGrowingAnnuity implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount firstPayment) { return calculate(firstPayment, discountRate, growthRate, periods); } }
FutureValueGrowingAnnuity implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount firstPayment) { return calculate(firstPayment, discountRate, growthRate, periods); } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); }
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(); }
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 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()); }
@Override public String toString() { return "FutureValueGrowingAnnuity{" + "discountRate=" + discountRate + ", growthRate=" + growthRate + ", periods=" + periods + '}'; }
FutureValueGrowingAnnuity implements MonetaryOperator { @Override public String toString() { return "FutureValueGrowingAnnuity{" + "discountRate=" + discountRate + ", growthRate=" + growthRate + ", periods=" + periods + '}'; } }
FutureValueGrowingAnnuity implements MonetaryOperator { @Override public String toString() { return "FutureValueGrowingAnnuity{" + "discountRate=" + discountRate + ", growthRate=" + growthRate + ", periods=" + periods + '}'; } private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods); }
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(); }
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 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)); }
public static PresentValue of(RateAndPeriods rateAndPeriods) { return new PresentValue(rateAndPeriods); }
PresentValue extends AbstractRateAndPeriodBasedOperator { public static PresentValue of(RateAndPeriods rateAndPeriods) { return new PresentValue(rateAndPeriods); } }
PresentValue extends AbstractRateAndPeriodBasedOperator { public static PresentValue of(RateAndPeriods rateAndPeriods) { return new PresentValue(rateAndPeriods); } private PresentValue(RateAndPeriods rateAndPeriods); }
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(); }
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 of_notNull() throws Exception { ContinuousCompoundInterest ci = ContinuousCompoundInterest.of( RateAndPeriods.of(0.05,1) ); assertNotNull(ci); }
public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); }
ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); } }
ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); } private ContinuousCompoundInterest(RateAndPeriods rateAndPeriods); }
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(); }
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 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)); }
public static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods){ Objects.requireNonNull(amount, "Amount required"); Objects.requireNonNull(rateAndPeriods, "RateAndPeriods required"); return amount.divide(PresentValueFactor.calculate(rateAndPeriods)); }
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)); } }
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); }
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(); }
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 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()); }
@Override public String toString() { return "PresentValue{" + "\n " + rateAndPeriods + '}'; }
PresentValue extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValue{" + "\n " + rateAndPeriods + '}'; } }
PresentValue extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValue{" + "\n " + rateAndPeriods + '}'; } private PresentValue(RateAndPeriods rateAndPeriods); }
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(); }
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 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))); }
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()); }
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()); } }
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(); }
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); }
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_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))); }
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()); }
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()); } }
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(); }
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); }
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_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))); }
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()); }
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()); } }
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(); }
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); }
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 testCalculate() { assertEquals(BigDecimal.valueOf(0.5), PriceToBookValue.calculate(MARKET_PRICE_PER_SHARE, BOOK_VALUE_PER_SHARE)); }
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); }
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); } }
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(); }
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); }
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.8), DividendPayoutRatio.calculate(DIVIDENDS, NET_INCOME)); }
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); }
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); } }
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(); }
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); }
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(0.0871, GeometricMeanReturn.calculate(RATES_OF_RETURN), 0.0001); }
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; }
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; } }
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(); }
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); }
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(expected = IllegalArgumentException.class) public void testCalculateWithNullRatesThrowsException() { GeometricMeanReturn.calculate(Arrays.asList(Rate.of(0.1), Rate.of(0.1), null, Rate.of(0.5))); }
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; }
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; } }
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(); }
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); }
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(Money.of(9, "GBP"), NetAssetValue.calculate(ASSETS, FUND_LIABILITIES, OUTSTANDING_SHARES)); }
public static MonetaryAmount calculate(MonetaryAmount fundAssets, MonetaryAmount fundLiabilities, double outstandingShares) { return fundAssets.subtract(fundLiabilities).divide(outstandingShares); }
NetAssetValue { public static MonetaryAmount calculate(MonetaryAmount fundAssets, MonetaryAmount fundLiabilities, double outstandingShares) { return fundAssets.subtract(fundLiabilities).divide(outstandingShares); } }
NetAssetValue { public static MonetaryAmount calculate(MonetaryAmount fundAssets, MonetaryAmount fundLiabilities, double outstandingShares) { return fundAssets.subtract(fundLiabilities).divide(outstandingShares); } private NetAssetValue(); }
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); }
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 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)); }
public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); }
ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); } }
ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); } private ContinuousCompoundInterest(RateAndPeriods rateAndPeriods); }
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(); }
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 testCalculate() { assertEquals(0.81301, CapitalGainsYield.calculate(INITIAL_STOCK_PRICE, STOCK_PRICE_AFTER_FIRST_PERIOD).doubleValue(), 0.00001); }
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); }
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); } }
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(); }
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); }
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.1111, CurrentYield.calculate(ANNUAL_COUPONS, CURRENT_BOND_PRICE).doubleValue(), 0.0001); }
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); }
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); } }
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(); }
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); }
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(Money.of(11, "GBP"), DilutedEarningsPerShare.calculate(NET_INCOME, AVERAGE_SHARES, OTHER_CONVERTIBLE_INSTRUMENTS)); }
public static MonetaryAmount calculate(MonetaryAmount netIncome, BigDecimal averageShares, BigDecimal otherConvertibleInstruments) { return netIncome.divide(averageShares.add(otherConvertibleInstruments)); }
DilutedEarningsPerShare { public static MonetaryAmount calculate(MonetaryAmount netIncome, BigDecimal averageShares, BigDecimal otherConvertibleInstruments) { return netIncome.divide(averageShares.add(otherConvertibleInstruments)); } }
DilutedEarningsPerShare { public static MonetaryAmount calculate(MonetaryAmount netIncome, BigDecimal averageShares, BigDecimal otherConvertibleInstruments) { return netIncome.divide(averageShares.add(otherConvertibleInstruments)); } private DilutedEarningsPerShare(); }
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); }
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(0.04, DividendYield.calculate(DIVIDENDS, INITIAL_PRICE).doubleValue()); }
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); }
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); } }
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(); }
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); }
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(BigDecimal.valueOf(0.2), PriceToSalesRatio.calculate(SHARE_PRICE, SALES_PER_SHARE)); }
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); }
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); } }
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(); }
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); }
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(Money.of(10, "GBP"), BookValuePerShare.calculate(EQUITY, NUMBER_OF_COMMON_SHARES)); }
public static MonetaryAmount calculate(MonetaryAmount equity, int numberOfCommonShares) { return equity.divide(numberOfCommonShares); }
BookValuePerShare { public static MonetaryAmount calculate(MonetaryAmount equity, int numberOfCommonShares) { return equity.divide(numberOfCommonShares); } }
BookValuePerShare { public static MonetaryAmount calculate(MonetaryAmount equity, int numberOfCommonShares) { return equity.divide(numberOfCommonShares); } private BookValuePerShare(); }
BookValuePerShare { public static MonetaryAmount calculate(MonetaryAmount equity, int numberOfCommonShares) { return equity.divide(numberOfCommonShares); } private BookValuePerShare(); static MonetaryAmount calculate(MonetaryAmount equity, int numberOfCommonShares); }
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(BigDecimal.valueOf(0.04), RiskPremium.calculate(ASSET_RETURN, RISK_FREE_RETURN)); }
public static BigDecimal calculate(Rate assetReturn, Rate riskFreeReturn) { return assetReturn.get().subtract(riskFreeReturn.get()); }
RiskPremium { public static BigDecimal calculate(Rate assetReturn, Rate riskFreeReturn) { return assetReturn.get().subtract(riskFreeReturn.get()); } }
RiskPremium { public static BigDecimal calculate(Rate assetReturn, Rate riskFreeReturn) { return assetReturn.get().subtract(riskFreeReturn.get()); } private RiskPremium(); }
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); }
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 testCalculateWithCAPM() { assertEquals(BigDecimal.valueOf(0.025), RiskPremium.calculateWithCAPM(BETA, MARKET_RETURN, RISK_FREE_RETURN)); }
public static BigDecimal calculateWithCAPM(BigDecimal beta, Rate marketReturn, Rate riskFreeReturn) { return beta.multiply(marketReturn.get().subtract(riskFreeReturn.get())); }
RiskPremium { public static BigDecimal calculateWithCAPM(BigDecimal beta, Rate marketReturn, Rate riskFreeReturn) { return beta.multiply(marketReturn.get().subtract(riskFreeReturn.get())); } }
RiskPremium { public static BigDecimal calculateWithCAPM(BigDecimal beta, Rate marketReturn, Rate riskFreeReturn) { return beta.multiply(marketReturn.get().subtract(riskFreeReturn.get())); } private RiskPremium(); }
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); }
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 testCalculate() { assertEquals(Money.of(0.05, "GBP"), BidAskSpread.calculate(ASK_PRICE, BID_PRICE)); }
public static MonetaryAmount calculate(MonetaryAmount askPrice, MonetaryAmount bidPrice) { return askPrice.subtract(bidPrice); }
BidAskSpread { public static MonetaryAmount calculate(MonetaryAmount askPrice, MonetaryAmount bidPrice) { return askPrice.subtract(bidPrice); } }
BidAskSpread { public static MonetaryAmount calculate(MonetaryAmount askPrice, MonetaryAmount bidPrice) { return askPrice.subtract(bidPrice); } private BidAskSpread(); }
BidAskSpread { public static MonetaryAmount calculate(MonetaryAmount askPrice, MonetaryAmount bidPrice) { return askPrice.subtract(bidPrice); } private BidAskSpread(); static MonetaryAmount calculate(MonetaryAmount askPrice, MonetaryAmount bidPrice); }
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(4, "GBP"), EarningsPerShare.calculate(NET_INCOME, WEIGHTED_AVERAGE_OF_OUTSTANDING_SHARES)); }
public static MonetaryAmount calculate(MonetaryAmount netIncome, double weightedAverageOfOutstandingShares) { return netIncome.divide(weightedAverageOfOutstandingShares); }
EarningsPerShare { public static MonetaryAmount calculate(MonetaryAmount netIncome, double weightedAverageOfOutstandingShares) { return netIncome.divide(weightedAverageOfOutstandingShares); } }
EarningsPerShare { public static MonetaryAmount calculate(MonetaryAmount netIncome, double weightedAverageOfOutstandingShares) { return netIncome.divide(weightedAverageOfOutstandingShares); } private EarningsPerShare(); }
EarningsPerShare { public static MonetaryAmount calculate(MonetaryAmount netIncome, double weightedAverageOfOutstandingShares) { return netIncome.divide(weightedAverageOfOutstandingShares); } private EarningsPerShare(); static MonetaryAmount calculate(MonetaryAmount netIncome, double weightedAverageOfOutstandingShares); }
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 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); }
public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); }
ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); } }
ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); } private ContinuousCompoundInterest(RateAndPeriods rateAndPeriods); }
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(); }
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 testCalculate() { assertEquals(Money.of(25, "GBP"), DividendsPerShare.calculate(DIVIDENDS, NUMBER_OF_SHARES)); }
public static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares) { return dividends.divide(numberOfShares); }
DividendsPerShare { public static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares) { return dividends.divide(numberOfShares); } }
DividendsPerShare { public static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares) { return dividends.divide(numberOfShares); } private DividendsPerShare(); }
DividendsPerShare { public static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares) { return dividends.divide(numberOfShares); } private DividendsPerShare(); static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares); }
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(BigDecimal.valueOf(0.25), PriceToEarningsRatio.calculate(PRICE_PER_SHARE, EARNINGS_PER_SHARE)); }
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); }
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); } }
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(); }
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); }
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 testCalculateForConstantGrowth() { assertEquals(Money.of(1700, "GBP"), StockPresentValue.calculateForConstantGrowth(ESTIMATED_DIVIDENDS, REQUIRED_RATE_OF_RETURN, GROWTH_RATE)); }
public static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate) { return estimatedDividends.divide(requiredRateOfReturn.get().subtract(growthRate.get())); }
StockPresentValue implements MonetaryOperator { public static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate) { return estimatedDividends.divide(requiredRateOfReturn.get().subtract(growthRate.get())); } }
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); }
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(); }
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 testCalculateForZeroGrowth() { assertEquals(Money.of(680, "GBP"), StockPresentValue.calculateForZeroGrowth(ESTIMATED_DIVIDENDS, REQUIRED_RATE_OF_RETURN)); }
public static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, Rate.ZERO); }
StockPresentValue implements MonetaryOperator { public static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, Rate.ZERO); } }
StockPresentValue implements MonetaryOperator { public static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, Rate.ZERO); } private StockPresentValue(Rate requiredRateOfReturn, Rate growthRate); }
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(); }
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 testApply() { assertEquals(Money.of(1700, "GBP"), ESTIMATED_DIVIDENDS.with(StockPresentValue.of(REQUIRED_RATE_OF_RETURN, GROWTH_RATE))); }
@Override public MonetaryAmount apply(MonetaryAmount estimatedDividends) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, growthRate); }
StockPresentValue implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount estimatedDividends) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, growthRate); } }
StockPresentValue implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount estimatedDividends) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, growthRate); } private StockPresentValue(Rate requiredRateOfReturn, Rate growthRate); }
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(); }
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 testCalculate() { assertEquals(0.0597, TaxEquivalentYield.calculate(TAX_FREE_YIELD, TAX_RATE).doubleValue(), 0.0001); }
public static BigDecimal calculate(Rate taxFreeYield, Rate taxRate) { return taxFreeYield.get().divide(BigDecimal.ONE.subtract(taxRate.get()), MathContext.DECIMAL64); }
TaxEquivalentYield { public static BigDecimal calculate(Rate taxFreeYield, Rate taxRate) { return taxFreeYield.get().divide(BigDecimal.ONE.subtract(taxRate.get()), MathContext.DECIMAL64); } }
TaxEquivalentYield { public static BigDecimal calculate(Rate taxFreeYield, Rate taxRate) { return taxFreeYield.get().divide(BigDecimal.ONE.subtract(taxRate.get()), MathContext.DECIMAL64); } private TaxEquivalentYield(); }
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); }
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.1319, HoldingPeriodReturn.calculate(RATES_OF_RETURN).doubleValue(), 0.00001); }
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); }
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); } }
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(); }
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); }
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(expected = IllegalArgumentException.class) public void testCalculateWithNullReturnsThrowsException() { HoldingPeriodReturn.calculate(Arrays.asList(Rate.of(0.1), Rate.of(0.1), null, Rate.of(0.5))); }
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); }
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); } }
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(); }
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); }
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 testCalculateForSameReturn() { assertEquals(0.728, HoldingPeriodReturn.calculateForSameReturn(PERIODIC_RATE, NUMBER_OF_PERIODS).doubleValue(), 0.0001); }
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); }
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); } }
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(); }
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); }
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(expected = IllegalArgumentException.class) public void testCalculateForSameReturnWithNullRateThrowsException() { HoldingPeriodReturn.calculateForSameReturn(null, NUMBER_OF_PERIODS); }
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); }
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); } }
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(); }
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); }
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 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")); }
public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); }
ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); } }
ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { public static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods) { return new ContinuousCompoundInterest(rateAndPeriods); } private ContinuousCompoundInterest(RateAndPeriods rateAndPeriods); }
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(); }
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(expected = IllegalArgumentException.class) public void testCalculateForSameReturnWithNegativeNumberOfPeriodsThrowsException() { HoldingPeriodReturn.calculateForSameReturn(PERIODIC_RATE, -1); }
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); }
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); } }
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(); }
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); }
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 testCalculate() { assertEquals(0.2974, ZeroCouponBondYield.calculate(FACE_AMOUNT, PRESENT_AMOUNT, NUMBER_OF_PERIODS), 0.0001); }
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; }
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; } }
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(); }
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); }
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.40556, BondEquivalentYield.calculate(FACE_AMOUNT, PRICE_AMOUNT, NUMBER_OF_DAYS_TO_MATURITY).doubleValue(), 0.00001); }
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); }
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); } }
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(); }
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); }
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(BigDecimal.valueOf(0.04), TotalStockReturn.calculate(INITIAL_PRICE, ENDING_PRICE, DIVIDENDS)); }
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); }
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); } }
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(); }
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); }
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); }