marcelofoxes

CidadeConverter.jaa

May 20th, 2016
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. /**
  2.  *
  3.  */
  4. package com.zxsheart.pedidovenda.converter;
  5.  
  6. import javax.enterprise.context.Dependent;
  7. import javax.faces.component.UIComponent;
  8. import javax.faces.context.FacesContext;
  9. import javax.faces.convert.Converter;
  10. import javax.inject.Inject;
  11. import javax.inject.Named;
  12.  
  13. import org.apache.commons.lang3.StringUtils;
  14.  
  15. import com.zxsheart.pedidovenda.model.endereco.Cidade;
  16. import com.zxsheart.pedidovenda.repository.Cidades;
  17.  
  18. /**
  19.  * @author Marcelo Paixao Resende
  20.  *
  21.  */
  22. @Named
  23. @Dependent
  24. public class CidadeConverter implements Converter {
  25.    
  26.     private @Inject Cidades cidades;
  27.  
  28.     /* (non-Javadoc)
  29.      * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
  30.      */
  31.     @Override
  32.     public Object getAsObject(FacesContext context, UIComponent component, String value) {
  33.         // value é nulo ou em branco?
  34.         if (value == null || StringUtils.isBlank(value)) {
  35.             return null;
  36.         }
  37.        
  38.         try {
  39.             Integer codigo = Integer.parseInt(value);
  40.             return cidades.porCodigo(codigo);
  41.         } catch (NumberFormatException e) {
  42.             return null;
  43.         }
  44.     }
  45.  
  46.     /* (non-Javadoc)
  47.      * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
  48.      */
  49.     @Override
  50.     public String getAsString(FacesContext context, UIComponent component, Object value) {
  51.         if (value == null) {
  52.             return null;
  53.         }
  54.        
  55.         if (!(value instanceof Cidade)) {
  56.             return null;
  57.         }
  58.        
  59.         Cidade cidade = (Cidade) value;
  60.        
  61.         if (cidade.getCodigo() == null) {
  62.             return null;
  63.         }
  64.        
  65.         return cidade.getCodigo().toString();
  66.     }
  67.  
  68. }
Add Comment
Please, Sign In to add comment