List of usage examples for java.lang Number toString
public String toString()
From source file:org.springframework.data.solr.core.DefaultQueryParserTests.java
@Test public void testRegisterAlternateConverter() { Criteria criteria = new Criteria("field_1").is(100); queryParser.registerConverter(new Converter<Number, String>() { @Override// www .j av a 2 s. co m public String convert(Number arg0) { return StringUtils.reverse(arg0.toString()); } }); Assert.assertEquals("field_1:001", queryParser.createQueryStringFromCriteria(criteria)); }
From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java
private byte[] generateLineChart(String siteId, CategoryDataset dataset, int width, int height, boolean render3d, float transparency, boolean itemLabelsVisible, boolean smallFontInDomainAxis) { JFreeChart chart = null;/* w ww. ja v a 2s. c o m*/ if (render3d) chart = ChartFactory.createLineChart3D(null, null, null, dataset, PlotOrientation.VERTICAL, true, false, false); else chart = ChartFactory.createLineChart(null, null, null, dataset, PlotOrientation.VERTICAL, true, false, false); CategoryPlot plot = (CategoryPlot) chart.getPlot(); // set transparency plot.setForegroundAlpha(transparency); // set background chart.setBackgroundPaint(parseColor(M_sm.getChartBackgroundColor())); // set chart border chart.setPadding(new RectangleInsets(10, 5, 5, 5)); chart.setBorderVisible(true); chart.setBorderPaint(parseColor("#cccccc")); // set antialias chart.setAntiAlias(true); // set domain axis font size if (smallFontInDomainAxis && !canUseNormalFontSize(width)) { plot.getDomainAxis().setTickLabelFont(new Font("SansSerif", Font.PLAIN, 8)); plot.getDomainAxis().setCategoryMargin(0.05); } // set outline LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer(); renderer.setDrawOutlines(true); // item labels if (itemLabelsVisible) { plot.getRangeAxis().setUpperMargin(0.2); renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator() { private static final long serialVersionUID = 1L; @Override public String generateLabel(CategoryDataset dataset, int row, int column) { Number n = dataset.getValue(row, column); if (n.intValue() != 0) //return n.intValue()+""; return n.toString(); return ""; } }); renderer.setItemLabelFont(new Font("SansSerif", Font.PLAIN, 8)); renderer.setItemLabelsVisible(true); } BufferedImage img = chart.createBufferedImage(width, height); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ImageIO.write(img, "png", out); } catch (IOException e) { LOG.warn("Error occurred while generating SiteStats chart image data", e); } return out.toByteArray(); }
From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java
private byte[] generateTimeSeriesChart(String siteId, IntervalXYDataset dataset, int width, int height, boolean renderBar, float transparency, boolean itemLabelsVisible, boolean smallFontInDomainAxis, String timePeriod, Date firstDate, Date lastDate) { JFreeChart chart = null;//w w w. j av a2 s .c om if (!renderBar) { chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, true, false, false); } else { chart = ChartFactory.createXYBarChart(null, null, true, null, dataset, PlotOrientation.VERTICAL, true, false, false); } XYPlot plot = (XYPlot) chart.getPlot(); // set transparency plot.setForegroundAlpha(transparency); // set background chart.setBackgroundPaint(parseColor(M_sm.getChartBackgroundColor())); // set chart border chart.setPadding(new RectangleInsets(10, 5, 5, 5)); chart.setBorderVisible(true); chart.setBorderPaint(parseColor("#cccccc")); // set antialias chart.setAntiAlias(true); // set domain axis font size if (smallFontInDomainAxis && !canUseNormalFontSize(width)) { plot.getDomainAxis().setTickLabelFont(new Font("SansSerif", Font.PLAIN, 8)); } // configure date display (localized) in domain axis Locale locale = msgs.getLocale(); PeriodAxis periodaxis = new PeriodAxis(null); Class timePeriodClass = null; if (dataset instanceof TimeSeriesCollection) { TimeSeriesCollection tsc = (TimeSeriesCollection) dataset; if (tsc.getSeriesCount() > 0) { timePeriodClass = tsc.getSeries(0).getTimePeriodClass(); } else { timePeriodClass = org.jfree.data.time.Day.class; } periodaxis.setAutoRangeTimePeriodClass(timePeriodClass); } PeriodAxisLabelInfo aperiodaxislabelinfo[] = null; if (StatsManager.CHARTTIMESERIES_WEEKDAY.equals(timePeriod)) { aperiodaxislabelinfo = new PeriodAxisLabelInfo[2]; aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Day.class, new SimpleDateFormat("E", locale)); aperiodaxislabelinfo[1] = new PeriodAxisLabelInfo(org.jfree.data.time.Day.class, new SimpleDateFormat("d", locale)); } else if (StatsManager.CHARTTIMESERIES_DAY.equals(timePeriod)) { aperiodaxislabelinfo = new PeriodAxisLabelInfo[3]; aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Day.class, new SimpleDateFormat("d", locale)); aperiodaxislabelinfo[1] = new PeriodAxisLabelInfo(org.jfree.data.time.Month.class, new SimpleDateFormat("MMM", locale)); aperiodaxislabelinfo[2] = new PeriodAxisLabelInfo(org.jfree.data.time.Year.class, new SimpleDateFormat("yyyy", locale)); } else if (StatsManager.CHARTTIMESERIES_MONTH.equals(timePeriod)) { aperiodaxislabelinfo = new PeriodAxisLabelInfo[2]; aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Month.class, new SimpleDateFormat("MMM", locale)); aperiodaxislabelinfo[1] = new PeriodAxisLabelInfo(org.jfree.data.time.Year.class, new SimpleDateFormat("yyyy", locale)); } else if (StatsManager.CHARTTIMESERIES_YEAR.equals(timePeriod)) { aperiodaxislabelinfo = new PeriodAxisLabelInfo[1]; aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Year.class, new SimpleDateFormat("yyyy", locale)); } periodaxis.setLabelInfo(aperiodaxislabelinfo); // date range if (firstDate != null || lastDate != null) { periodaxis.setAutoRange(false); if (firstDate != null) { if (StatsManager.CHARTTIMESERIES_MONTH.equals(timePeriod) || StatsManager.CHARTTIMESERIES_YEAR.equals(timePeriod)) { periodaxis.setFirst(new org.jfree.data.time.Month(firstDate)); } else { periodaxis.setFirst(new org.jfree.data.time.Day(firstDate)); } } if (lastDate != null) { if (StatsManager.CHARTTIMESERIES_MONTH.equals(timePeriod) || StatsManager.CHARTTIMESERIES_YEAR.equals(timePeriod)) { periodaxis.setLast(new org.jfree.data.time.Month(lastDate)); } else { periodaxis.setLast(new org.jfree.data.time.Day(lastDate)); } } } periodaxis.setTickMarkOutsideLength(0.0F); plot.setDomainAxis(periodaxis); // set outline AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) plot.getRenderer(); if (renderer instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) renderer; r.setDrawSeriesLineAsPath(true); r.setShapesVisible(true); r.setShapesFilled(true); } else if (renderer instanceof XYBarRenderer) { //XYBarRenderer r = (XYBarRenderer) renderer; ClusteredXYBarRenderer r = new ClusteredXYBarRenderer(); r.setDrawBarOutline(true); if (smallFontInDomainAxis && !canUseNormalFontSize(width)) r.setMargin(0.05); else r.setMargin(0.10); plot.setRenderer(r); renderer = r; } // item labels if (itemLabelsVisible) { plot.getRangeAxis().setUpperMargin(0.2); renderer.setItemLabelGenerator(new XYItemLabelGenerator() { private static final long serialVersionUID = 1L; public String generateLabel(XYDataset dataset, int series, int item) { Number n = dataset.getY(series, item); if (n.doubleValue() != 0) return n.toString(); return ""; } }); renderer.setItemLabelFont(new Font("SansSerif", Font.PLAIN, 8)); renderer.setItemLabelsVisible(true); } BufferedImage img = chart.createBufferedImage(width, height); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ImageIO.write(img, "png", out); } catch (IOException e) { LOG.warn("Error occurred while generating SiteStats chart image data", e); } return out.toByteArray(); }
From source file:org.compiere.mobile.WWindow.java
/** * Get Field value (convert value to datatype of MField) * @param wsc session context//from w w w . j a v a 2 s . c o m * @param mField field * @param value String Value * @return converted Field Value */ private Object getFieldValue(MobileSessionCtx wsc, GridField mField, String value) { //Modified by Rob Klein 4/29/07 //if (value == null || value.length() == 0) //return null; Object defaultObject = null; int dt = mField.getDisplayType(); String columnName = mField.getColumnName(); if (value == null || value.length() == 0) { defaultObject = mField.getDefault(); mField.setValue(defaultObject, true); if (value == null || value.length() == 0 || mField.getValue() == null) { return null; } else value = mField.getValue().toString(); } // BigDecimal if (DisplayType.isNumeric(dt)) { BigDecimal bd = null; try { Number nn = null; if (dt == DisplayType.Amount) nn = wsc.amountFormat.parse(value); else if (dt == DisplayType.Quantity) nn = wsc.quantityFormat.parse(value); else // DisplayType.CostPrice nn = wsc.numberFormat.parse(value); if (nn instanceof BigDecimal) bd = (BigDecimal) nn; else bd = new BigDecimal(nn.toString()); } catch (Exception e) { log.warning("BigDecimal: " + columnName + "=" + value + ERROR); return ERROR; } log.fine("BigDecimal: " + columnName + "=" + value + " -> " + bd); return bd; } // ID else if (DisplayType.isID(dt)) { Integer ii = null; try { ii = new Integer(value); } catch (Exception e) { log.log(Level.WARNING, "ID: " + columnName + "=" + value, e); ii = null; } // -1 indicates NULL if (ii != null && ii.intValue() == -1) ii = null; log.fine("ID: " + columnName + "=" + value + " -> " + ii); return ii; } // Date/Time else if (DisplayType.isDate(dt)) { Timestamp ts = null; try { java.util.Date d = null; if (dt == DisplayType.Date) d = wsc.dateFormat.parse(value); else d = wsc.dateTimeFormat.parse(value); ts = new Timestamp(d.getTime()); } catch (Exception e) { log.warning("Date: " + columnName + "=" + value + ERROR); return ERROR; } log.fine("Date: " + columnName + "=" + value + " -> " + ts); return ts; } // Checkbox else if (dt == DisplayType.YesNo) { Boolean retValue = Boolean.FALSE; if (value.equals("true")) retValue = Boolean.TRUE; log.fine("YesNo: " + columnName + "=" + value + " -> " + retValue); return retValue; } // treat as string log.fine(columnName + "=" + value); return value; }
From source file:org.richfaces.renderkit.AbstractProgressBarRenderer.java
/** * Encode initial javascript/*from w w w . j ava2s .co m*/ * * @param context * @param component * @throws IOException */ public void encodeInitialScript(FacesContext context, UIComponent component, String state) throws IOException { ResponseWriter writer = context.getResponseWriter(); UIProgressBar progressBar = (UIProgressBar) component; ComponentVariables variables = ComponentsVariableResolver.getVariables(this, component); StringBuffer script = new StringBuffer(); String clientId = component.getClientId(context); String containerId = ((UIComponent) AjaxRendererUtils.findAjaxContainer(context, component)) .getClientId(context); String mode = (String) component.getAttributes().get("mode"); UIComponent form = AjaxRendererUtils.getNestingForm(component); String formId = ""; if (form != null) { formId = form.getClientId(context); } else if ("ajax".equals(mode)) { // Ignore form absent. It can be rendered by forcing from any // component // throw new FaceletException("Progress bar component in ajax mode // should be placed inside the form"); } Number minValue = getNumber(component.getAttributes().get("minValue")); Number maxValue = getNumber(component.getAttributes().get("maxValue")); Number value = (Number) variables.getVariable("value"); StringBuffer markup = getMarkup(context, component); script.append("new ProgressBar('").append(clientId).append("','") // id .append(containerId).append("','") // containerId .append(formId).append("','") // formId .append(mode).append("',") // mode .append(minValue).append(",") // min value .append(maxValue).append(","); // max value script.append(getContext(component)); // context script.append(","); script.append(markup != null ? new JSLiteral(markup.toString()) : JSReference.NULL); // markup script.append(","); script.append(ScriptUtils.toScript(buildAjaxOptions(clientId, // options progressBar, context))); String progressVar = (String) component.getAttributes().get("progressVar"); if (progressVar != null) { script.append(",'"); script.append(progressVar); // progress var script.append("','"); } else { script.append(",null,'"); } script.append(state); script.append("',"); script.append(value.toString()); script.append(")\n;"); writer.write(script.toString()); }
From source file:org.crazydog.util.spring.NumberUtils.java
/** * Convert the given number into an instance of the given target class. * * @param number the number to convert * @param targetClass the target class to convert to * @return the converted number/*w w w .j a v a2s .c om*/ * @throws IllegalArgumentException if the target class is not supported * (i.e. not a standard Number subclass as included in the JDK) * @see Byte * @see Short * @see Integer * @see Long * @see BigInteger * @see Float * @see Double * @see BigDecimal */ @SuppressWarnings("unchecked") public static <T extends Number> T convertNumberToTargetClass(Number number, Class<T> targetClass) throws IllegalArgumentException { org.springframework.util.Assert.notNull(number, "Number must not be null"); org.springframework.util.Assert.notNull(targetClass, "Target class must not be null"); if (targetClass.isInstance(number)) { return (T) number; } else if (Byte.class == targetClass) { long value = number.longValue(); if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { raiseOverflowException(number, targetClass); } return (T) new Byte(number.byteValue()); } else if (Short.class == targetClass) { long value = number.longValue(); if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) { raiseOverflowException(number, targetClass); } return (T) new Short(number.shortValue()); } else if (Integer.class == targetClass) { long value = number.longValue(); if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { raiseOverflowException(number, targetClass); } return (T) new Integer(number.intValue()); } else if (Long.class == targetClass) { BigInteger bigInt = null; if (number instanceof BigInteger) { bigInt = (BigInteger) number; } else if (number instanceof BigDecimal) { bigInt = ((BigDecimal) number).toBigInteger(); } // Effectively analogous to JDK 8's BigInteger.longValueExact() if (bigInt != null && (bigInt.compareTo(LONG_MIN) < 0 || bigInt.compareTo(LONG_MAX) > 0)) { raiseOverflowException(number, targetClass); } return (T) new Long(number.longValue()); } else if (BigInteger.class == targetClass) { if (number instanceof BigDecimal) { // do not lose precision - use BigDecimal's own conversion return (T) ((BigDecimal) number).toBigInteger(); } else { // original value is not a Big* number - use standard long conversion return (T) BigInteger.valueOf(number.longValue()); } } else if (Float.class == targetClass) { return (T) new Float(number.floatValue()); } else if (Double.class == targetClass) { return (T) new Double(number.doubleValue()); } else if (BigDecimal.class == targetClass) { // always use BigDecimal(String) here to avoid unpredictability of BigDecimal(double) // (see BigDecimal javadoc for details) return (T) new BigDecimal(number.toString()); } else { throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" + number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]"); } }
From source file:org.mifos.clientportfolio.loan.ui.LoanAccountFormBean.java
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { "SIC_INNER_SHOULD_BE_STATIC_ANON" }, justification = "") public void validateEnterAccountDetailsStep(ValidationContext context) { MessageContext messageContext = context.getMessageContext(); Errors errors = validator.checkConstraints(this); // handle data binding errors that may of occurred if (messageContext.hasErrorMessages()) { Message[] errorMessages = messageContext.getMessagesByCriteria(new MessageCriteria() { @Override/*from ww w. j a v a 2s.c om*/ public boolean test(@SuppressWarnings("unused") Message message) { return true; } }); messageContext.clearMessages(); for (Message message : errorMessages) { handleDataMappingError(errors, message); } } if (this.glimApplicable) { int index = 0; int selectedCount = 0; for (Boolean clientSelected : this.clientSelectForGroup) { if (clientSelected != null && clientSelected.booleanValue()) { Number clientAmount = this.clientAmount[index]; if (clientAmount == null || exceedsMinOrMax(clientAmount, Integer.valueOf(1), this.maxAllowedAmount)) { String defaultErrorMessage = "Please specify valid Amount."; rejectGlimClientAmountField(index + 1, errors, defaultErrorMessage); } if (clientAmount != null) { BigDecimal amountAsDecimal = new BigDecimal(clientAmount.toString()).stripTrailingZeros(); int places = amountAsDecimal.scale(); if (places > this.digitsAfterDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsAfterDecimal.invalid", new Object[] { index + 1, this.digitsAfterDecimalForMonetaryAmounts }); } int digitsBefore = amountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsBeforeDecimal.invalid", new Object[] { index + 1, this.digitsBeforeDecimalForMonetaryAmounts }); } } // check error message of loan purpose for each client when its mandatory.. Integer clientLoanPurposeId = this.clientLoanPurposeId[index]; if (this.purposeOfLoanMandatory && isInvalidSelection(clientLoanPurposeId)) { errors.rejectValue("clientLoanPurposeId", "loanAccountFormBean.glim.purposeOfLoan.invalid", new Object[] { index + 1 }, "Please specify loan purpose."); this.clientLoanPurposeId[index] = 0; } else { // needed so attempt in freemarker(ftl) to display loan purpose doesnt fall over. if (clientLoanPurposeId == null) { this.clientLoanPurposeId[index] = 0; } } selectedCount++; } else { Number clientAmount = this.clientAmount[index]; Integer clientLoanPurposeId = this.clientLoanPurposeId[index]; if (clientAmount != null || clientLoanPurposeId != null) { String defaultErrorMessage = "You have entered details for a member you have not selected. Select the checkbox in front of the member's name in order to include him or her in the loan."; rejectUnselectedGlimClientAmountField(index + 1, errors, defaultErrorMessage); } } index++; } if (selectedCount < 2) { String defaultErrorMessage = "Not enough clients for group loan."; rejectGroupLoanWithTooFewClients(errors, defaultErrorMessage); } } if (this.amount == null || exceedsMinOrMax(this.amount, this.minAllowedAmount, this.maxAllowedAmount)) { String defaultErrorMessage = "Please specify valid Amount."; if (glimApplicable) { defaultErrorMessage = "The sum of the amounts specified for each member is outside the allowable total amount for this loan product."; rejectGlimTotalAmountField(errors, defaultErrorMessage); } else { rejectAmountField(errors, defaultErrorMessage); } } if (this.amount != null) { BigDecimal amountAsDecimal = new BigDecimal(this.amount.toString()).stripTrailingZeros(); int places = amountAsDecimal.scale(); if (places > this.digitsAfterDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsAfterDecimal.invalid", new Object[] { this.digitsAfterDecimalForMonetaryAmounts }); } int digitsBefore = amountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsBeforeDecimal.invalid", new Object[] { this.digitsBeforeDecimalForMonetaryAmounts }); } } if (this.interestRate == null || exceedsMinOrMax(this.interestRate, this.minAllowedInterestRate, this.maxAllowedInterestRate)) { String defaultErrorMessage = "Please specify valid Interest rate."; rejectInterestRateField(errors, defaultErrorMessage); } if (this.interestRate != null) { BigDecimal interestRateAsDecimal = new BigDecimal(this.interestRate.toString()).stripTrailingZeros(); int places = interestRateAsDecimal.scale(); if (places > this.digitsAfterDecimalForInterest) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsAfterDecimalForInterest.invalid", new Object[] { this.digitsAfterDecimalForInterest }); } int digitsBefore = interestRateAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForInterest) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsBeforeDecimalForInterest.invalid", new Object[] { this.digitsBeforeDecimalForInterest }); } } if (this.numberOfInstallments == null || exceedsMinOrMax(this.numberOfInstallments, this.minNumberOfInstallments, this.maxNumberOfInstallments)) { String defaultErrorMessage = "Please specify valid number of installments."; rejectNumberOfInstallmentsField(errors, defaultErrorMessage); } if (this.graceDuration == null || this.graceDuration.intValue() < 0) { if (!errors.hasFieldErrors("graceDuration")) { String defaultErrorMessage = "Please specify valid Grace period for repayments. Grace period should be a value less than " + numberOfInstallments.intValue() + "."; rejectGraceDurationField(errors, defaultErrorMessage); } } else { if (this.graceDuration.intValue() > this.maxGraceDuration.intValue()) { String defaultErrorMessage = "The Grace period cannot be greater than in loan product definition."; errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDuration.invalid", defaultErrorMessage); } if (this.numberOfInstallments != null && (this.graceDuration.intValue() >= this.numberOfInstallments.intValue())) { String defaultErrorMessage = "Grace period for repayments must be less than number of loan installments."; errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDurationInRelationToInstallments.invalid", defaultErrorMessage); } } if (dateValidator == null) { dateValidator = new DateValidator(); } if (!dateValidator.formsValidDate(this.disbursementDateDD, this.disbursementDateMM, this.disbursementDateYY)) { String defaultErrorMessage = "Please specify valid disbursal date."; rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", "loanAccountFormBean.DisbursalDate.invalid", ""); } else { LocalDate validDate = new DateTime().withDate(disbursementDateYY.intValue(), disbursementDateMM.intValue(), disbursementDateDD.intValue()).toLocalDate(); org.mifos.platform.validations.Errors disbursementDateErrors = new org.mifos.platform.validations.Errors(); if (this.redoLoanAccount) { disbursementDateErrors = loanDisbursementDateValidationServiceFacade .validateLoanWithBackdatedPaymentsDisbursementDate(validDate, customerId, productId); } else { disbursementDateErrors = loanDisbursementDateValidationServiceFacade .validateLoanDisbursementDate(validDate, customerId, productId); } for (ErrorEntry entry : disbursementDateErrors.getErrorEntries()) { String defaultErrorMessage = "The disbursal date is invalid."; rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", entry.getErrorCode(), entry.getArgs().get(0)); } } if (this.sourceOfFundsMandatory && isInvalidSelection(this.fundId)) { errors.rejectValue("fundId", "loanAccountFormBean.SourceOfFunds.invalid", "Please specify source of funds."); } if (this.externalIdMandatory && StringUtils.isBlank(this.externalId)) { errors.rejectValue("externalId", "loanAccountFormBean.externalid.invalid", "Please specify required external id."); } if (!this.glimApplicable && this.purposeOfLoanMandatory && isInvalidSelection(this.loanPurposeId)) { errors.rejectValue("loanPurposeId", "loanAccountFormBean.PurposeOfLoan.invalid", "Please specify loan purpose."); } validateAdministrativeAndAdditionalFees(errors); if (this.repaymentScheduleIndependentOfCustomerMeeting) { if (isInvalidRecurringFrequency(this.repaymentRecursEvery)) { errors.rejectValue("repaymentRecursEvery", "loanAccountFormBean.repaymentDay.recursEvery.invalid", "Please specify a valid recurring frequency for repayment day."); } if (this.weekly) { if (isInvalidDayOfWeekSelection()) { errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.weekly.dayOfWeek.invalid", "Please select a day of the week for repayment day."); } } else if (this.monthly) { if (this.monthlyDayOfMonthOptionSelected) { if (isInvalidDayOfMonthEntered()) { errors.rejectValue("repaymentDayOfMonth", "loanAccountFormBean.repaymentDay.monthly.dayOfMonth.invalid", "Please select a day of the month for repayment day."); } } else if (this.monthlyWeekOfMonthOptionSelected) { if (isInvalidWeekOfMonthSelection()) { errors.rejectValue("repaymentWeekOfMonth", "loanAccountFormBean.repaymentDay.monthly.weekOfMonth.invalid", "Please select a week of the month for repayment day."); } if (isInvalidDayOfWeekSelection()) { errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.monthly.dayOfWeek.invalid", "Please select a day of the week for repayment day."); } } } if (this.variableInstallmentsAllowed) { if (this.selectedFeeId != null) { for (Number feeId : this.selectedFeeId) { if (feeId != null) { VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue()); if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.additionalfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments."); } } } } int defaultFeeIndex = 0; if (this.defaultFeeId != null) { for (Number feeId : this.defaultFeeId) { if (feeId != null) { Boolean feeSelectedForRemoval = this.defaultFeeSelected[defaultFeeIndex]; if (feeSelectedForRemoval == null || !feeSelectedForRemoval) { VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue()); if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.defaultfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments."); } } } defaultFeeIndex++; } } } } if (errors.hasErrors()) { for (FieldError fieldError : errors.getFieldErrors()) { MessageBuilder builder = new MessageBuilder().error().source(fieldError.getField()) .codes(fieldError.getCodes()).defaultText(fieldError.getDefaultMessage()) .args(fieldError.getArguments()); messageContext.addMessage(builder.build()); } } }
From source file:org.orcid.core.manager.impl.OrcidProfileManagerImpl.java
/** * Replace the funding amount string into the desired format * /*from w w w .ja v a 2 s . c o m*/ * @param updatedOrcidProfile * The profile containing the new funding * */ private void setFundingAmountsWithTheCorrectFormat(OrcidProfile updatedOrcidProfile) throws IllegalArgumentException { FundingList fundings = updatedOrcidProfile.retrieveFundings(); for (Funding funding : fundings.getFundings()) { // If the amount is not empty, update it if (funding.getAmount() != null && StringUtils.isNotBlank(funding.getAmount().getContent())) { String amount = funding.getAmount().getContent(); Locale locale = localeManager.getLocale(); ParsePosition parsePosition = new ParsePosition(0); DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale); DecimalFormatSymbols symbols = numberFormat.getDecimalFormatSymbols(); /** * When spaces are allowed, the grouping separator is the * character 160, which is a non-breaking space So, lets change * it so it uses the default space as a separator * */ if (symbols.getGroupingSeparator() == 160) { symbols.setGroupingSeparator(' '); } numberFormat.setDecimalFormatSymbols(symbols); Number number = numberFormat.parse(amount, parsePosition); String formattedAmount = number.toString(); if (parsePosition.getIndex() != amount.length()) { double example = 1234567.89; NumberFormat numberFormatExample = NumberFormat.getNumberInstance(localeManager.getLocale()); throw new IllegalArgumentException( "The amount: " + amount + " doesn'n have the right format, it should use the format: " + numberFormatExample.format(example)); } funding.getAmount().setContent(formattedAmount); } } }
From source file:org.pentaho.chart.plugin.openflashchart.OpenFlashChartFactoryEngine.java
public Chart makePieChart(ChartModel chartModel, NamedValuesDataModel chartTableModel, IChartLinkGenerator chartLinkGenerator) { PieChart pieChart = new PieChart(); PiePlot piePlot = (PiePlot) chartModel.getPlot(); pieChart.setAnimate(piePlot.getAnimate()); pieChart.setBorder(2);//from ww w . ja v a2 s .c o m if (piePlot.getLabels().getVisible() && (piePlot.getLabels().getFontSize() != null)) { pieChart.setFontSize(piePlot.getLabels().getFontSize()); } if (piePlot.getStartAngle() != null) { pieChart.setStartAngle(piePlot.getStartAngle()); } if (piePlot.getOpacity() != null) { pieChart.setAlpha(piePlot.getOpacity()); } ArrayList<Slice> slices = new ArrayList<Slice>(); for (NamedValue chartDataPoint : chartTableModel) { Number value = chartDataPoint.getValue(); if (value != null) { Slice slice = null; if (piePlot.getLabels().getVisible()) { slice = new Slice(scaleNumber(value, chartTableModel.getScalingFactor()), "", chartDataPoint.getName()); } else { slice = new Slice(scaleNumber(value, chartTableModel.getScalingFactor()), ""); slice.setTooltip(chartDataPoint.getName() + " - " + value.toString()); } if (chartLinkGenerator != null) { String sliceLink = chartLinkGenerator.generateLink(chartDataPoint.getName(), chartDataPoint.getName(), chartDataPoint.getValue()); if (sliceLink != null) { slice.setOnClick(sliceLink.replaceAll("javascript:", "")); //$NON-NLS-1$ //$NON-NLS-2$ } } slices.add(slice); } } pieChart.addSlices(slices); Palette palette = getPalette(piePlot); ArrayList<String> strColors = new ArrayList<String>(); for (Integer color : palette) { strColors.add("#" + Integer.toHexString(0x00FFFFFF & color)); } pieChart.setColours(strColors); Chart chart = createBasicChart(chartModel); chart.addElements(pieChart); return chart; }
From source file:org.tolven.assembler.webxml.WebXMLAssembler.java
protected void addServlet(Extension servletExn, XMLStreamWriter xmlStreamWriter) throws XMLStreamException { String servletName = servletExn.getParameter("servlet-name").valueAsString(); String servletClass = servletExn.getParameter("servlet-class").valueAsString(); xmlStreamWriter.writeStartElement("xsl:if"); xmlStreamWriter.writeAttribute("test", "count(tp:servlet[tp:servlet-name = '" + servletName + "']) = 0"); xmlStreamWriter.writeCharacters("\n"); xmlStreamWriter.writeStartElement("servlet"); xmlStreamWriter.writeCharacters("\n"); xmlStreamWriter.writeStartElement("servlet-name"); xmlStreamWriter.writeCharacters(servletName); xmlStreamWriter.writeEndElement();// ww w . j a v a2 s.c o m xmlStreamWriter.writeCharacters("\n"); xmlStreamWriter.writeStartElement("servlet-class"); xmlStreamWriter.writeCharacters(servletClass); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeCharacters("\n"); for (Parameter param : servletExn.getParameters("init-param")) { xmlStreamWriter.writeStartElement("init-param"); String paramName = param.getSubParameter("param-name").valueAsString(); xmlStreamWriter.writeStartElement("param-name"); xmlStreamWriter.writeCharacters(paramName); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeCharacters("\n"); String paramValue = param.getSubParameter("param-value").valueAsString(); xmlStreamWriter.writeStartElement("param-value"); xmlStreamWriter.writeCharacters(paramValue); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeCharacters("\n"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeCharacters("\n"); } if (servletExn.getParameter("load-on-startup") != null) { Number loadOnStartUp = servletExn.getParameter("load-on-startup").valueAsNumber(); xmlStreamWriter.writeStartElement("load-on-startup"); xmlStreamWriter.writeCharacters(loadOnStartUp.toString()); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeCharacters("\n"); } xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeCharacters("\n"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeCharacters("\n"); }