Advertisement
Fhernd

CarConverter.java

Dec 19th, 2012
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.15 KB | None | 0 0
  1. package cars;
  2.  
  3. import javax.el.ValueExpression;
  4. import javax.faces.application.FacesMessage;
  5. import javax.faces.component.UIComponent;
  6. import javax.faces.context.FacesContext;
  7. import javax.faces.convert.Converter;
  8. import javax.faces.convert.ConverterException;
  9. import javax.faces.convert.FacesConverter;
  10.  
  11. @FacesConverter(value = "carConverter")
  12. public class CarConverter implements Converter {
  13.    
  14.     /* (non-Javadoc)
  15.      * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
  16.      */
  17.        public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
  18.  
  19.         if (arg0 == null) { throw new NullPointerException("context"); }
  20.     if (arg1 == null) { throw new NullPointerException("component"); }
  21.  
  22.         return ((CarBean)arg2).getCarNumber().toString();
  23.     }
  24.  
  25.     /* (non-Javadoc)
  26.      * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
  27.      */    
  28.     public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
  29.  
  30.         if (arg0 == null) { throw new NullPointerException("context"); }
  31.     if (arg1 == null) { throw new NullPointerException("component"); }
  32.  
  33.         FacesContext ctx = FacesContext.getCurrentInstance();
  34.         ValueExpression vex = ctx.getApplication().getExpressionFactory().createValueExpression(ctx.getELContext(), "#{carsBean}",CarsBean.class);
  35.         CarsBean cars = (CarsBean)vex.getValue(ctx.getELContext());
  36.  
  37.          CarBean car;
  38.         try {            
  39.         car = cars.getCar(new Integer (arg2));
  40.         } catch( NumberFormatException e ) {
  41.             FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_ERROR,
  42.                 "Unknown value", "This is not a  car number!" );
  43.             throw new ConverterException( message );
  44.         }
  45.  
  46.         if( car == null ) {
  47.             FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_ERROR,
  48.                 "Unknown value", "The car is unknown!" );
  49.             throw new ConverterException( message );
  50.         }
  51.  
  52.         return car;
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement