Example usage for org.apache.wicket.util.convert IConverter convertToString

List of usage examples for org.apache.wicket.util.convert IConverter convertToString

Introduction

In this page you can find the example usage for org.apache.wicket.util.convert IConverter convertToString.

Prototype

String convertToString(C value, Locale locale);

Source Link

Document

Converts the given value to a string.

Usage

From source file:com.antilia.web.field.impl.TableRadioChoice.java

License:Apache License

/**
 * @see org.apache.wicket.Component#onComponentTagBody(MarkupStream, ComponentTag)
 *///from w w w  . j  ava  2 s  .  c om
@Override
protected final void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {
    // Iterate through choices
    final List<? extends T> choices = getChoices();

    // Buffer to hold generated body
    final AppendingStringBuffer buffer = new AppendingStringBuffer((choices.size() + 1) * 70);

    // The selected value
    final String selected = getValue();

    buffer.append("<table style=\"width: 100%;\" cellpadding=\"0\" cellspacing=\"5\">");

    // Loop through choices
    for (int index = 0; index < choices.size(); index++) {
        // Get next choice
        final T choice = choices.get(index);

        Object displayValue = getChoiceRenderer().getDisplayValue(choice);
        Class<?> objectClass = (displayValue == null ? null : displayValue.getClass());

        // Get label for choice
        String label = "";

        if (objectClass != null && objectClass != String.class) {
            final IConverter converter = (IConverter) getConverter(objectClass);

            if (!converter.getClass().isAssignableFrom(objectClass)) {
                throw new IllegalArgumentException(
                        "converter can not convert " + objectClass.getName() + " to string");
            }

            label = converter.convertToString(displayValue, getLocale());
        } else if (displayValue != null) {
            label = displayValue.toString();
        }

        // If there is a display value for the choice, then we know that the
        // choice is automatic in some way. If label is /null/ then we know
        // that the choice is a manually created radio tag at some random
        // location in the page markup!
        if (label != null) {
            // Append option suffix
            buffer.append(getPrefix());

            String id = getChoiceRenderer().getIdValue(choice, index);
            final String idAttr = getMarkupId() + "_" + id;

            buffer.append("<tr>");
            buffer.append("<td style=\"width: 15px; vertical-align: top;\">");

            // Add radio tag
            buffer.append("<input name=\"").append(getInputName()).append("\"").append(" type=\"radio\"")
                    .append((isSelected(choice, index, selected) ? " checked=\"checked\"" : ""))
                    .append((isEnabled() ? "" : " disabled=\"disabled\"")).append(" value=\"").append(id)
                    .append("\" id=\"").append(idAttr).append("\"");

            // Should a roundtrip be made (have onSelectionChanged called)
            // when the option is clicked?
            if (wantOnSelectionChangedNotifications()) {
                CharSequence url = urlFor(IOnChangeListener.INTERFACE);

                Form<?> form = findParent(Form.class);
                if (form != null) {
                    RequestContext rc = RequestContext.get();
                    if (rc.isPortletRequest()) {
                        // restore url back to real wicket path as its going to be interpreted
                        // by the form itself
                        url = ((PortletRequestContext) rc).getLastEncodedPath();
                    }
                    buffer.append(" onclick=\"").append(form.getJsForInterfaceUrl(url)).append(";\"");
                } else {
                    // TODO: following doesn't work with portlets, should be posted to a dynamic
                    // hidden form
                    // with an ActionURL or something
                    // NOTE: do not encode the url as that would give
                    // invalid JavaScript
                    buffer.append(" onclick=\"window.location.href='").append(url)
                            .append((url.toString().indexOf('?') > -1 ? "&amp;" : "?") + getInputName())
                            .append("=").append(id).append("';\"");
                }
            }

            buffer.append("/>");

            buffer.append("</td>");

            buffer.append("<td nowrap=\"nowrap\" style=\"width: 300px;\">");
            // Add label for radio button
            String display = label;
            if (localizeDisplayValues()) {
                display = getLocalizer().getString(label, this, label);
            }
            CharSequence escaped = Strings.escapeMarkup(display, false, true);
            buffer.append(escaped);

            // Append option suffix
            buffer.append(getSuffix());
            buffer.append("</td>");
            buffer.append("</tr>");
        }

    }
    buffer.append("</table>");

    // Replace body
    replaceComponentTagBody(markupStream, openTag, buffer);
}

From source file:com.googlecode.wicket.jquery.core.utils.ConverterUtils.java

License:Apache License

/**
 * Converts the object to its string representation using the appropriate converter, if defined.
 * //  www  .  j  av  a  2 s  .co  m
 * @param object the object
 * @return the string representation using the appropriate converter, if defined. #toString() otherwise.
 */
public static <T> String toString(T object) {
    String value = null;

    @SuppressWarnings("unchecked")
    IConverter<T> converter = (IConverter<T>) Application.get().getConverterLocator()
            .getConverter(object.getClass());

    if (converter != null) {
        value = converter.convertToString(object, Session.get().getLocale());
    } else {
        value = object.toString();
    }

    return value;
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebDataButton.java

License:Open Source License

/**
 * @see org.apache.wicket.Component#onBeforeRender()
 *//*from  w  w w. ja v  a  2  s  . c o  m*/
@Override
protected void onBeforeRender() {
    super.onBeforeRender();

    IModel<?> model = getInnermostModel();
    if (needEntireState && model instanceof RecordItemModel) {
        if (dataProviderID != null) {
            Object val = getModelObject();
            if (val instanceof byte[]) {
                setIcon((byte[]) val);
            } else if (icon != null) {
                setIcon(null);
            } else {
                try {
                    ComponentFormat fp = getScriptObject().getComponentFormat();
                    if (fp == null) {
                        bodyText = Text.processTags((String) val, resolver);
                    } else {
                        bodyText = Text.processTags(TagResolver.formatObject(val, application.getLocale(),
                                fp.parsedFormat,
                                (fp.parsedFormat.getDisplayFormat() != null
                                        ? new ServoyMaskFormatter(fp.parsedFormat.getDisplayFormat(), true)
                                        : null)),
                                resolver);
                    }
                } catch (ParseException e) {
                    Debug.error(e);
                }
            }
        } else {
            bodyText = Text.processTags(tagText, resolver);
        }

        if (bodyText != null) {
            if (HtmlUtils.startsWithHtml(bodyText)) {
                bodyText = StripHTMLTagsConverter
                        .convertBodyText(this, bodyText, application.getFlattenedSolution()).getBodyTxt();
            } else {
                // convert the text
                final IConverter converter = getConverter(String.class);
                bodyText = converter.convertToString(bodyText, getLocale());
            }
        }
    } else {
        Object modelObject = getModelObject();
        if (modelObject instanceof byte[]) {
            setIcon((byte[]) modelObject);
        } else if (icon != null) {
            setIcon(null);
        } else {
            ComponentFormat cf = getScriptObject().getComponentFormat();
            if (cf == null) {
                bodyText = Text.processTags(getDefaultModelObjectAsString(), resolver);
            } else {
                try {
                    bodyText = TagResolver.formatObject(modelObject, application.getLocale(), cf.parsedFormat,
                            (cf.parsedFormat.getDisplayFormat() != null
                                    ? new ServoyMaskFormatter(cf.parsedFormat.getDisplayFormat(), true)
                                    : null));
                } catch (ParseException e) {
                    Debug.error(e);
                }
            }
            if (HtmlUtils.startsWithHtml(modelObject)) {
                // ignore script/header contributions for now
                bodyText = StripHTMLTagsConverter
                        .convertBodyText(this, bodyText, application.getFlattenedSolution()).getBodyTxt();
            }
        }
    }

    if (model instanceof RecordItemModel) {
        ((RecordItemModel) model).updateRenderedValue(this);
    }
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebDataComboBox.java

License:Open Source License

@Override
public void updateModel() {
    Object input = getConvertedInput();
    if (input instanceof Date) {
        IConverter c = getConverter(Date.class);
        setModelObject(c.convertToObject(c.convertToString(input, getLocale()), getLocale()));
    } else {/*from  w w w .  j  av  a 2 s.  co  m*/
        setModelObject(input);
    }
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebDataLabel.java

License:Open Source License

/**
 * @see org.apache.wicket.Component#onBeforeRender()
 */// w  w  w  .j  a v a 2 s.  c om
@Override
protected void onBeforeRender() {
    super.onBeforeRender();

    IModel<?> model = getInnermostModel();
    hasHTML = false;
    if (needEntireState && model instanceof RecordItemModel) {
        if (dataProviderID != null) {
            Object val = getDefaultModelObject();
            if (val instanceof byte[]) {
                setIcon((byte[]) val);
            } else if (icon != null) {
                setIcon(null);
            } else {
                ComponentFormat cf = getComponentFormat();
                if (cf == null) {
                    bodyText = Text.processTags((String) val, resolver);
                } else {
                    try {
                        bodyText = Text.processTags(TagResolver.formatObject(val, application.getLocale(),
                                cf.parsedFormat,
                                (cf.parsedFormat.getDisplayFormat() != null
                                        ? new ServoyMaskFormatter(cf.parsedFormat.getDisplayFormat(), true)
                                        : null)),
                                resolver);
                    } catch (ParseException e) {
                        Debug.error(e);
                    }
                }
            }
        } else {
            bodyText = Text.processTags(tagText, resolver);
        }
        if (bodyText != null) {
            if (HtmlUtils.startsWithHtml(bodyText)) {
                bodyText = StripHTMLTagsConverter
                        .convertBodyText(this, bodyText, application.getFlattenedSolution()).getBodyTxt();
                hasHTML = true;
            } else {
                // convert the text (strip html if needed)
                final IConverter converter = getConverter(String.class);
                bodyText = converter.convertToString(bodyText, getLocale());
            }
        }
    } else {
        Object modelObject = getDefaultModelObject();
        if (modelObject instanceof byte[]) {
            setIcon((byte[]) modelObject);
        } else if (icon != null) {
            setIcon(null);
        } else {
            ComponentFormat cf = getComponentFormat();
            if (cf == null) {
                bodyText = Text.processTags(getDefaultModelObjectAsString(), resolver);
            } else {
                try {
                    bodyText = TagResolver.formatObject(modelObject, application.getLocale(), cf.parsedFormat,
                            (cf.parsedFormat.getDisplayFormat() != null
                                    ? new ServoyMaskFormatter(cf.parsedFormat.getDisplayFormat(), true)
                                    : null));
                } catch (ParseException e) {
                    Debug.error(e);
                }
            }
            if (HtmlUtils.startsWithHtml(modelObject)) {
                // ignore script/header contributions for now
                bodyText = StripHTMLTagsConverter
                        .convertBodyText(this, bodyText, application.getFlattenedSolution()).getBodyTxt();
                hasHTML = true;
            }
        }
    }

    if (model instanceof RecordItemModel) {
        ((RecordItemModel) model).updateRenderedValue(this);
    }
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebDataLabel.java

License:Open Source License

/**
 * @see com.servoy.j2db.dataprocessing.IDisplayData#setValue(java.lang.Object)
 *///from ww  w. j  a v  a2  s.  co  m
public void setValueObject(Object obj) {
    if (dataProviderID == null && needEntireState) {
        CharSequence current = Text.processTags(tagText, resolver);
        // test for the page else this field is not yet attached to a page yet and must be rerendered anyway.
        if (current != null && findPage() != null) {
            if (HtmlUtils.startsWithHtml(current)) {
                current = StripHTMLTagsConverter
                        .convertBodyText(this, current, application.getFlattenedSolution()).getBodyTxt();
            } else {
                // convert the text (strip html if needed)
                final IConverter converter = getConverter(String.class);
                current = converter.convertToString(current, getLocale());
            }
        }
        if (bodyText != null && current != null) {
            if (!Utils.equalObjects(bodyText.toString(), current.toString()))
                getScriptObject().getChangesRecorder().setChanged();
        } else if (current != null || bodyText != null)
            getScriptObject().getChangesRecorder().setChanged();
    } else {
        ((ChangesRecorder) getScriptObject().getChangesRecorder()).testChanged(this, obj);
    }
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebDataLookupField.java

License:Open Source License

private void init() {

    add(new HeaderContributor(new IHeaderContributor() {
        private static final long serialVersionUID = 1L;

        public void renderHead(IHeaderResponse response) {
            response.renderCSSReference(
                    new CompressedResourceReference(WebDataLookupField.class, "servoy_lookupfield.css")); //$NON-NLS-1$
        }/*from   ww  w.ja  v a 2s  .com*/
    }) {
        @Override
        public boolean isEnabled(Component component) {
            return !getScriptObject().isReadOnly() && getScriptObject().isEnabled();
        }
    });

    setOutputMarkupPlaceholderTag(true);

    AutoCompleteSettings behSettings = new AutoCompleteSettings();
    behSettings.setMaxHeightInPx(200);
    behSettings.setPreselect(true);
    behSettings.setShowCompleteListOnFocusGain(true);
    behSettings.setAdjustInputWidth(false);

    ClientProperties clp = (application.getApplicationType() != IApplication.HEADLESS_CLIENT
            ? ((WebClientInfo) Session.get().getClientInfo()).getProperties()
            : null); // in case of batch processors/jsp, we can't get browser info because UI is not given by web client components
    if (clp != null && (!clp.isBrowserInternetExplorer() || clp.getBrowserVersionMajor() >= 8)) {
        // smart positioning doesn't work on IE < 8 (probably because of unreliable clientWidth/clientHeight browser element js properties)
        behSettings.setUseSmartPositioning(true);
        behSettings.setUseHideShowCoveredIEFix(false); // don't know if the problem this setting is for can still be reproduced (I couldn't reproduce it)... this is true by default and makes fields in IE and Opera appear/dissapear if they would be covered by type-ahead popup
    } else {
        behSettings.setUseSmartPositioning(false);
        behSettings.setUseHideShowCoveredIEFix(true);
    }
    behSettings.setThrottleDelay(500);

    IAutoCompleteRenderer<Object> renderer = new IAutoCompleteRenderer<Object>() {
        protected String getTextValue(Object object) {
            String str = ""; //$NON-NLS-1$
            if (object instanceof DisplayString) {
                str = object.toString();
            } else if (object != null && !(object instanceof String)) {
                IConverter con = getConverter(object.getClass());
                if (con != null) {
                    str = con.convertToString(object, getLocale());
                } else {
                    str = object.toString();
                }
            } else if (object != null) {
                str = object.toString();
            }
            if (str == null || str.trim().equals("")) //$NON-NLS-1$
                str = "&nbsp;"; //$NON-NLS-1$
            return str;
        }

        protected void renderChoice(Object object, Response response, String criteria) {
            if (IValueList.SEPARATOR_DESIGN_VALUE.equals(object))
                return;
            String renderedObject = getTextValue(object);
            // escape the markup if it is not html or not just an empty none breaking space (null or empty string object)
            if (!renderedObject.equals("&nbsp;") && !HtmlUtils.hasHtmlTag(renderedObject)) //$NON-NLS-1$
                renderedObject = HtmlUtils.escapeMarkup(renderedObject, true, false).toString();
            response.write(renderedObject);
        }

        /*
         * (non-Javadoc)
         *
         * @see org.apache.wicket.extensions.ajax.markup.html.autocomplete.IAutoCompleteRenderer#render(java.lang.Object, org.apache.wicket.Response,
         * java.lang.String)
         */
        public void render(Object object, Response response, String criteria) {
            String textValue = getTextValue(object);
            if (textValue == null) {
                throw new IllegalStateException(
                        "A call to textValue(Object) returned an illegal value: null for object: "
                                + object.toString());
            }
            textValue = textValue.replaceAll("\\\"", "&quot;");

            response.write("<li textvalue=\"" + textValue + "\"");
            response.write(">");
            renderChoice(object, response, criteria);
            response.write("</li>");
        }

        /*
         * (non-Javadoc)
         *
         * @see org.apache.wicket.extensions.ajax.markup.html.autocomplete.IAutoCompleteRenderer#renderHeader(org.apache.wicket.Response)
         */
        @SuppressWarnings("nls")
        public void renderHeader(Response response) {
            StringBuffer listStyle = new StringBuffer();
            listStyle.append("style=\"");

            String fFamily = "Tahoma, Arial, Helvetica, sans-serif";
            String bgColor = "#ffffff";
            String fgColor = "#000000";
            String fSize = TemplateGenerator.DEFAULT_FONT_SIZE + "px";
            String padding = "2px";
            String margin = "0px";
            if (getFont() != null) {
                Font f = getFont();
                if (f != null) {
                    if (f.getFamily() != null) {
                        fFamily = f.getFamily();
                        if (fFamily.contains(" "))
                            fFamily = "'" + fFamily + "'";
                    }
                    if (f.getName() != null) {
                        String fName = f.getName();
                        if (fName.contains(" "))
                            fName = "'" + fName + "'";
                        fFamily = fName + "," + fFamily;
                    }
                    if (f.isBold())
                        listStyle.append("font-weight:bold; ");
                    if (f.isItalic())
                        listStyle.append("font-style:italic; ");

                    fSize = Integer.toString(f.getSize()) + "px";
                }
            }

            if (getListColor() != null && getListColor().getAlpha() == 255) {
                // background shouldn't be transparent
                bgColor = getWebColor(getListColor().getRGB());
            }
            if (getForeground() != null) {
                fgColor = getWebColor(getForeground().getRGB());
            }
            Insets _padding = getPadding();
            if (getPadding() != null)
                padding = _padding.top + "px " + _padding.right + "px " + _padding.bottom + "px "
                        + _padding.left + "px";

            listStyle.append("font-family:" + fFamily + "; ");
            listStyle.append("background-color: " + bgColor + "; ");
            listStyle.append("color: " + fgColor + "; ");
            listStyle.append("font-size:" + fSize + "; ");
            listStyle.append("min-width:" + (getSize().width - 6) + "px; "); // extract padding and border
            listStyle.append("margin: " + margin + "; ");
            listStyle.append("padding: " + padding + "; ");
            listStyle.append(
                    "text-align:" + TemplateGenerator.getHorizontalAlignValue(getHorizontalAlignment()));
            listStyle.append("\"");

            response.write("<ul " + listStyle + ">");
        }

        /*
         * (non-Javadoc)
         *
         * @see org.apache.wicket.extensions.ajax.markup.html.autocomplete.IAutoCompleteRenderer#renderFooter(org.apache.wicket.Response)
         */
        public void renderFooter(Response response) {
            response.write("</ul>"); //$NON-NLS-1$
        }

        /**
         * Returns web color representation of int rgba color by
         * removing the alpha value
         *
         * @param color int representation of rgba color
         * @return web color of form #rrggbb
         */
        private String getWebColor(int color) {
            String webColor = Integer.toHexString(color);
            int startIdx = webColor.length() - 6;
            if (startIdx < 0)
                startIdx = 0;
            webColor = webColor.substring(startIdx);

            StringBuilder sb = new StringBuilder();
            sb.append('#');
            int nrMissing0 = 6 - webColor.length();
            for (int i = 0; i < nrMissing0; i++) {
                sb.append('0');
            }
            sb.append(webColor);

            return sb.toString();
        }
    };

    AutoCompleteBehavior<Object> beh = new AutoCompleteBehavior<Object>(renderer, behSettings) {
        private static final long serialVersionUID = 1L;

        /**
         * @see org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteBehavior#getChoices(java.lang.String)
         */
        @Override
        protected Iterator<Object> getChoices(String input) {
            String filteredInput = filterInput(input);
            if (changeListener != null)
                dlm.getValueList().removeListDataListener(changeListener);
            try {
                dlm.fill(parentState, getDataProviderID(), filteredInput, false);
                return dlm.iterator();
            } catch (Exception ex) {
                Debug.error(ex);
            } finally {
                if (changeListener != null)
                    dlm.getValueList().addListDataListener(changeListener);
            }
            return Collections.emptyList().iterator();
        }

        /**
         * filters the input in case of masked input (removes the mask)
         */
        private String filterInput(String input) {
            String displayFormat = WebDataLookupField.this.parsedFormat.getDisplayFormat();
            if (displayFormat != null && displayFormat.length() > 0
                    && input.length() == displayFormat.length()) {
                int index = firstBlankSpacePosition(input, displayFormat);
                if (index == -1)
                    return input;
                return input.substring(0, index);
            }
            return input;
        }

        /**
         * Computes the index of the first space char found in the input and is not ' ' nor '*' in the format
         * Example:
         * input  '12 - 3  -  '
         * format '## - ## - #'
         * returns 6
         * @param input
         * @param displayFormat
         * @return The index of the first space char found in the input and is not ' ' nor '*' in the format
         */
        private int firstBlankSpacePosition(String input, String displayFormat) {
            for (int i = 0; i < input.length(); i++) {
                if ((input.charAt(i) == ' ') && (displayFormat.charAt(i) != ' ')
                        && (displayFormat.charAt(i) != '*'))
                    return i;
            }
            return 0;
        }

        /**
         * @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#getFailureScript()
         */
        @Override
        protected CharSequence getFailureScript() {
            return "onAjaxError();"; //$NON-NLS-1$
        }

        /**
         * @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#getPreconditionScript()
         */
        @Override
        protected CharSequence getPreconditionScript() {
            return "onAjaxCall();" + super.getPreconditionScript(); //$NON-NLS-1$
        }

        // need to set this behavior to true (enterHidesWithNoSelection) because otherwise the onKeyDown events
        // or other events for the component with type ahead would be null in Firefox, and would not execute as
        // expected on the other browsers...
        @Override
        public void renderHead(IHeaderResponse response) {
            settings.setShowListOnEmptyInput(Boolean.TRUE.equals(UIUtils.getUIProperty(getScriptObject(),
                    application, IApplication.TYPE_AHEAD_SHOW_POPUP_WHEN_EMPTY, Boolean.TRUE)));
            settings.setShowListOnFocusGain(Boolean.TRUE.equals(UIUtils.getUIProperty(getScriptObject(),
                    application, IApplication.TYPE_AHEAD_SHOW_POPUP_ON_FOCUS_GAIN, Boolean.TRUE)));
            if (!getScriptObject().isReadOnly() && getScriptObject().isEnabled()) {
                super.renderHead(response);
                response.renderJavascript("Wicket.AutoCompleteSettings.enterHidesWithNoSelection = true;", //$NON-NLS-1$
                        "AutocompleteSettingsID"); //$NON-NLS-1$
            }
        }

        /**
         * @see org.apache.wicket.behavior.AbstractBehavior#isEnabled(org.apache.wicket.Component)
         */
        @Override
        public boolean isEnabled(Component component) {
            IFormUIInternal<?> formui = findParent(IFormUIInternal.class);
            if (formui != null && formui.isDesignMode()) {
                return false;
            }
            return super.isEnabled(component) && WebClientSession.get().useAjax();
        }
    };
    add(beh);
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebDataSpinner.java

License:Open Source License

private String[] getNewValues() {
    String[] values = null;/*from   www.j ava  2 s. c o  m*/
    if (valueList != null) {
        IValueList vl = valueList;
        if (!field.getEventExecutor().getValidationEnabled() && vl.getFallbackValueList() != null) {
            vl = vl.getFallbackValueList();
        }
        int size = vl.getSize();
        if (size > 1 || (size == 1 && vl.getElementAt(0) != null
                && String.valueOf(vl.getElementAt(0)).trim().length() > 0)) {
            values = new String[size];
            Object v;
            IConverter converter = field.getConverter(field.getType());
            for (int i = 0; i < size; i++) {
                v = vl.getRealElementAt(i);
                String val = (v != null) ? converter.convertToString(v, getLocale()) : "";
                if (val == null)
                    val = "";
                values[size - i - 1] = val;
            }
        }
    }
    if (values == null) {
        values = new String[] { "", "" }; //$NON-NLS-1$//$NON-NLS-2$
    }
    return values;
}

From source file:de.alpharogroup.wicket.components.form.ChoicesListView.java

License:Apache License

/**
 * Convenience method exposed to subclasses for determining the display value of a given list
 * item. This delegates to {@link IChoiceRenderer#getDisplayValue getDisplayValue()} on the
 * IChoiceRenderer. The display value will be coverted to a String if necessary using Wicket's
 * {@link IConverter} system.//from   w  w w . j  a v a2s.  c o m
 * 
 * @param choice
 *            The current value of the list that is being rendered.
 * @return the choice label
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected String getChoiceLabel(final T choice) {
    // This code was copied from Wicket's CheckBoxMultipleChoice.java
    final Object displayValue = getChoiceRenderer().getDisplayValue(choice);
    final Class<?> objectClass = displayValue == null ? null : displayValue.getClass();
    // Get label for choice
    String label = "";
    if ((objectClass != null) && (objectClass != String.class)) {
        final IConverter converter = getConverter(objectClass);
        label = converter.convertToString(displayValue, getLocale());
    } else if (displayValue != null) {
        label = displayValue.toString();
    }
    return label;
}

From source file:de.invesdwin.nowicket.component.palette.component.AOptions.java

License:Apache License

/**
 * {@inheritDoc}//from ww  w.jav a  2s .  co  m
 */
@Override
public void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {
    final StringBuilder buffer = new StringBuilder(128);
    final Iterator<T> options = getOptionsIterator();
    final IChoiceRenderer<T> renderer = getPalette().getChoiceRenderer();

    final boolean localizeDisplayValues = localizeDisplayValues();

    while (options.hasNext()) {
        final T choice = options.next();

        final CharSequence id;
        //CHECKSTYLE:OFF
        {
            //CHECKSTYLE:ON
            final String value = renderer.getIdValue(choice, 0);

            if (getEscapeModelStrings()) {
                id = Strings.escapeMarkup(value);
            } else {
                id = value;
            }
        }

        final CharSequence value;
        //CHECKSTYLE:OFF
        {
            //CHECKSTYLE:ON
            final Object displayValue = renderer.getDisplayValue(choice);
            final Class<?> displayClass = displayValue == null ? null : displayValue.getClass();

            @SuppressWarnings("unchecked")
            final IConverter<Object> converter = (IConverter<Object>) getConverter(displayClass);
            String displayString = converter.convertToString(displayValue, getLocale());
            if (localizeDisplayValues) {
                displayString = getLocalizer().getString(displayString, this, displayString);
            }

            if (getEscapeModelStrings()) {
                value = Strings.escapeMarkup(displayString);
            } else {
                value = displayString;
            }
        }

        buffer.append("\n<option value=\"").append(id).append("\"");

        final Map<String, String> additionalAttributesMap = getAdditionalAttributes(choice);
        if (additionalAttributesMap != null) {
            for (final Map.Entry<String, String> entry : additionalAttributesMap.entrySet()) {
                buffer.append(' ').append(entry.getKey()).append("=\"").append(entry.getValue()).append("\"");
            }
        }

        buffer.append(">").append(value).append("</option>");
    }

    buffer.append("\n");

    replaceComponentTagBody(markupStream, openTag, buffer);
}