javax.naming.Context#close ( )源码实例Demo

下面列出了javax.naming.Context#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: oodt   文件: ExecServer.java
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) {
		}
	  }
	}
}
 
源代码2 项目: AsuraFramework   文件: JNDIConnectionProvider.java
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) {}
                }
            }
        }
    }
 
源代码3 项目: spring-ldap   文件: DefaultDirObjectFactory.java
@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
			}

		}
	}
}
 
源代码4 项目: spring4-understanding   文件: JndiTemplate.java
/**
 * 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);
		}
	}
}
 
源代码5 项目: tomee   文件: MovieTest.java
@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();
    }
}
 
源代码6 项目: spring-analysis-note   文件: JndiTemplate.java
/**
 * 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);
		}
	}
}
 
源代码7 项目: lams   文件: JndiTemplate.java
/**
 * 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);
		}
	}
}
 
源代码8 项目: ironjacamar   文件: TransactionManagerImpl.java
/**
 * Stop
 * @exception Throwable Thrown if an error occurs
 */
public void stop() throws Throwable
{
   Context context = new InitialContext();

   context.unbind(JNDI_NAME);

   context.close();
}
 
源代码9 项目: AsuraFramework   文件: JNDIConnectionProvider.java
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) {}
        }
    }
}
 
源代码10 项目: lams   文件: UserTransactionImpl.java
/**
 * Stop
 * @exception Throwable Thrown if an error occurs
 */
public void stop() throws Throwable
{
   Context context = new InitialContext();

   context.unbind(JNDI_NAME);

   context.close();
}
 
源代码11 项目: openjdk-jdk9   文件: AppletIsNotUsed.java
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");
}
 
源代码12 项目: lams   文件: JNDIConnectionProvider.java
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) {}
        }
    }
}
 
源代码13 项目: submarine   文件: EmbeddedLdapRuleTest.java
@Test
public void testContextClose() throws Exception {
  final Context context = embeddedLdapRule.context();
  context.close();
  assertNotNull(context.getNameInNamespace());
}
 
源代码14 项目: ironjacamar   文件: JndiBinder.java
/**
 * 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
         }
      }
   }
}
 
源代码15 项目: ironjacamar   文件: JNPStrategy.java
/**
 * {@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
         }
      }
   }
}
 
源代码16 项目: ironjacamar   文件: JNPStrategy.java
/**
 * {@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
         }
      }
   }
}
 
源代码17 项目: tomee   文件: DynamicDataSourceTest.java
@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();
}
 
源代码18 项目: lams   文件: ExplicitJndiStrategy.java
/**
 * {@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;
}
 
源代码19 项目: lams   文件: SimpleJndiStrategy.java
/**
 * {@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};
}
 
源代码20 项目: lams   文件: SimpleJndiStrategy.java
/**
 * {@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};
}