Java Code Examples for javax.naming.Context#close()

The following examples show how to use javax.naming.Context#close() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: oodt   File: ExecServer.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
	while (shouldKeepBinding()) {
	  try {
		Context objectContext = configuration.getObjectContext();
		objectContext.rebind(name, server.getServant());
		objectContext.close();
	  } catch (Exception ex) {
		System.err.println("Exception binding at " + new Date() + "; will keep trying...");
		ex.printStackTrace();
	  } finally {
		try {
		  Thread.sleep(REBIND_PERIOD);
		} catch (InterruptedException ignore) {
		}
	  }
	}
}
 
Example 2
private void init() {

        if (!isAlwaysLookup()) {
            Context ctx = null;
            try {
                ctx = (props != null) ? new InitialContext(props) : new InitialContext(); 

                datasource = (DataSource) ctx.lookup(url);
            } catch (Exception e) {
                getLog().error(
                        "Error looking up datasource: " + e.getMessage(), e);
            } finally {
                if (ctx != null) {
                    try { ctx.close(); } catch(Exception ignore) {}
                }
            }
        }
    }
 
Example 3
@Override
public final Object getObjectInstance(
           Object obj,
           Name name,
           Context nameCtx,
           Hashtable<?, ?> environment,
           Attributes attrs) throws Exception {

	try {
		String nameInNamespace;
		if (nameCtx != null) {
			nameInNamespace = nameCtx.getNameInNamespace();
		}
		else {
			nameInNamespace = "";
		}

		return constructAdapterFromName(attrs, name, nameInNamespace);
	}
	finally {
		// It seems that the object supplied to the obj parameter is a
		// DirContext instance with reference to the same Ldap connection as
		// the original context. Since it is not the same instance (that's
		// the nameCtx parameter) this one really needs to be closed in
		// order to correctly clean up and return the connection to the pool
		// when we're finished with the surrounding operation.
		if (obj instanceof Context) {

			Context ctx = (Context) obj;
			try {
				ctx.close();
			}
			catch (Exception e) {
				// Never mind this
			}

		}
	}
}
 
Example 4
/**
 * Release a JNDI context as obtained from {@link #getContext()}.
 * @param ctx the JNDI context to release (may be {@code null})
 * @see #getContext
 */
public void releaseContext(Context ctx) {
	if (ctx != null) {
		try {
			ctx.close();
		}
		catch (NamingException ex) {
			logger.debug("Could not close JNDI InitialContext", ex);
		}
	}
}
 
Example 5
Source Project: tomee   File: MovieTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAsEmployee() throws Exception {
    final Context context = getContext("eddie", "jump");

    try {
        movies.addMovie(new Movie("Quentin Tarantino", "Reservoir Dogs", 1992));
        movies.addMovie(new Movie("Joel Coen", "Fargo", 1996));
        movies.addMovie(new Movie("Joel Coen", "The Big Lebowski", 1998));

        List<Movie> list = movies.getMovies();
        Assert.assertEquals("List.size()", 3, list.size());

        for (Movie movie : list) {
            try {
                movies.deleteMovie(movie);
                Assert.fail("Employees should not be allowed to delete");
            } catch (EJBAccessException e) {
                // Good, Employees cannot delete things
            }
        }

        // The list should still be three movies long
        Assert.assertEquals("Movies.getMovies()", 3, movies.getMovies().size());
    } finally {
        context.close();
    }
}
 
Example 6
Source Project: spring-analysis-note   File: JndiTemplate.java    License: MIT License 5 votes vote down vote up
/**
 * Release a JNDI context as obtained from {@link #getContext()}.
 * @param ctx the JNDI context to release (may be {@code null})
 * @see #getContext
 */
public void releaseContext(@Nullable Context ctx) {
	if (ctx != null) {
		try {
			ctx.close();
		}
		catch (NamingException ex) {
			logger.debug("Could not close JNDI InitialContext", ex);
		}
	}
}
 
Example 7
Source Project: lams   File: JndiTemplate.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Release a JNDI context as obtained from {@link #getContext()}.
 * @param ctx the JNDI context to release (may be {@code null})
 * @see #getContext
 */
public void releaseContext(Context ctx) {
	if (ctx != null) {
		try {
			ctx.close();
		}
		catch (NamingException ex) {
			logger.debug("Could not close JNDI InitialContext", ex);
		}
	}
}
 
Example 8
/**
 * Stop
 * @exception Throwable Thrown if an error occurs
 */
public void stop() throws Throwable
{
   Context context = new InitialContext();

   context.unbind(JNDI_NAME);

   context.close();
}
 
Example 9
public Connection getConnection() throws SQLException {
    Context ctx = null;
    try {
        Object ds = this.datasource;

        if (ds == null || isAlwaysLookup()) {
            ctx = (props != null) ? new InitialContext(props): new InitialContext(); 

            ds = ctx.lookup(url);
            if (!isAlwaysLookup()) {
                this.datasource = ds;
            }
        }

        if (ds == null) {
            throw new SQLException( "There is no object at the JNDI URL '" + url + "'");
        }

        if (ds instanceof XADataSource) {
            return (((XADataSource) ds).getXAConnection().getConnection());
        } else if (ds instanceof DataSource) { 
            return ((DataSource) ds).getConnection();
        } else {
            throw new SQLException("Object at JNDI URL '" + url + "' is not a DataSource.");
        }
    } catch (Exception e) {
        this.datasource = null;
        throw new SQLException(
                "Could not retrieve datasource via JNDI url '" + url + "' "
                        + e.getClass().getName() + ": " + e.getMessage());
    } finally {
        if (ctx != null) {
            try { ctx.close(); } catch(Exception ignore) {}
        }
    }
}
 
Example 10
/**
 * Stop
 * @exception Throwable Thrown if an error occurs
 */
public void stop() throws Throwable
{
   Context context = new InitialContext();

   context.unbind(JNDI_NAME);

   context.close();
}
 
Example 11
private static void testWith(String appletProperty) throws NamingException {
    Hashtable<Object, Object> env = new Hashtable<>();
    // Deliberately put java.lang.Object rather than java.applet.Applet
    // if an applet was used we would see a ClassCastException down there
    env.put(appletProperty, new Object());
    // It's ok to instantiate InitialContext with no parameters
    // and be unaware of it right until you try to use it
    Context ctx = new InitialContext(env);
    boolean threw = true;
    try {
        ctx.lookup("whatever");
        threw = false;
    } catch (NoInitialContextException e) {
        String m = e.getMessage();
        if (m == null || m.contains("applet"))
            throw new RuntimeException("The exception message is incorrect", e);
    } catch (Throwable t) {
        throw new RuntimeException(
                "The test was supposed to catch NoInitialContextException" +
                        " here, but caught: " + t.getClass().getName(), t);
    } finally {
        ctx.close();
    }

    if (!threw)
        throw new RuntimeException("The test was supposed to catch NoInitialContextException here");
}
 
Example 12
public Connection getConnection() throws SQLException {
    Context ctx = null;
    try {
        Object ds = this.datasource;

        if (ds == null || isAlwaysLookup()) {
            ctx = (props != null) ? new InitialContext(props): new InitialContext(); 

            ds = ctx.lookup(url);
            if (!isAlwaysLookup()) {
                this.datasource = ds;
            }
        }

        if (ds == null) {
            throw new SQLException( "There is no object at the JNDI URL '" + url + "'");
        }

        if (ds instanceof XADataSource) {
            return (((XADataSource) ds).getXAConnection().getConnection());
        } else if (ds instanceof DataSource) { 
            return ((DataSource) ds).getConnection();
        } else {
            throw new SQLException("Object at JNDI URL '" + url + "' is not a DataSource.");
        }
    } catch (Exception e) {
        this.datasource = null;
        throw new SQLException(
                "Could not retrieve datasource via JNDI url '" + url + "' "
                        + e.getClass().getName() + ": " + e.getMessage());
    } finally {
        if (ctx != null) {
            try { ctx.close(); } catch(Exception ignore) {}
        }
    }
}
 
Example 13
Source Project: submarine   File: EmbeddedLdapRuleTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testContextClose() throws Exception {
  final Context context = embeddedLdapRule.context();
  context.close();
  assertNotNull(context.getNameInNamespace());
}
 
Example 14
Source Project: ironjacamar   File: JndiBinder.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Bind
 * @exception Throwable Thrown in case of an error
 */
public void bind() throws Throwable
{
   if (name == null)
      throw new IllegalArgumentException("Name is null");

   if (obj == null)
      throw new IllegalArgumentException("Obj is null");

   if (trace)
      log.trace("Binding " + obj.getClass().getName() + " under " + name);

   Properties properties = new Properties();
   properties.setProperty(Context.PROVIDER_URL, jndiProtocol + "://" + jndiHost + ":" + jndiPort);
   Context context = new InitialContext(properties);

   try
   {
      String className = obj.getClass().getName();
      Reference ref = new Reference(className,
                                    new StringRefAddr("class", className),
                                    JndiBinder.class.getName(),
                                    null);
      ref.add(new StringRefAddr("name", name));

      objs.put(name, obj);

      Util.bind(context, name, ref);

      if (log.isDebugEnabled())
         log.debug("Bound " + obj.getClass().getName() + " under " + name);
   }
   finally
   {
      if (context != null)
      {
         try
         {
            context.close();
         }
         catch (NamingException ne)
         {
            // Ignore
         }
      }
   }
}
 
Example 15
Source Project: ironjacamar   File: JNPStrategy.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void bind(String jndiName, Object o) throws NamingException
{
   if (jndiName == null)
      throw new NamingException();

   if (o == null)
      throw new NamingException();

   Context context = createContext();
   try
   {
      String className = o.getClass().getName();

      if (trace)
         log.trace("Binding " + className + " under " + jndiName);

      Reference ref = new Reference(className,
                                    new StringRefAddr("class", className),
                                    JNPStrategy.class.getName(),
                                    null);
      ref.add(new StringRefAddr("name", jndiName));

      if (objs.putIfAbsent(qualifiedName(jndiName, className), o) != null)
      {
         throw new NamingException(bundle.deploymentFailedSinceJndiNameHasDeployed(className, jndiName));
      }

      if (o instanceof Referenceable)
      {
         Referenceable referenceable = (Referenceable)o;
         referenceable.setReference(ref);
      }
         
      Util.bind(context, jndiName, o);

      if (log.isDebugEnabled())
         log.debug("Bound " + className + " under " + jndiName);
   }
   finally
   {
      if (context != null)
      {
         try
         {
            context.close();
         }
         catch (NamingException ne)
         {
            // Ignore
         }
      }
   }
}
 
Example 16
Source Project: ironjacamar   File: JNPStrategy.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void unbind(String jndiName, Object o) throws NamingException
{
   if (jndiName == null)
      throw new NamingException();

   if (o == null)
      throw new NamingException();

   Context context = createContext();
   try
   {
      String className = o.getClass().getName();

      if (trace)
         log.trace("Unbinding " + className + " under " + jndiName);

      Util.unbind(context, jndiName);

      objs.remove(qualifiedName(jndiName, className));

      if (log.isDebugEnabled())
         log.debug("Unbound " + className + " under " + jndiName);
   }
   catch (Throwable t)
   {
      //log.exceptionDuringUnbind(t);
   }
   finally
   {
      if (context != null)
      {
         try
         {
            context.close();
         }
         catch (NamingException ne)
         {
            // Ignore
         }
      }
   }
}
 
Example 17
Source Project: tomee   File: DynamicDataSourceTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void route() throws Exception {
    String[] databases = new String[]{"database1", "database2", "database3"};

    Properties properties = new Properties();
    properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());

    // resources
    // datasources
    for (int i = 1; i <= databases.length; i++) {
        String dbName = databases[i - 1];
        properties.setProperty(dbName, "new://Resource?type=DataSource");
        dbName += ".";
        properties.setProperty(dbName + "JdbcDriver", "org.hsqldb.jdbcDriver");
        properties.setProperty(dbName + "JdbcUrl", "jdbc:hsqldb:mem:db" + i);
        properties.setProperty(dbName + "UserName", "sa");
        properties.setProperty(dbName + "Password", "");
        properties.setProperty(dbName + "JtaManaged", "true");
    }

    // router
    properties.setProperty("My Router", "new://Resource?provider=org.router:DeterminedRouter&type=" + DeterminedRouter.class.getName());
    properties.setProperty("My Router.DatasourceNames", "database1 database2 database3");
    properties.setProperty("My Router.DefaultDataSourceName", "database1");

    // routed datasource
    properties.setProperty("Routed Datasource", "new://Resource?provider=RoutedDataSource&type=" + DataSource.class.getName());
    properties.setProperty("Routed Datasource.Router", "My Router");

    Context ctx = EJBContainer.createEJBContainer(properties).getContext();
    RoutedPersister ejb = (RoutedPersister) ctx.lookup("java:global/dynamic-datasource-routing/RoutedPersister");
    for (int i = 0; i < 18; i++) {
        // persisting a person on database db -> kind of manual round robin
        String name = "record " + i;
        String db = databases[i % 3];
        ejb.persist(i, name, db);
    }

    // assert database records number using jdbc
    for (int i = 1; i <= databases.length; i++) {
        Connection connection = DriverManager.getConnection("jdbc:hsqldb:mem:db" + i, "sa", "");
        Statement st = connection.createStatement();
        ResultSet rs = st.executeQuery("select count(*) from PERSON");
        rs.next();
        assertEquals(6, rs.getInt(1));
        st.close();
        connection.close();
    }

    ctx.close();
}
 
Example 18
/**
 * {@inheritDoc}
 */
public String[] bindConnectionFactories(String deployment, Object[] cfs, String[] jndis) throws Throwable
{
   if (deployment == null)
      throw new IllegalArgumentException("Deployment is null");

   if (deployment.trim().equals(""))
      throw new IllegalArgumentException("Deployment is empty");

   if (cfs == null)
      throw new IllegalArgumentException("CFS is null");

   if (cfs.length == 0)
      throw new IllegalArgumentException("CFS is empty");

   if (jndis == null)
      throw new IllegalArgumentException("JNDIs is null");

   if (jndis.length == 0)
      throw new IllegalArgumentException("JNDIs is empty");

   if (cfs.length != jndis.length)
      throw new IllegalArgumentException("Number of connection factories doesn't match number of JNDI names");

   Context context = new InitialContext();
   try
   {
      for (int i = 0; i < cfs.length; i++)
      {
         String jndiName = jndis[i];
         Object cf = cfs[i];

         if (log.isTraceEnabled())
            log.tracef("Binding %s under %s", cf.getClass().getName(), jndiName);

         if (cf == null)
            throw new IllegalArgumentException("Connection factory is null");

         if (jndiName == null)
            throw new IllegalArgumentException("JNDI name is null");

         String className = cf.getClass().getName();
         Reference ref = new Reference(className,
                                       new StringRefAddr("class", className),
                                       ExplicitJndiStrategy.class.getName(),
                                       null);
         ref.add(new StringRefAddr("name", jndiName));

         if (objs.putIfAbsent(qualifiedName(jndiName, className), cf) != null)
            throw new Exception(bundle.deploymentFailedSinceJndiNameHasDeployed(className, jndiName));

         Referenceable referenceable = (Referenceable)cf;
         referenceable.setReference(ref);
         
         Util.bind(context, jndiName, cf);

         if (log.isDebugEnabled())
            log.debug("Bound " + cf.getClass().getName() + " under " + jndiName);
      }
   }
   finally
   {
      if (context != null)
      {
         try
         {
            context.close();
         }
         catch (NamingException ne)
         {
            // Ignore
         }
      }
   }

   return jndis;
}
 
Example 19
/**
 * {@inheritDoc}
 */
public String[] bindConnectionFactories(String deployment, Object[] cfs, String[] jndis) throws Throwable
{
   if (deployment == null)
      throw new IllegalArgumentException("Deployment is null");

   if (deployment.trim().equals(""))
      throw new IllegalArgumentException("Deployment is empty");

   if (cfs == null)
      throw new IllegalArgumentException("CFS is null");

   if (cfs.length == 0)
      throw new IllegalArgumentException("CFS is empty");

   if (cfs.length > 1)
      throw new IllegalArgumentException("SimpleJndiStrategy only support " + 
                                         "a single connection factory per deployment");
   if (jndis == null)
      throw new IllegalArgumentException("JNDIs is null");

   if (jndis.length == 0)
      throw new IllegalArgumentException("JNDIs is empty");

   if (jndis.length > 1)
      throw new IllegalArgumentException("SimpleJndiStrategy only support " + 
                                         "a single JNDI name per deployment");

   String jndiName = jndis[0];
   Object cf = cfs[0];

   if (log.isTraceEnabled())
      log.tracef("Binding %s under %s", cf.getClass().getName(), jndiName);
   
   if (cf == null)
      throw new IllegalArgumentException("Connection factory is null");
   
   if (jndiName == null)
      throw new IllegalArgumentException("JNDI name is null");

   Context context = new InitialContext();
   try
   {
      String className = cf.getClass().getName();
      Reference ref = new Reference(className,
                                    new StringRefAddr("class", className),
                                    SimpleJndiStrategy.class.getName(),
                                    null);
      ref.add(new StringRefAddr("name", jndiName));

      if (objs.putIfAbsent(qualifiedName(jndiName, className), cf) != null)
         throw new Exception(bundle.deploymentFailedSinceJndiNameHasDeployed(className, jndiName));

      Referenceable referenceable = (Referenceable)cf;
      referenceable.setReference(ref);

      Util.bind(context, jndiName, cf);

      if (log.isDebugEnabled())
         log.debug("Bound " + cf.getClass().getName() + " under " + jndiName);
   }
   finally
   {
      if (context != null)
      {
         try
         {
            context.close();
         }
         catch (NamingException ne)
         {
            // Ignore
         }
      }
   }

   return new String[] {jndiName};
}
 
Example 20
/**
 * {@inheritDoc}
 */
public String[] bindAdminObjects(String deployment, Object[] aos, String[] jndis) throws Throwable
{
   if (deployment == null)
      throw new IllegalArgumentException("Deployment is null");

   if (deployment.trim().equals(""))
      throw new IllegalArgumentException("Deployment is empty");

   if (aos == null)
      throw new IllegalArgumentException("AOS is null");

   if (aos.length == 0)
      throw new IllegalArgumentException("AOS is empty");

   if (aos.length > 1)
      throw new IllegalArgumentException("SimpleJndiStrategy only support " + 
                                         "a single admin object per deployment");
   if (jndis == null)
      throw new IllegalArgumentException("JNDIs is null");

   if (jndis.length == 0)
      throw new IllegalArgumentException("JNDIs is empty");

   if (jndis.length > 1)
      throw new IllegalArgumentException("SimpleJndiStrategy only support " + 
                                         "a single JNDI name per deployment");

   String jndiName = jndis[0];
   Object ao = aos[0];

   if (log.isTraceEnabled())
      log.tracef("Binding %s under %s", ao.getClass().getName(), jndiName);
   
   if (ao == null)
      throw new IllegalArgumentException("Admin object is null");
   
   if (jndiName == null)
      throw new IllegalArgumentException("JNDI name is null");

   Context context = new InitialContext();
   try
   {
      if (ao instanceof Referenceable)
      {
         String className = ao.getClass().getName();
         Reference ref = new Reference(className,
                                       new StringRefAddr("class", className),
                                       SimpleJndiStrategy.class.getName(),
                                       null);
         ref.add(new StringRefAddr("name", jndiName));

         if (objs.putIfAbsent(qualifiedName(jndiName, className), ao) != null)
            throw new Exception(bundle.deploymentFailedSinceJndiNameHasDeployed(className, jndiName));

         Referenceable referenceable = (Referenceable)ao;
         referenceable.setReference(ref);
      }

      Util.bind(context, jndiName, ao);

      if (log.isDebugEnabled())
         log.debug("Bound " + ao.getClass().getName() + " under " + jndiName);
   }
   finally
   {
      if (context != null)
      {
         try
         {
            context.close();
         }
         catch (NamingException ne)
         {
            // Ignore
         }
      }
   }

   return new String[] {jndiName};
}