GestoreJNDI.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */



  20. package org.openspcoop2.utils.resources;

  21. import java.util.Map;
  22. import java.util.concurrent.ConcurrentHashMap;

  23. import javax.naming.Context;
  24. import javax.naming.InitialContext;
  25. import javax.naming.NameNotFoundException;

  26. import org.openspcoop2.utils.SemaphoreLock;
  27. import org.openspcoop2.utils.UtilsException;
  28. import org.slf4j.Logger;

  29. /**
  30.  * Classe dove sono forniti metodi per effettuare operazioni sull'albero JNDI
  31.  *
  32.  *
  33.  * @author Poli Andrea (apoli@link.it)
  34.  * @author $Author$
  35.  * @version $Rev$, $Date$
  36.  */

  37. public class GestoreJNDI {

  38.     private java.util.Properties contextProperties;

  39.        
  40.     /**
  41.      * Costruttore
  42.      *
  43.      * @param contextP Proprieta' del contesto JNDI
  44.      */
  45.     public GestoreJNDI(java.util.Properties contextP){
  46.         this.contextProperties = contextP;
  47.     }
  48.     /**
  49.      * Costruttore
  50.      *
  51.      */
  52.     public GestoreJNDI(){
  53.         this.contextProperties = new java.util.Properties();
  54.     }

  55.    
  56.     private static org.openspcoop2.utils.Semaphore semaphore = new org.openspcoop2.utils.Semaphore("GestoreJNDI");
  57.     private static Map<String, Object> localTreeJNDI = new ConcurrentHashMap<>();
  58.     public static final String LOCAL_TREE_JNDI_PREFIX = "local:/openspcoop2/";


  59.     /**
  60.      * Ritorna l'oggetto registrato nell'albero JNDI con nome <var>fullPath</var>, se presente.
  61.      *
  62.      * @param fullPath Nome dell'oggetto da ricercare nell'albero JNDI
  63.      */
  64.     public Object lookup(String fullPath) throws UtilsException {
  65.        
  66.         if(fullPath!=null && fullPath.startsWith(LOCAL_TREE_JNDI_PREFIX)){
  67.        
  68.             /**System.out.println("-------------------------------- LOCAL LOOKUP ["+fullPath+"]");*/
  69.            
  70.             Object o = null;
  71.             SemaphoreLock lock = semaphore.acquireThrowRuntime("lookup");
  72.             try {
  73.                 o = localTreeJNDI.get(fullPath);
  74.             }finally {
  75.                 semaphore.release(lock, "lookup");
  76.             }
  77.             if(o==null){
  78.                 throw new UtilsException("LocalResource ["+fullPath+"] not found");
  79.             }
  80.             return o;
  81.            
  82.         }
  83.        
  84.         // Inizializzo Contesto
  85.         InitialContext ctx = null;
  86.         try{
  87.             if(this.contextProperties!=null && this.contextProperties.size() > 0){
  88.                 ctx = new InitialContext(this.contextProperties);
  89.             }else{
  90.                 ctx = new InitialContext();
  91.             }
  92.             // Lookup Object
  93.             return ctx.lookup(fullPath);
  94.         }catch(Exception e){
  95.             throw new UtilsException(e.getMessage(),e);
  96.         }
  97.         finally{
  98.             try{
  99.                 if(ctx!=null)
  100.                     ctx.close();
  101.             }catch(Exception eClose){
  102.                 // close
  103.             }
  104.         }
  105.     }




  106.     /**
  107.      * Elimina la registrazione di un oggetto con nome JNDI <var>fullPath</var> dall'albero JNDI
  108.      *
  109.      * @param fullPath Nome dell'oggetto da eliminare nell'albero JNDI
  110.      * @return true se l'eliminazione ha successo, false altrimenti
  111.      */
  112.     public boolean unbind(String fullPath) {
  113.         return unbind(fullPath, null, null);
  114.     }
  115.     public boolean unbind(String fullPath,Logger log) {
  116.         return unbind(fullPath, log, null);
  117.     }
  118.     public boolean unbind(String fullPath,Logger log,Logger logConsole) {
  119.        
  120.         if(fullPath!=null && fullPath.startsWith(LOCAL_TREE_JNDI_PREFIX)){
  121.            
  122.             /**System.out.println("-------------------------------- LOCAL UNBIND ["+fullPath+"]");*/
  123.            
  124.             Object o = null;
  125.             SemaphoreLock lock = semaphore.acquireThrowRuntime("unbind");
  126.             try {
  127.                 o = localTreeJNDI.remove(fullPath);
  128.             }finally {
  129.                 semaphore.release(lock, "unbind");
  130.             }
  131.             String msg = "LocalResource ["+fullPath+"] not found";
  132.             if(log!=null)
  133.                 log.warn(msg);
  134.             if(logConsole!=null)
  135.                 logConsole.warn(msg);
  136.             return o!=null;
  137.            
  138.         }
  139.        
  140.         Context currentContext = null;
  141.         try{
  142.             currentContext = new InitialContext() ;
  143.             final String name = currentContext.composeName(fullPath,currentContext.getNameInNamespace() ) ;
  144.             if(log!=null) {
  145.                 String msg = "Unbind  fullname " + name;
  146.                 log.debug(msg) ;
  147.             }
  148.             try{
  149.                 currentContext.unbind( name ) ;
  150.                 /**System.out.println( "eraser" ) ;*/
  151.             }catch( final NameNotFoundException ignored ){
  152.                 if(log!=null)
  153.                     log.error( "Errore durante l'unbind (Ignored) ["+ignored+"]",ignored);
  154.                 if(logConsole!=null)
  155.                     logConsole.error( "Errore durante l'unbind (Ignored) ["+ignored+"]",ignored);
  156.                 return false;      

  157.             }
  158.             //          L'unbind fatto in questa maniera ricerca il componente sulla "root" dell albero
  159.             //          non sul corretto sottoalbero come dovrebbe
  160.             //          
  161.             /**         final String[] components = name.split( "/" ) ;
  162.             //          for( int ix = components.length-1 ; ix >=0 ; ix-- ){
  163.             //              final String nextPath = components[ix] ;
  164.             //              log.debug( "Unbind  component \"" + nextPath + "\" in context " + currentContext ) ;
  165.             //              try{
  166.             //                  currentContext.unbind( nextPath ) ;
  167.             //                  //System.out.println( "eraser" ) ;
  168.             //              }catch( final NameNotFoundException ignored ){
  169.             //                  log.error( "Errore durante l'unbind (Ignored) ["+ignored+"]",ignored);
  170.             //                  logConsole.error( "Errore durante l'unbind (Ignored) ["+ignored+"]",ignored);
  171.             //                  return false;      
  172.             //                  
  173.             //              }
  174.             //          }*/
  175.             return true;

  176.         }catch(Exception e){
  177.             if(log!=null)
  178.                 log.error( "Errore durante l'unbind ["+e+"]",e);
  179.             if(logConsole!=null)
  180.                 logConsole.error( "Errore durante l'unbind ["+e+"]",e);
  181.             return false;
  182.         }finally{
  183.             try{
  184.                 if(currentContext!=null)
  185.                     currentContext.close();
  186.             }catch(Exception eClose){
  187.                 // close
  188.             }
  189.         }
  190.     }


  191.     /**
  192.      * Effettua la registrazione di un oggetto con nome JNDI <var>fullPath</var> nell'albero JNDI
  193.      *
  194.      * @param fullPath Nome dell'oggetto da registrare nell'albero JNDI
  195.      * @return true se l'eliminazione ha successo, false altrimenti
  196.      */
  197.     public boolean bind(String fullPath,Object toBind) {
  198.         return bind(fullPath, toBind, null, null);
  199.     }
  200.     public boolean bind(String fullPath,Object toBind,Logger log) {
  201.         return bind(fullPath, toBind, log, null);
  202.     }
  203.     public boolean bind(String fullPath,Object toBind,Logger log,Logger logConsole) {
  204.        
  205.         if(fullPath!=null && fullPath.startsWith(LOCAL_TREE_JNDI_PREFIX)){
  206.            
  207.             /**System.out.println("-------------------------------- LOCAL BIND ["+fullPath+"]");*/
  208.            
  209.             SemaphoreLock lock = semaphore.acquireThrowRuntime("bind");
  210.             try {
  211.                
  212.                 if(localTreeJNDI.containsKey(fullPath)){
  213.                     String msg = "LocalResource ["+fullPath+"] already exists";
  214.                     if(log!=null)
  215.                         log.warn(msg);
  216.                     if(logConsole!=null)
  217.                         logConsole.warn(msg);
  218.                     return false;
  219.                 }
  220.                
  221.                 localTreeJNDI.put(fullPath, toBind);
  222.                 return true;
  223.             }finally {
  224.                 semaphore.release(lock, "bind");
  225.             }
  226.            
  227.         }
  228.        
  229.        
  230.         Context currentContext = null;
  231.         try{

  232.             /**System.out.println("Attempting to bind object " + toBind + " to context path \"" + fullPath + "\"" ) ;*/

  233.             currentContext = new InitialContext() ;
  234.             final String name = currentContext.composeName(fullPath,currentContext.getNameInNamespace() ) ;
  235.             final String[] components = name.split( "/" ) ;

  236.             // the last item in the array refers to the object itself.
  237.             // we don't want to create a (sub)Context for that; we
  238.             // want to bind the object to it
  239.             final int stop = components.length - 1 ;        
  240.             for( int ix = 0 ; ix < stop ; ++ix ){
  241.                 final String nextPath = components[ix] ;
  242.                 /**System.out.println( "Looking up subcontext named \"" + nextPath + "\" in context " + currentContext ) ;*/
  243.                 try{
  244.                     currentContext = (Context) currentContext.lookup( nextPath ) ;
  245.                     /**System.out.println( "found" ) ;*/
  246.                 }catch( final NameNotFoundException ignored ){
  247.                     /**System.out.println( "not found; creating subcontext" ) ;*/
  248.                     currentContext = currentContext.createSubcontext( nextPath ) ;
  249.                     /**System.out.println( "done" ) ;*/            
  250.                 }  
  251.             }

  252.             // by this point, we've built up the entire context path leading up
  253.             // to the desired bind point... so we can bind the object itself
  254.             currentContext.bind( components[stop] , toBind ) ;
  255.             String msg = "binding ["+fullPath+"] to " + currentContext;
  256.             if(log!=null)
  257.                 log.info(msg) ;
  258.             if(logConsole!=null)
  259.                 logConsole.info(msg) ;

  260.             return true;

  261.         }catch(Exception e){
  262.             if(log!=null)
  263.                 log.error( "Errore durante il bind ["+e+"]",e);
  264.             if(logConsole!=null)
  265.                 logConsole.error( "Errore durante il bind ["+e+"]",e);
  266.             return false;
  267.         }   finally{
  268.             try{
  269.                 if(currentContext!=null)
  270.                     currentContext.close();
  271.             }catch(Exception eClose){
  272.                 // close
  273.             }
  274.         }
  275.     }

  276. }