Mostrando postagens com marcador JSF. Mostrar todas as postagens
Mostrando postagens com marcador JSF. Mostrar todas as postagens

sexta-feira, 24 de setembro de 2010

Emulando IE7 no richfaces jsf (Problemas no IE8)

Tem varias formas de fazer a emulação do ie7 ...
 import javax.servlet.Filter;  
 import javax.servlet.FilterChain;  
 import javax.servlet.FilterConfig;  
 import javax.servlet.ServletException;  
 import javax.servlet.ServletRequest;  
 import javax.servlet.ServletResponse;  
 import javax.servlet.http.HttpServletResponse;  
 /**  
  * Servlet Filter implementation class IE8CompatablityFixServlet  
  */  
 public class IE8CompatablityFixServlet implements Filter {  
      /**  
       * Default constructor.  
       */  
      public IE8CompatablityFixServlet() {  
      }  
      /**  
       * @see Filter#destroy()  
       */  
      public void destroy() {  
      }  
      /**  
       * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)  
       */  
      public void doFilter(ServletRequest request, ServletResponse response,  
                FilterChain chain) throws IOException, ServletException {  
           ((HttpServletResponse) response).setHeader("X-UA-Compatible",  
                     "IE=EmulateIE7");  
           chain.doFilter(request, response);  
      }  
      /**  
       * @see Filter#init(FilterConfig)  
       */  
      public void init(FilterConfig fConfig) throws ServletException {  
      }  
 }  
E no web.xml : 

<filter>
    <display-name>IE8CompatablityFixServlet</display-name>
    <filter-name>IE8CompatablityFixServlet</filter-name>
    <filter-class>br.com.sintel.plan.presentation.utils.IE8CompatablityFixServlet</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>IE8CompatablityFixServlet</filter-name>
    <url-pattern>/IE8CompatablityFixServlet</url-pattern>
  </filter-mapping>


Opção 2 : 

<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
...
<head/>


Particularmente .. a Opção 1 funciona melhor ! 

Abraços ...

Sem mais !

segunda-feira, 13 de setembro de 2010

Painel modal de status “loading” ou processando ... com a4j:status


Problema:

Como implementar uma tela modal de status “loading” com Ajax?

Solução:

Achei um post bem bom que mostra como fazer, abaixo segue uma copia de trechos do post (necessário para garantir a permanecia da informação):

O a4j:status é um indicador de uma solicitação Ajax. Apresenta um aviso ao usuário enquanto o sistema está processando sua solicitação.
Este componente tem dois estados: start e stop.
O estado start indica que uma solicitação Ajax está em andamento.
O componente muda para o estado stop quando a solicitação Ajax é finalizada.
Quando uma solicitação Ajax é enviada o evento onstart do componente a4j:status é acionado, então ele abre o ModalPanel com o id “panel_loading”.
Quando a solicitação é finalizada, o componente muda seu estado para onstop e chama a função responsável em fechar o ModalPanel.


<rich:modalPanel id="panel_loading" autosized="true">

<h:graphicImage url="/img/loading.gif" style="border:0px; vertical-align: middle;" />

<rich:spacer width="20" />

<h:outputText value="Aguarde..." />

</rich:modalPanel>

<a4j:status id="loading" onstart="Richfaces.showModalPanel('panel_loading')" onstop="Richfaces.hideModalPanel('panel_loading')" />
Ate mais ! ;)

quinta-feira, 9 de setembro de 2010

Chamar uma funcao da pagina pai dentro de um iframe !


Página Pai

<script language="Javascript">
function test() { alert('teste de mensagem'); };
</script>

..  html ...

<iframe src="http://siteY.com/page_y.htm"></iframe>
 Página IFrame

<script language="Javascript">
parent.test();
</script>
Página em servidores diferentes
Se as páginas ficarem em servidores diferentes deve usar essa linha de comando para evitar o erro de Permissão Negada

<script language="Javascript">
document.domain = "microsoft.com"
</script>

E digo mais ainda ... da para usar isso com o JSF + Rich .... por exemplo.... se vc esta abrindo um iframe dentro de um modal panel.... e quer fechar e nao sabe como ... hehehehe .. facil ... no onclick do button
coloca assim : window.parent.Richfaces.hideModalPanel('nome');  q funciona :D :D :D :D :D


EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE !!!!!

Sem mais !!!

segunda-feira, 6 de setembro de 2010

SelectOneRadio em linha ou coluna


Ta ai galera .. :D

<h:selectOneRadio layout="pageDirection" /> <%-- Vertical --%>
<h:selectOneRadio layout="lineDirection" /> <%-- Horizontal --%>

sexta-feira, 27 de agosto de 2010

Popup no commandLink

Pessoal ....

Um jeito facil de chamar relatorios em pdf .. sei la ... alguma coisa assim dentro de uma popup 8-)

Precisei disso esses dias ... consegui fazer e estou passando p vcs !!

<h:commandlink action="stringDaAction" value="#{msg['labeldocommandlink']}" onclick="javascript:window.open('','stringDaAction','height=600px,width=850px,toolbar=no,scrollbars=yes,resizable=no,menubar=no')" target="stringDaAction"/>

Bjunda !

sexta-feira, 20 de agosto de 2010

Trabalhando com ExtendedDataTable e DataProvider

Bom pessoal .. estava trabalhando num projeto novo e me deparei com um problema do cão .. "ExtendedDataTable" ... parece bom mas da um trabalho .... JESUSSSSSSSs .. mas blz ... tive q fazer ai umas POGs para funcionar .. mas ta blz .. estou passando o conhecimento para quem precisa ai ... vai um exemplo de como implementar o tal do DataProvider .... VLW q q coisa avisem !!
 public abstract class CustomDataProvider implements DataProvider{  
  private static final long serialVersionUID = 4469974447038357692L;  
  public List dados;  
  public CustomDataProvider(List dados) {  
  this.setDados(dados);  
  }  
  public T getItemByKey(Object arg0) {  
  for (Object c : this.getDados()) {  
   if (arg0.equals(getKey((T)c))) {  
   return (T) c;  
   }  
  }  
  return null;  
  }  
  public abstract Object getKey(T arg0);  
  public List getItemsByRange(int arg0, int arg1) {  
  return getDados().subList(arg0, arg1);  
  }  
  public int getRowCount() {  
  return getDados().size();  
  }  
  public List getDados() {  
  return dados;  
  }  
  private void setDados(List dados) {  
  this.dados = dados;  
  }  
 }  
}

Modo de usar : Bater 2 ovos com aveia de manha ... ops ...  errei ...

  XXXXX = new ExtendedTableDataModel(  
   new CustomDataProvider(dsItens){  
    public Object getKey(TipoObjetoDaLista item) {  
    return item.getCodCliente(); // Exemplo !  
    }  
   });  

segunda-feira, 16 de agosto de 2010

Operações com arquivos

 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.io.OutputStream;  
 import javax.faces.context.ExternalContext;  
 import javax.faces.context.FacesContext;  
 import javax.servlet.http.HttpServletResponse;  
 public class OperacoesArquivos {  
   public static synchronized void downloadFile(String filename, String fileLocation, String mimeType,  
                          FacesContext facesContext) {  
     String path = fileLocation; // Localizacao do arquivo  
     String fullFileName = path + filename;  
     File file = new File(path); // Objeto arquivo mesmo :)  
     OperacoesArquivos.downloadFile(filename, file, facesContext, mimeType);  
   }  
   public static synchronized void downloadFile(String filename,File arquivo,FacesContext facesContext,String mimeType){  
     ExternalContext context = facesContext.getExternalContext(); // Context  
     HttpServletResponse response = (HttpServletResponse) context.getResponse();  
     try {  
       FileInputStream in = new FileInputStream(arquivo);  
       OutputStream out = response.getOutputStream();  
       byte[] buf = new byte[(int)arquivo.length()];  
       if (buf.length > 0){       
         int count;       
         while ((count = in.read(buf)) >= 0) {  
           out.write(buf, 0, count);  
         }  
       }  
       in.close();  
       out.flush();  
       out.close();  
       facesContext.responseComplete();  
     } catch (IOException ex) {  
       System.out.println("Error in downloadFile: " + ex.getMessage());  
       ex.printStackTrace();  
     }  
     response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\""); //aki eu seto o header e o nome q vai aparecer na hr do donwload  
     response.setContentLength((int) arquivo.length()); // O tamanho do arquivo  
     response.setContentType(mimeType); // e obviamente o tipo  
   }  
 }  

JSFUtil Utilitario para manipular paginas em jsf

Bom pessoal .. deps de um LONGO tempo sem mexer em jsf .. estou voltando à ativa no jsf... mtas novidades mas .. não posso deixar de usar as coisas q eu ja implementei .. então la vai um utilitário para manipular jsf .. Abraços


 import java.util.Map;  
 import javax.faces.FactoryFinder;  
 import javax.faces.application.Application;  
 import javax.faces.application.ApplicationFactory;  
 import javax.faces.application.FacesMessage;  
 import javax.faces.context.ExternalContext;  
 import javax.faces.context.FacesContext;  
 import javax.faces.el.ValueBinding;  
 import javax.faces.webapp.UIComponentTag;  
 import javax.servlet.ServletContext;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 import javax.servlet.http.HttpSession;  
 /**  
  *  
  * @author Caio Paulucci  
  */  
 public class JSFHelper {  
   public static ExternalContext getExternalContext() {  
     FacesContext facesContext = FacesContext.getCurrentInstance();  
     return facesContext.getExternalContext();  
   }  
   public static String getRequestParameter(String parameterName) {  
     Map paramMap = getExternalContext().getRequestParameterMap();  
     return (String) paramMap.get(parameterName);  
   }  
   public static Object getRequestAttribute(String attributeName) {  
     Map attrMap = getExternalContext().getRequestMap();  
     return attrMap.get(attributeName);  
   }  
   public static Object getSessionAttribute(String attributeName) {  
     Map attrMap = getExternalContext().getSessionMap();  
     return attrMap.get(attributeName);  
   }  
   public static void setSessionAttribute(String attributeName, Object attribute) {  
     Map attrMap = getExternalContext().getSessionMap();  
     attrMap.put(attributeName, attribute);  
   }  
   public static Object getApplicationAttribute(String attributeName) {  
     Map attrMap = getExternalContext().getApplicationMap();  
     return attrMap.get(attributeName);  
   }  
   public static void addGlobalMessage(String message) {  
     FacesMessage facesMessage = new FacesMessage(message);  
     FacesContext.getCurrentInstance().addMessage(null, facesMessage);  
   }  
   public static FacesContext getFacesContext(){  
     return FacesContext.getCurrentInstance();  
   }  
   /**  
    * Get servlet context.  
    *  
    * @return the servlet context  
    */  
   public static ServletContext getServletContext() {  
     return (ServletContext) FacesContext.getCurrentInstance()  
                       .getExternalContext().getContext();  
   }  
   /**  
    * Get managed bean based on the bean name.  
    *  
    * @param beanName the bean name  
    * @return the managed bean associated with the bean name  
    */  
   public static Object getManagedBean(String beanName) {  
     Object o =  
       getValueBinding(getJsfEl(beanName)).getValue(FacesContext.getCurrentInstance());  
     return o;  
   }  
   /**  
    * Remove the managed bean based on the bean name.  
    *  
    * @param beanName the bean name of the managed bean to be removed  
    */  
   public static void resetManagedBean(String beanName) {  
     getValueBinding(getJsfEl(beanName)).setValue(FacesContext.getCurrentInstance(),  
                            null);  
   }  
   /**  
    * Store the managed bean inside the session scope.  
    *  
    * @param beanName the name of the managed bean to be stored  
    * @param managedBean the managed bean to be stored  
    */  
   @SuppressWarnings("unchecked")  
  public static void setManagedBeanInSession(String beanName,  
                         Object managedBean) {  
     FacesContext.getCurrentInstance().getExternalContext().getSessionMap()  
           .put(beanName, managedBean);  
   }  
   /**  
    * Get parameter value from request scope.  
    *  
    * @param name the name of the parameter  
    * @return the parameter value  
    */  
   public static Map getRequestParameters() {  
     return FacesContext.getCurrentInstance().getExternalContext()  
                   .getRequestParameterMap();  
   }  
   /**  
    * Add information message.  
    *  
    * @param msg the information message  
    */  
   public static void addInfoMessage(String msg) {  
     addInfoMessage(null, msg);  
   }  
   /**  
    * Add information message to a sepcific client.  
    *  
    * @param clientId the client id  
    * @param msg the information message  
    */  
   public static void addInfoMessage(String clientId, String msg) {  
     FacesContext.getCurrentInstance().addMessage(clientId,  
                            new FacesMessage(FacesMessage.SEVERITY_INFO,  
                                    msg, msg));  
   }  
   /**  
    * Add error message.  
    *  
    * @param msg the error message  
    */  
   public static void addErrorMessage(String msg) {  
     addErrorMessage(null, msg);  
   }  
   /**  
    * Add error message to a sepcific client.  
    *  
    * @param clientId the client id  
    * @param msg the error message  
    */  
   public static void addErrorMessage(String clientId, String msg) {  
     FacesContext.getCurrentInstance().addMessage(clientId,  
                            new FacesMessage(FacesMessage.SEVERITY_ERROR,  
                                    msg, msg));  
   }  
   /**  
    * Evaluate the integer value of a JSF expression.  
    *  
    * @param el the JSF expression  
    * @return the integer value associated with the JSF expression  
    */  
   public static Integer evalInt(String el) {  
     if (el == null) {  
       return null;  
     }  
     if (UIComponentTag.isValueReference(el)) {  
       Object value = getElValue(el);  
       if (value == null) {  
         return null;  
       } else if (value instanceof Integer) {  
         return (Integer) value;  
       } else {  
         return new Integer(value.toString());  
       }  
     } else {  
       return new Integer(el);  
     }  
   }  
   private static Application getApplication() {  
     ApplicationFactory appFactory =  
       (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);  
     return appFactory.getApplication();  
   }  
   private static ValueBinding getValueBinding(String el) {  
     return getApplication().createValueBinding(el);  
   }  
   public static HttpServletRequest getRequest() {  
     return (HttpServletRequest) FacesContext.getCurrentInstance()  
                         .getExternalContext()  
                         .getRequest();  
   }  
   public static HttpServletResponse getResponse() {  
     return (HttpServletResponse) FacesContext.getCurrentInstance()  
                         .getExternalContext()  
                         .getResponse();  
   }  
   public static HttpSession getSession() {  
     return (HttpSession) FacesContext.getCurrentInstance()  
                         .getExternalContext()  
                         .getSession(false);  
   }  
   private static Object getElValue(String el) {  
     return getValueBinding(el).getValue(FacesContext.getCurrentInstance());  
   }  
   private static String getJsfEl(String value) {  
     return "#{" + value + "}";  
   }  
 }  

sexta-feira, 6 de novembro de 2009

<h:inputTextarea> maxlength

É pessoal ... fui usar o tal do
   <h:inputTextarea>
... e precisava setar o maxlength e me deparei com um problema grave !!! ... não tem maxlength no   <h:inputTextarea> :( .
Pesquisei ... achei uma pancada de coisa falando para usar
   <f:validateLength maximum="4000" />
, mas mesmo assim nao funcionou como o esperado ! Tinha q mexer no arquivo de mensagem .. traduzir ... etc ... etc ... e como diria o tio san : time is money ! Ohhhhh yeah ! foi ai q resolvi usando uma coisa simples ... q a maioria dos desenvolvedores esquecem quando estão usando java ( esquece pq a maioria vai ficando louco com o tempo ! ) e usei o seguinte codigo :
   <h:inputTextarea onkeyup="this.value = this.value.substring(0, 4000);" />
funcionou tao bem q ate me escorreu uma lagrima de alegria ! hauehuaeh ...

então fica ai a dica ...
:D