Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch JSF Converter for class in ManagedBean (JSF 1.2)

I am stuck and need outside help from JSF experts with the following problem: I defined some converters in the faces-config.xml for specific classes so I don't have to use the converter-attribute or tag all the time. For example:

    <converter>
      <converter-for-class>org.joda.time.DateTime</converter-for-class>
      <converter-class>com.example.converter.JodaDateTimeConverter</converter-class>
    </converter>

Now there is the need for a crawler for a JSF-Component (mostly rich:extendedDataTable) which builds the whole component tree and converts level after level into CSV, HTML or whatever might be needed later on. Namely a generic way to export to CSV, HTML, ... without the need to implement it every single time anew. It is almost done (thanks to the great idea of an old colleague of mine) and it does work great except for one part:

    Object expressionResult = expression.getValue(FacesContext.getCurrentInstance().getELContext());
    expressionResultString = expressionResult.toString();

That command retrieves the value of an h:outputText and converts it to String. That last line is what I want to replace with the converter-for-class if there is a custom converter for a specific expressionResult. I can't find out how to find that exact converter for my classes (as specified by faces-config). The FacesContext doesn't seem to hold any useful method/object for my use case. Accessing the faces-config.xml directly seems kind of wrong. A correct approach might look something like:

    Converter converter = magically_fetch_the_correct_converter_for_expressionResult_type;
    converter.getAsString(FacesContext.getCurrentInstance(), component,
                                expressionResult);

It would be fairly easy if I used converter-id and the appropriate attribute/tag for the components themselves but I really want to avoid that kind of useless additional code.

Can someone out there please help me?

like image 593
Michael Colin Avatar asked May 08 '12 13:05

Michael Colin


1 Answers

You're looking for Application#createConverter().

Object object = expression.getValue(context.getELContext());
Class<?> type = expression.getType(context.getELContext());
Converter converter = context.getApplication().createConverter(type);
String string = converter.getAsString(context, component, object);
like image 182
BalusC Avatar answered Nov 15 '22 08:11

BalusC