Package org.boco.seamUtility

Source Code of org.boco.seamUtility.SeamUtility

/***************************************************************************
* Copyright (c) 2004 - 2008  Fabrizio Boco fabboco@users.sourceforge.net  *
*                                                                         *
*                                                                         *
*   This is free software; you can redistribute it and/or                 *
*   modify it under the terms of the GNU Library General Public           *
*   License (version 2.1) as published by the Free Software Foundation    *
*                                                                         *
*   This library  is distributed in the hope that it will be useful,      *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU Library General Public License for more details.                  *
*                                                                         *
*   You should have received a copy of the GNU Library General Public     *
*   License along with this library; see the file COPYING.LIB. If not,    *
*   write to the Free Software Foundation, Inc., 59 Temple Place,         *
*   Suite 330, Boston, MA  02111-1307, USA                                *
*                                                                         *
***************************************************************************/

/**
- $Header: /usr/local/cvslocalrepository/SeamUtility/src/org/boco/seamUtility/SeamUtility.java,v 1.12.4.9 2008/05/27 16:46:32 fab Exp $
- $Author: fab $
- $Revision: 1.12.4.9 $
- $Date: 2008/05/27 16:46:32 $
- $Log: SeamUtility.java,v $
- Revision 1.12.4.9  2008/05/27 16:46:32  fab
- Nuove funzioni per la gestione della CRUD in Popup
-
- Revision 1.12.4.8  2008/05/25 07:51:32  fab
- Inserita funzione removeRelatedValue2 per CRUD in popup
-
- Revision 1.12.4.7  2008/05/23 19:27:19  fab
- *** empty log message ***
-
- Revision 1.12.4.6  2008/05/06 16:39:26  fab
- Ottimizzazione nella isRelationshipToOne
-
- Revision 1.12.4.5  2008/04/22 06:15:26  fab
- *** empty log message ***
-
- Revision 1.12.4.4  2008/04/22 06:14:35  fab
- Aggiornamento indirizzo di posta
-
- Revision 1.12.4.3  2008/04/19 11:14:40  fab
- Aggiornamento riferimenti licenza e documentazione
-
- Revision 1.12.4.2  2008/03/25 11:05:50  fab
- *** empty log message ***
-
- Revision 1.12.4.1  2008/03/05 17:41:19  fab
- *** empty log message ***
-
- Revision 1.12  2008/01/31 17:38:05  fab
- Fix nella convertDouble
-
- Revision 1.11  2008/01/31 17:32:19  fab
- Fix nella convertDouble
-
- Revision 1.10  2008/01/30 09:06:15  fab
- *** empty log message ***
-
- Revision 1.9  2008/01/14 20:19:06  fab
- Inserita la funzione convertDouble
-
- Revision 1.8  2007/12/28 11:13:50  fab
- Inserite funzioni varie
-
- Revision 1.7  2007/12/23 13:09:01  fab
- Modifiche varie per supportare le popup verso relazioni ereditate dal bean padre
-
- Revision 1.6  2007/11/27 07:01:14  fab
- Introdotta nuova funzione displayMessage
-
- Revision 1.5  2007/10/30 14:01:16  fab
- Fix nella getCallingBeanField per la corretta gestione nel caso di bean gestito nella popup
-
- Revision 1.4  2007/10/22 15:45:22  fab
- Aggiornamento documentazione
-
- Revision 1.3  2007/10/08 13:25:49  fab
- Aggiunta la funzione getPathReference
-
- Revision 1.2  2007/10/01 07:55:35  fab
- Inserita la funzione displayMessageFromMessagesProperties
-
- Revision 1.1  2007/09/30 07:45:40  fab
- Nuova versione iniziale del 30/09/2007
-
- Revision 1.33  2007/09/26 06:15:11  fab
- Inserita funzione orderBy per la gestione degli ordinamenti sui campi transient
-
- Revision 1.32  2007/09/04 10:35:04  fab
- Inserite due funzioni:
-
- convertDate
- getMessage
-
- Revision 1.31  2007/07/20 17:01:51  fab
- Fix per SEAM 2
-
- Revision 1.30  2007/07/17 13:52:32  fab
- Inserita la funzione makeGet
-
- Revision 1.29  2007/07/09 05:54:18  fab
- *** empty log message ***
-
- Revision 1.28  2007/06/29 09:56:17  fab
- Fix nella getBeanRelationshipValues
-
- Revision 1.27  2007/06/25 22:06:43  fab
- Fix nelle funzioni
-    addRelatedValue
-    removeAllRelatedValues
- per la corretta ricerca dei metodi del bean padre da utilizzare
- Inserita la funzione existMethod
-
- Revision 1.26  2007/06/23 06:00:29  fab
- Inserita la funzione isRelationshipToOne
-
- Revision 1.25  2007/06/10 06:39:56  fab
- Modifica per conservare nel path id non come Long ma come oggetto generico.
- In questo modo possono essere supportate le chiavi con più campi
-
- Revision 1.24  2007/06/09 10:41:41  fab
- *** empty log message ***
-
- Revision 1.23  2007/05/30 14:18:36  fab
- Corretto mispelling getReferer in getReferrer
-
- Revision 1.22  2007/05/19 09:34:28  dev
- Modifiche varie
-
- Revision 1.21  2007/01/30 13:45:57  dev
- Fix nella path2String
-
- Revision 1.20  2007/01/28 11:01:11  dev
- Fix vari
-
- Revision 1.19  2007/01/07 14:34:29  dev
- Modifiche Dicembre 2006
-
- Revision 1.18  2006/12/30 14:56:17  dev
- Fix vari
-
- Revision 1.17  2006/12/10 16:38:20  dev
- Modifiche per supportate la reingegnerizzazione del generatore
-
- Revision 1.16  2006/12/03 19:07:48  dev
- Fix vari
-
- Revision 1.15  2006/11/27 20:51:18  dev
- Ulteriore fix sulla removeAllRelatedValues
-
- Revision 1.14  2006/11/27 20:26:13  dev
- Fix sulla removeAllRelatedValues
-
- Revision 1.13  2006/11/18 11:45:24  dev
- Fix sulla getReferenceToMaster
- Fix sulla getReferer
- Fix sulla path2String
- Inserita la resetPath
-
- Revision 1.12  2006/11/01 11:00:56  dev
- Fix vari
-
- Revision 1.11  2006/10/14 06:47:11  dev
- Fix vari
-
- Revision 1.10  2006/10/04 11:50:16  dev
- Fix su diverse funzioni. Se il bean conteneva la string get (per es. Oggetto) le funzioni davano i numeri !
-
- Revision 1.9  2006/09/28 09:10:51  dev
- Introdotta la funzione getParameter
-
- Revision 1.8  2006/09/16 16:43:07  dev
- Supporto per la gestione del path delle relazioni Master-Detail
-
- Revision 1.7  2006/09/03 14:30:12  dev
- Modifiche per le relazioni MASTER_DETAIL
-
- Revision 1.6  2006/09/03 12:07:04  dev
- Inseriti metatag cvs
-
**/
package org.boco.seamUtility;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Stack;
import java.util.Vector;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.boco.seamUtility.comparator.GenericFieldComparator;
import org.boco.seamUtility.messages.MessagesLoader;
import org.boco.seamUtility.pathManagement.PathItem;
import org.jboss.seam.contexts.Context;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.faces.FacesMessages;

public class SeamUtility
{

  /**
   * Restituisce la pagina che ha effettuato la chiamata
   */
  public static String getReferrer(FacesContext facesContext)
  {
    HttpServletRequest request;
    String referer;

    if (facesContext == null)
      return null;

    //    System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
    //    System.out.println(facesContext.getExternalContext().getRequest().getClass());
    //    System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");

    request = (HttpServletRequest) facesContext.getExternalContext().getRequest();

    referer = request.getHeader("referer"); // Nel protocollo referrer e' stato erroneamente scritto referer !!

    //    Recuperare il referrer con la tecnica indicata nel codice successivo può essere utilizzato nel portal !   
    //    java.util.Map<String,String> rM = facesContext.getExternalContext().getRequestHeaderMap();
    //    System.out.println("--> "+rM.get("referer"));

    if (referer == null)
      return "";

    //System.out.println("Referer " + referer);

    int idxLastSlash = referer.indexOf("/", 0);
    idxLastSlash = referer.indexOf("/", idxLastSlash + 1);
    idxLastSlash = referer.indexOf("/", idxLastSlash + 1);
    idxLastSlash = referer.indexOf("/", idxLastSlash + 1);

    //return referer.substring(idxLastSlash,referer.length()).replace("seam","jsp");
    return referer.substring(idxLastSlash, referer.length());
  }

  /**
   * Restituisce il parametro di una chiamata
   * <br>
   * Si osservi che la @RequestParameter() viene attivata solo alla creazione del bean che la contiene, quindi
   * se il bean è in una conversazione i parametri non sono aggiornati
   */
  public static String getParameter(FacesContext facesContext, String parameterName)
  {
    HttpServletRequest request;

    request = (HttpServletRequest) facesContext.getExternalContext().getRequest();

    return request.getParameter(parameterName);
  }

  /**
   * 
   * Restituisce la proprieta' del BeanManager corrispondente al bean che ha chiamato la PopUp
   * <br>
   * Si assume che il referer sia nella forma ?
   * 
   */
  public static Field getCallingBeanField(Class beanManagerClass, String referer)
  {
    String beanClassName;
    String beanName;
    Field beanField = null;

    if (referer == null || referer.equals(""))
      return null;

    try
    {
      if (referer.startsWith("/search"))
      {
        beanClassName = referer.substring(8, referer.indexOf(".") - 6);
        beanName = beanClassName.toLowerCase().substring(0, 1) + beanClassName.substring(1, beanClassName.length());
        beanField = beanManagerClass.getDeclaredField(beanName + "Search");
      }
      else
      {
        beanClassName = referer.substring(1, referer.indexOf("."));
        beanName = beanClassName.toLowerCase().substring(0, 1) + beanClassName.substring(1, beanClassName.length());

        if (beanName.indexOf("InPopUp") != -1)
        {
          beanName = beanName.substring(0, beanName.indexOf("InPopUp"));
        }

        beanField = beanManagerClass.getDeclaredField(beanName);
      }

      return beanField;
    }
    catch (StringIndexOutOfBoundsException e)
    {
      System.out.println("-----------------------------------");
      System.out.println("Errore nella getCallingBeanField");
      System.out.println("beanManagerClass " + beanManagerClass);
      System.out.println("referer " + referer);
      System.out.println("Errore: " + e.getMessage());
      System.out.println("-----------------------------------");
      return null;
    }
    catch (SecurityException e)
    {
      return null;
    }
    catch (NoSuchFieldException e)
    {
      System.out.println("-----------------------------------");
      System.out.println("Errore nella getCallingBeanField");
      System.out.println("beanManagerClass " + beanManagerClass);
      System.out.println("referer " + referer);
      System.out.println("Errore: Il campo " + e.getMessage() + " non esiste !!!");
      System.out.println("-----------------------------------");
      return null;
    }
    catch (IllegalArgumentException e)
    {
      return null;
    }
  }

  /**
   * 
   * Restituisce la proprieta' del BeanManager corrispondente al bean che ha chiamato la PopUp
   * <br>
   * Si assume che il referer sia nella forma BeanSourceRelationshipName dove:
   * <br>
   * RelationshipName assume la forma getBeanTarget
   *
   */
  public static Field getCallingBeanField2(Class beanManagerClass, String referer, boolean search)
  {
    Field beanField = null;

    //    String targetBean = beanManagerClass.getSimpleName().substring(0,beanManagerClass.getSimpleName().indexOf("ManagerBean"));   
    //    String beanClassName;

    int popUpIndex = referer.indexOf("/popup/");
    int getIndex = referer.indexOf("get");

    while (getIndex != -1)
    {
      String sourceBeanName = referer.substring(popUpIndex + 7, getIndex);
      String sourceBeanFieldName = makeFirstLetterLowerCase(sourceBeanName);

      if (search)
        sourceBeanFieldName += "Search";
      try
      {
        beanField = beanManagerClass.getDeclaredField(sourceBeanFieldName);

        return beanField;
      }
      catch (SecurityException e)
      {
        return null;
      }
      catch (NoSuchFieldException e)
      {

        getIndex = referer.indexOf("get", getIndex + 1);

        // Verifica se l'attributo appartiene ad una classe padre
        //ClassLoader cl = beanManagerClass.getClassLoader();

        //      try
        //      { 
        //        System.out.println(beanManagerClass.getCanonicalName());
        //       
        //        String packageName = beanManagerClass.getName().substring(0,beanManagerClass.getName().lastIndexOf("."));
        //        packageName = packageName.replace("manager","entity");
        //       
        //        Class beanClass = Class.forName(packageName+"."+beanClassName, true, cl);
        //       
        //        Class superClass = beanClass.getSuperclass();
        //
        //        System.out.println(superClass.getSimpleName());
        //       
        //        beanClassName = superClass.getSimpleName();
        //       
        //        beanName = beanClassName.toLowerCase().substring(0, 1) + beanClassName.substring(1, beanClassName.length());
        //       
        //
        //        System.out.println(beanName);
        //               
        //        beanField = beanManagerClass.getDeclaredField(beanName);
        //
        //        return beanField;
        //      }
        //      catch (ClassNotFoundException e1)
        //      {
        //        e1.printStackTrace();
        //        return null;
        //      }
        //      catch (SecurityException e1)
        //      {
        //        e.printStackTrace();
        //        return null;
        //      }
        //      catch (NoSuchFieldException e1)
        //      {
        //        e.printStackTrace();
        //        return null;
        //      }

      }
      catch (IllegalArgumentException e)
      {
        return null;
      }
    }

    return null;
  }

  /**
   *
   */
  public static String getCallingBean(Class beanManagerClass, String referer)
  {
    String targetBean = beanManagerClass.getSimpleName().substring(0, beanManagerClass.getSimpleName().indexOf("ManagerBean"));
    String beanClassName;

    if (referer.indexOf("_") == -1)
    {
      if (referer.indexOf("get" + targetBean + "PopUp") == -1)
      {
        beanClassName = referer.substring(referer.lastIndexOf("/") + 1, referer.indexOf("get" + targetBean + "sPopUp"));
      }
      else
      {
        beanClassName = referer.substring(referer.lastIndexOf("/") + 1, referer.indexOf("get" + targetBean + "PopUp"));
      }
    }
    else
    {
      beanClassName = referer.substring(referer.lastIndexOf("/") + 1, referer.indexOf("get" + targetBean + "_"));
    }
    // String beanClassName = referer.substring(referer.lastIndexOf("/") + 1, referer.indexOf("get"));

    return beanClassName;
  }

  //  public static List getBeanRelationshipValues(Object bean, String relationshipName)
  //  {
  //    Method m;
  //    try
  //    {
  //      m = bean.getClass().getMethod(relationshipName, (Class[]) null);
  //     
  //      return (List) m.invoke(bean, (Object[]) null);
  //    }
  //    catch (SecurityException e)
  //    {
  //      return null;
  //    }
  //    catch (NoSuchMethodException e)
  //    {
  //      return null;
  //    }
  //    catch (IllegalArgumentException e)
  //    {
  //      return null;
  //    }
  //    catch (IllegalAccessException e)
  //    {
  //      return null;
  //    }
  //    catch (InvocationTargetException e)
  //    {
  //      return null;
  //    }   
  //  }

  /**
   * Restituisce la lista dei bean correlati da una specifica relazione
   * <br>
   * La relazione puo' essere :N o a :1.
   * <br>
   * Nel caso della relazione :1 la lista dei bean correlati e' una lista con un solo elemento
   *  
   *
   */
  public static List getBeanRelationshipValues(Object bean, String referer)
  {
    String relationshipName;

    Method methods[] = bean.getClass().getDeclaredMethods();
    Method m;

    int start = referer.indexOf("get");
    int end = referer.indexOf("PopUp");

    if (start == -1)
      return null;

    if (end == -1)
      return null;

    relationshipName = referer.substring(start, end);

    while (!existMethod(methods, relationshipName))
    {
      start = referer.indexOf("get", start + 1);
      end = referer.indexOf("PopUp", start + 1);

      if (start == -1 || end == -1)
      {
        // Forse il metodo ricercato e' nel padre di questo bean
        if (!bean.getClass().getGenericSuperclass().equals(Object.class) && bean.getClass().getSuperclass() != null)
        {
          methods = bean.getClass().getSuperclass().getDeclaredMethods();

          start = referer.indexOf("get");
          end = referer.indexOf("PopUp");

          if (start == -1)
            return null;

          if (end == -1)
            return null;

          relationshipName = referer.substring(start, end);
        }
      }
      else
        relationshipName = referer.substring(start, end);
    }

    try
    {
      m = bean.getClass().getMethod(relationshipName, (Class[]) null);

      Object obj = m.invoke(bean, (Object[]) null);

      if (obj == null)
        return null;

      if (obj.getClass().getName().contains("PersistentBag") || obj.getClass().getName().contains("Vector"))
      {
        // Relazione :N
        return (List) obj;
      }

      // Relazione :1 - Il singolo item correlato viene inserito in una lista di un solo elemento
      Vector tmp = new Vector();

      tmp.add(obj);

      return tmp;
    }
    catch (SecurityException e)
    {
      return null;
    }
    catch (NoSuchMethodException e)
    {
      return null;
    }
    catch (IllegalArgumentException e)
    {
      return null;
    }
    catch (IllegalAccessException e)
    {
      return null;
    }
    catch (InvocationTargetException e)
    {
      return null;
    }
  }
 
  /**
   * Restituisce la lista dei bean correlati da una specifica relazione
   * <br>
   * La relazione puo' essere :N o a :1.
   * <br>
   * Nel caso della relazione :1 la lista dei bean correlati e' una lista con un solo elemento
   *  
   *
   */
  public static List getRelatedValues(Object bean, String relationshipName)
  {
    Method m;

    try
    {
      m = bean.getClass().getMethod(relationshipName, (Class[]) null);

      Object obj = m.invoke(bean, (Object[]) null);

      if (obj == null)
        return null;

      if (obj.getClass().getName().contains("PersistentBag") || obj.getClass().getName().contains("Vector"))
      {
        // Relazione :N
        return (List) obj;
      }

      // Relazione :1 - Il singolo item correlato viene inserito in una lista di un solo elemento
      Vector tmp = new Vector();

      tmp.add(obj);

      return tmp;
    }
    catch (SecurityException e)
    {
      return null;
    }
    catch (NoSuchMethodException e)
    {
      return null;
    }
    catch (IllegalArgumentException e)
    {
      return null;
    }
    catch (IllegalAccessException e)
    {
      return null;
    }
    catch (InvocationTargetException e)
    {
      return null;
    }
  } 

  /**
   * Consente di recupere un bean non dal db ma dal form che lo contiene
   * @param callingBean
   * @param relationshipName
   * @param bean
   * @return
   */
  public static Object getSelectedBean(Object callingBean, String relationshipName, Object bean)
  {
    List<?> values = SeamUtility.getRelatedValues(callingBean, relationshipName);
   
    if(values == null)
      return null;
   
    if (values.size() == 1)
      return values.get(0);
   
    for(int i=0; i<values.size(); i++)
    {
      if (values.get(i).equals(bean))
        return values.get(i);
    }
   
    return null;
 
  /**
   * Indica se una relazione è :1
   *
   */
  public static boolean isRelationshipToOne(Object bean, String referer)
  {
    int start = referer.lastIndexOf("get");
    int end = referer.lastIndexOf("PopUp");

    if (start == -1 || end == -1)
      return false; // ? Non è corretto

    String relationshipName = referer.substring(start, end);
    Method m;
    try
    {
      m = bean.getClass().getMethod(relationshipName, (Class[]) null);

      if (m.getReturnType().getName().contains("PersistentBag") ||
          m.getReturnType().getName().contains("Vector") ||
          m.getReturnType().getName().contains("List")
        )
      {
        // Relazione :N
        return false;
      }

      return true;
    }
    catch (SecurityException e)
    {
      return false;
    }
    catch (NoSuchMethodException e)
    {
      return false;
    }
    catch (IllegalArgumentException e)
    {
      return false;
    }
  }

  /**
   * Da un bean rimuove tutti valori correlati con un target bean chiamando il metodo
   * <br>
   * Si assume che il referer sia nella forma BeanSourceRelationshipName dove:
   * <br>
   * RelationshipName assume la forma getBeanTarget
   * 
   */
  public static void removeAllRelatedValues(Object bean, String referer)
  {
    Method m = null;
    String relationship;
    String field = "";
    String removeAllMethodName;

    Method methods[] = bean.getClass().getDeclaredMethods();

    try
    {
      int start = referer.indexOf("get");
      int end = referer.indexOf("PopUp");

      if (start == -1)
        return;

      if (end == -1)
        return;

      relationship = referer.substring(start, end);

      while (!existMethod(methods, relationship))
      {
        start = referer.indexOf("get", start + 1);
        end = referer.indexOf("PopUp", start + 1);

        if (start == -1 || end == -1)
        {
          // Forse il metodo ricercato e' nel padre di questo bean
          if (!bean.getClass().getGenericSuperclass().equals(Object.class) && bean.getClass().getSuperclass() != null)
          {
            methods = bean.getClass().getSuperclass().getDeclaredMethods();

            start = referer.indexOf("get");
            end = referer.indexOf("PopUp");

            if (start == -1)
              return;

            if (end == -1)
              return;

            relationship = referer.substring(start, end);
          }
        }
        else
          relationship = referer.substring(start, end);
      }

      field = makeMethod2Field(relationship);

      removeAllMethodName = makeRemoveAll(field);

      m = bean.getClass().getMethod(removeAllMethodName, (Class[]) null);
      m.invoke(bean, (Object[]) null);
    }
    catch (SecurityException e)
    {
      System.out.println("ERRORE SeamUtility " + e.getMessage());
    }
    catch (NoSuchMethodException e)
    {
      removeAllMethodName = makeSet(field);

      try
      {
        for (int i = 0; i < methods.length; i++)
        {
          if (methods[i].getName().equals(removeAllMethodName))
          {
            m = methods[i];
            break;
          }
        }

        Object params[] = new Object[1];
        params[0] = null;

        m.invoke(bean, params);
      }
      catch (SecurityException e1)
      {
        System.out.println("ERRORE SeamUtility " + e1.getMessage());
      }
      catch (IllegalArgumentException e1)
      {
        System.out.println("ERRORE SeamUtility " + e1.getMessage());
      }
      catch (IllegalAccessException e1)
      {
        System.out.println("ERRORE SeamUtility " + e1.getMessage());
      }
      catch (InvocationTargetException e1)
      {
        System.out.println("ERRORE SeamUtility " + e1.getMessage());
      }
    }
    catch (IllegalArgumentException e)
    {
      System.out.println("ERRORE SeamUtility " + e.getMessage());
    }
    catch (IllegalAccessException e)
    {
      System.out.println("ERRORE SeamUtility " + e.getMessage());
    }
    catch (InvocationTargetException e)
    {
      System.out.println("ERRORE SeamUtility " + e.getMessage());
    }
  }

  /**
   * Verifica se un il nome di un metodo e' presente in una lista di metodi
   */
  private static boolean existMethod(Method methods[], String methodName)
  {
    for (Method method : methods)
    {
      if (method.getName().equals(methodName))
        return true;
    }

    return false;
  }

  /**
   * Aggiunge ad un bean un valore correlato di un target bean chiamando il metodo
   *
   */

  //  public static void addRelatedValue(Object bean, String targetBean, Class targetBeanClass, Object targetBeanValue)
  //  {
  //    Method m;
  //    try
  //    {
  //      Class classes[] = new Class[1];
  //      classes[0] = targetBeanClass;
  //     
  //      m = bean.getClass().getMethod("add"+targetBean, classes);
  //     
  //      Object values[] = new Object[1];
  //      values[0] = targetBeanValue;
  //     
  //      m.invoke(bean, values);
  //    }
  //    catch (SecurityException e)
  //    {
  //      ;
  //    }
  //    catch (NoSuchMethodException e)
  //    {
  //      ;
  //    }
  //    catch (IllegalArgumentException e)
  //    {
  //      ;
  //    }
  //    catch (IllegalAccessException e)
  //    {
  //      ;
  //    }
  //    catch (InvocationTargetException e)
  //    {
  //      ;
  //    }   
  //  } 
  /**
   * Aggiunge ad un bean un valore correlato di un target bean 
   * <br>
   * Si assume che il referer sia nella forma BeanSourceRelationshipName dove:
   * <br>
   * RelationshipName assume la forma getBeanTarget
   * <br>
   * La funzione chiama:
   * <br>
   * addBeanTarget se il target bean e' correlato da una relazione :N
   * <br>
   * setBeanTarget se il target bean e' correlato da una relazione :1
   *  
   */
  public static void addRelatedValue(Object bean, String referer, Class targetBeanClass, Object targetBeanValue)
  {
    Method m;

    Method methods[] = bean.getClass().getDeclaredMethods();

    int start = referer.indexOf("get");
    int end = referer.indexOf("PopUp");

    if (start == -1)
      return;

    String relationshipName = referer.substring(start, end);

    while (!existMethod(methods, relationshipName))
    {
      start = referer.indexOf("get", start + 1);
      end = referer.indexOf("PopUp", start + 1);

      if (start == -1 || end == -1)
      {
        // Forse il metodo ricercato e' nel padre di questo bean
        if (!bean.getClass().getGenericSuperclass().equals(Object.class) && bean.getClass().getSuperclass() != null)
        {
          methods = bean.getClass().getSuperclass().getDeclaredMethods();

          start = referer.indexOf("get");
          end = referer.indexOf("PopUp");

          if (start == -1)
            return;

          if (end == -1)
            return;

          relationshipName = referer.substring(start, end);
        }
      }
      else
        relationshipName = referer.substring(start, end);
    }

    try
    {
      Class classes[] = new Class[1];
      classes[0] = targetBeanClass;

      // Prende il metodo della relazione per stabilire la cardinalita'
      m = bean.getClass().getMethod(relationshipName, (Class[]) null);

      String returningClass = m.getReturnType().getName();

      if (returningClass.contains("List"))
      {
        // La relazione è di tipo :N

        String field = makeMethod2Field(relationshipName);

        // String targetBean = relationshipName.substring(3, relationshipName.length() - 1);

        m = bean.getClass().getMethod(makeAdd(field), classes);
      }
      else
      {
        // La relazione è di tipo :1

        String targetBean = relationshipName.substring(3, relationshipName.length());

        m = bean.getClass().getMethod("set" + targetBean, classes);
      }

      Object values[] = new Object[1];
      values[0] = targetBeanValue;

      m.invoke(bean, values);
    }
    catch (SecurityException e)
    {
      ;
    }
    catch (NoSuchMethodException e)
    {
      ;
    }
    catch (IllegalArgumentException e)
    {
      ;
    }
    catch (IllegalAccessException e)
    {
      ;
    }
    catch (InvocationTargetException e)
    {
      ;
    }
  }

  /**
   * Aggiunge ad un bean un valore correlato di un target bean 
   * <br>
   * La funzione chiama:
   * <br>
   * addBeanTarget se il target bean e' correlato da una relazione :N
   * <br>
   * setBeanTarget se il target bean e' correlato da una relazione :1
   *  
   */
  public static void addRelatedValue2(Object bean, String relationshipName, Class targetBeanClass, Object targetBeanValue)
  {
    Method m;

    Method methods[] = bean.getClass().getDeclaredMethods();

    try
    {
      Class classes[] = new Class[1];
      classes[0] = targetBeanClass;

      // Prende il metodo della relazione per stabilire la cardinalita'
      m = bean.getClass().getMethod(relationshipName, (Class[]) null);

      String returningClass = m.getReturnType().getName();

      if (returningClass.contains("List"))
      {
        // La relazione è di tipo :N

        String field = makeMethod2Field(relationshipName);

        // String targetBean = relationshipName.substring(3, relationshipName.length() - 1);

        m = bean.getClass().getMethod(makeAdd(field), classes);
      }
      else
      {
        // La relazione è di tipo :1

        String targetBean = relationshipName.substring(3, relationshipName.length());

        m = bean.getClass().getMethod("set" + targetBean, classes);
      }

      Object values[] = new Object[1];
      values[0] = targetBeanValue;

      m.invoke(bean, values);
    }
    catch (SecurityException e)
    {
      e.printStackTrace();
    }
    catch (NoSuchMethodException e)
    {
      e.printStackTrace();
    }
    catch (IllegalArgumentException e)
    {
      e.printStackTrace();
    }
    catch (IllegalAccessException e)
    {
      e.printStackTrace();
    }
    catch (InvocationTargetException e)
    {
      e.printStackTrace();
    }
  }

 
  /**
   * Rimuove da un bean un valore correlato di un target bean 
   * <br>
   * @throws ClassNotFoundException
   */
  public static void removeRelatedValue2(Object bean, String relationshipName, Class targetBeanClass, Object targetBeanValue)
  {
    Method m;

    Method methods[] = bean.getClass().getDeclaredMethods();

    try
    {
      Class classes[] = new Class[1];     
      classes[0] = targetBeanClass;

      // Prende il metodo della relazione per stabilire la cardinalita'
      m = bean.getClass().getMethod(relationshipName, (Class[]) null);

      String returningClass = m.getReturnType().getName();

      if (returningClass.contains("List"))
      {
        // La relazione è di tipo :N

        String field = makeMethod2Field(relationshipName);

        m = bean.getClass().getMethod(makeRemove(field), classes);
       
        Object values[] = new Object[1];
        values[0] = targetBeanValue;

        m.invoke(bean, values);       
      }
      else
      {
        // La relazione è di tipo :1

        String targetBean = relationshipName.substring(3, relationshipName.length());

        m = bean.getClass().getMethod("set" + targetBean, classes);
        Object values[] = new Object[1];
        values[0] = null;

        m.invoke(bean, values);       
      }

    }
    catch (SecurityException e)
    {
      e.printStackTrace();
    }
    catch (NoSuchMethodException e)
    {
      e.printStackTrace();
    }
    catch (IllegalArgumentException e)
    {
      e.printStackTrace();
    }
    catch (IllegalAccessException e)
    {
      e.printStackTrace();
    }
    catch (InvocationTargetException e)
    {
      e.printStackTrace();
    }
  } 
  /**
   * Restituisce la proprieta' del BeanManager corrispondente al bean master
   * <br>
   * Il referer si assume nella forma
   * <br>
   * /list/MasterBeanList.seam 
   */
  public static Field getMasterBeanField(Class beanManagerClass, String referer)
  {
    if (!referer.contains("List"))
      return null;

    String beanClassName = referer.substring(referer.lastIndexOf("/") + 1, referer.indexOf("List"));
    String beanName = beanClassName.toLowerCase().substring(0, 1) + beanClassName.substring(1, beanClassName.length());

    Field beanField = null;

    try
    {
      beanField = beanManagerClass.getDeclaredField(beanName);

      return beanField;
    }
    catch (SecurityException e)
    {
      return null;
    }
    catch (NoSuchFieldException e)
    {
      return null;
    }
    catch (IllegalArgumentException e)
    {
      return null;
    }

  }

  /**
   * Dato un nome di bean gestisce il percorso in modo oppurtuno
   *
   */
  public static void updateMasterDetailPath(String thisBeanName, String label, Object id)
  {
    // Context session = Contexts.getSessionContext();
    Context conversation = Contexts.getConversationContext();

    if (!conversation.isSet("path"))
    {
      // Non esiste ancora

      Stack<PathItem> path = new Stack<PathItem>();

      path.push(new PathItem(thisBeanName, label, id));

      conversation.set("path", path);
    }
    else
    {
      // Esiste

      Stack<PathItem> path = (Stack<PathItem>) conversation.get("path");

      if (path.contains(new PathItem(thisBeanName, label, null)))
      {
        PathItem item = path.peek();

        while (!path.peek().getBeanName().equals(thisBeanName))
        {
          path.pop();
        }

        path.pop();
        path.push(new PathItem(thisBeanName, label, id));
      }
      else
      {
        path.push(new PathItem(thisBeanName, label, id));
      }

      conversation.set("path", path);
    }
  }

  /**
   * Elimina l'ultimo item del path se corrispnde al bean indicato
   */
  public static void removeLastPathItem(String thisBeanName)
  {
    Context conversation = Contexts.getConversationContext();
    Stack<PathItem> path = (Stack<PathItem>) conversation.get("path");

    if (path == null)
      return;

    PathItem lastItem = path.peek();

    if (lastItem.getBeanName().equals(thisBeanName))
    {
      path.pop();
      conversation.set("path", path);
    }
  }

  /**
   * Restituisce il riferimento al master
   */
  public static PathItem getReferenceToMaster()
  {
    // Context session = Contexts.getSessionContext();
    Context conversation = Contexts.getConversationContext();
    Stack<PathItem> path = (Stack<PathItem>) conversation.get("path");
    PathItem ret;

    if ((path != null) && (path.size() >= 1))
    {
      /** Se la lunghezza del path è maggiore di 2 significa che il path è composto almeno da master -> detail **/
      /** Il riferimento al master è nell'ultimo elemento **/
      ret = path.get(path.size() - 1);
    }
    else
    {
      /** Il percorso contiene solo un detail e quindi non esiste un riferimento al master **/
      ret = new PathItem("", "", null);
    }

    return ret;
  }

  /**
   *
   * Restituisce il riferimento ad un bean del path risaendo all'indietro di pos posizioni 
   * <br>
   * <br>
   * Es.:
   * <br>
   * <br>
   * pos = 0 Ultimo elemento del path - Equivale a getReferenceToMaster
   * <br>
   * <br>
   * pos = 1 Penultimo elemento del path
   * 
   */
  public static PathItem getPathReference(int pos)
  {
    // Context session = Contexts.getSessionContext();
    Context conversation = Contexts.getConversationContext();
    Stack<PathItem> path = (Stack<PathItem>) conversation.get("path");
    PathItem ret;

    if ((path != null) && (path.size() >= 1))
    {
      /** Se la lunghezza del path è maggiore di 2 significa che il path è composto almeno da master -> detail **/
      /** Il riferimento al master è nell'ultimo elemento **/
      ret = path.get(path.size() - 1 - pos);
    }
    else
    {
      /** Il percorso contiene solo un detail e quindi non esiste un riferimento al master **/
      ret = new PathItem("", "", null);
    }

    return ret;
  }

  /**
   * Resetta il path
   */
  public static void resetPath()
  {
    //Context session = Contexts.getSessionContext();
    Context session = Contexts.getConversationContext();

    session.remove("path");
  }

  /**
   * Restituisce il path come stringa da visualizzare
   */
  public static String path2String()
  {
    String ret = "";

    // Context session = Contexts.getSessionContext();

    Context session = Contexts.getConversationContext();

    Stack<PathItem> path = (Stack<PathItem>) session.get("path");

    for (int i = 0; i < path.size(); i++)
    {
      //if (i>=1 && i<path.size()-1)
      if (i >= 1 && i <= path.size())
        ret += " -> ";

      ret += path.get(i).getLabel();
    }

    return ret;
  }

  public static String getParameterFromReferer(String referer, String parameterName)
  {
    String ret = "";
    int start;
    int end;

    start = referer.indexOf(parameterName);
    if (start == -1)
      return null;

    end = referer.indexOf("&", start + 1);
    if (end == -1)
      end = referer.length();

    return referer.substring(start + parameterName.length() + 1, end);
  }

  public static String makeFirstLetterUpperCase(String in)
  {
    String tmp = in.toUpperCase();

    return tmp.substring(0, 1) + in.substring(1, in.length());
  }

  public static String makeFirstLetterLowerCase(String in)
  {
    String tmp = in.toLowerCase();

    return tmp.substring(0, 1) + in.substring(1, in.length());
  }

  /**
   * Dato un metodo get<Field> o set<Field> restituisce <Field>
   *
   *
   */
  public static String makeMethod2Field(String getMethod)
  {
    return makeFirstLetterLowerCase(getMethod.substring(3, getMethod.length()));
  }

  /**
   * Dato un campo <Field> restituisce il metodo
   *
   * add<Field>
   *
   */
  public static String makeAdd(String field)
  {
    String tmp = field.toUpperCase();
    String tmp1 = tmp.substring(0, 1);

    return "add" + tmp1 + field.substring(1);
  }

  /**
   * Dato un campo <Field> restituisce il metodo
   *
   * set<Field>
   *
   */
  public static String makeSet(String field)
  {
    String tmp = field.toUpperCase();
    String tmp1 = tmp.substring(0, 1);

    return "set" + tmp1 + field.substring(1);
  }

  /**
   * Dato un campo <Field> restituisce il metodo
   *
   * get<Field>
   *
   */
  public static String makeGet(String field)
  {
    String tmp = field.toUpperCase();
    String tmp1 = tmp.substring(0, 1);

    return "get" + tmp1 + field.substring(1);
  }

  /**
   * Dato un campo <Field> restituisce il metodo
   *
   * removeAll<Field>
   *
   */
  public static String makeRemoveAll(String field)
  {
    String tmp = field.toUpperCase();
    String tmp1 = tmp.substring(0, 1);

    return "removeAll" + tmp1 + field.substring(1);
  }

  /**
   * Dato un campo <Field> restituisce il metodo
   *
   * remove<Field>
   *
   */
  public static String makeRemove(String field)
  {
    String tmp = field.toUpperCase();
    String tmp1 = tmp.substring(0, 1);

    return "remove" + tmp1 + field.substring(1);
  }

  /**
   *
   * Converte una data nel formato indicato
   *
   */
  public static String convertDate(Date date, String format)
  {
    SimpleDateFormat dateFormat = new SimpleDateFormat(format);

    if (date == null)
      return null;

    return dateFormat.format(date);
  }

  public static Date parseToDate(String sDate, String format) throws ParseException
  {
    SimpleDateFormat dateFormat = new SimpleDateFormat(format);

    if (sDate == null)
      return null;

    return dateFormat.parse(sDate);
  }

  /**
   * Converte un double in una stringa formattata
   */
  public static String convertDouble(Double doubleValue)
  {
    DecimalFormat doubleFormatter = new DecimalFormat("#,##0.00;");

    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    dfs.setDecimalSeparator(',');
    dfs.setGroupingSeparator('.');

    doubleFormatter.setDecimalFormatSymbols(dfs);

    if (doubleValue == null)
      return null;

    return doubleFormatter.format(doubleValue);
  }

  /** Restituisce il contenuto di una message string **/
  public static String getMessage(FacesContext facesContext, String key)
  {
    return MessagesLoader.getMessageResourceString(facesContext.getApplication().getMessageBundle(), key, null, facesContext.getViewRoot().getLocale());
  }

  /**
   * Funzione per l'ordinamento senza utilizzare le clausole EJBQL
   * <br>
   * Necessaria per i campi Transient
   */
  public static List orderBy(List asseList, String field, GenericFieldComparator.OrderType orderType)
  {
    Object tmp[] = asseList.toArray();

    java.util.Arrays.sort(tmp, new GenericFieldComparator(field, orderType));

    return new Vector(java.util.Arrays.asList(tmp));
  }

  /**
   * Inserisce un messaggio di segnalazione nella pagina
    *
   * @param facesContext
   * @param severity
   * @param key
   */
  public static void displayMessageFromMessagesProperties(FacesContext facesContext, FacesMessage.Severity severity, String key)
  {
    String msg = getMessage(facesContext, key);

    FacesMessage message = new FacesMessage();
    message.setDetail(msg);
    message.setSummary(msg);
    message.setSeverity(severity);

    FacesMessages.instance().clear();
    FacesMessages.instance().add(message);
  }

  /**
   * Inserisce un messaggio di segnalazione nella pagina
    *
   * @param facesContext
   * @param severity
   * @param msg
   */
  public static void displayMessage(FacesContext facesContext, FacesMessage.Severity severity, String msg)
  {
    FacesMessage message = new FacesMessage();
    message.setDetail(msg);
    message.setSummary(msg);
    message.setSeverity(severity);

    FacesMessages.instance().clear();
    FacesMessages.instance().add(message);
  }

  /**
   * Dato un bean ed il nome di un bean master, restituisce true se possono esistere
   * piu' master per lo stesso detail
   * <br>
   * @param bean
   * @param masterBeanName
   * @return
   */
  public static boolean moreMasters(Object bean, String masterBeanName)
  {
    Method methods[] = bean.getClass().getDeclaredMethods();

    String methodName = makeGet(masterBeanName) + "s";

    for (Method m : methods)
    {
      if (m.getName().equals(methodName))
        return true;
    }

    return false;
  }
}
TOP

Related Classes of org.boco.seamUtility.SeamUtility

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.