Java Code Examples for javax.naming.Context

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/.

Source file: DB.java

  19 
vote

/** 
 * Opens a connection from JNDI based on a registered name. This assumes that there is a <code>jndi.properties</code> file with proper JNDI configuration in it.
 * @param jndiName name of a configured data source. 
 */
public void open(String jndiName){
  checkExistingConnection(dbName);
  try {
    Context ctx=new InitialContext();
    DataSource ds=(DataSource)ctx.lookup(jndiName);
    Connection connection=ds.getConnection();
    ConnectionsAccess.attach(dbName,connection);
  }
 catch (  Exception e) {
    throw new InitException(e);
  }
}
 

Example 2

From project agile, under directory /agile-framework/src/main/java/org/apache/naming/.

Source file: ContextBindings.java

  19 
vote

/** 
 * Binds a naming context to a thread.
 * @param name Name of the context
 * @param token Security token
 */
public static void bindThread(Object name,Object token) throws NamingException {
  if (ContextAccessController.checkSecurityToken(name,token)) {
    Context context=(Context)contextNameBindings.get(name);
    if (context == null)     throw new NamingException(sm.getString("contextBindings.unknownContext",name));
    threadBindings.put(Thread.currentThread(),context);
    threadNameBindings.put(Thread.currentThread(),name);
  }
}
 

Example 3

From project arquillian-container-glassfish, under directory /glassfish-embedded-3.1/src/test/java/org/jboss/arquillian/container/glassfish/embedded_3_1/app/.

Source file: AsAdminCommandTestCase.java

  18 
vote

@Test public void shouldBeAbleToIssueAsAdminCommand() throws Exception {
  Assert.assertNotNull("Verify that the asadmin CommandRunner resource is available",commandRunner);
  CommandResult result=commandRunner.run("create-jdbc-connection-pool","--datasourceclassname=org.apache.derby.jdbc.EmbeddedXADataSource","--restype=javax.sql.XADataSource","--property=portNumber=1527:password=APP:user=APP" + ":serverName=localhost:databaseName=my_database" + ":connectionAttributes=create\\=true","my_derby_pool");
  Assert.assertEquals("Verify 'create-jdbc-connection-pool' asadmin command",ExitStatus.SUCCESS,result.getExitStatus());
  result=commandRunner.run("create-jdbc-resource","--connectionpoolid","my_derby_pool","jdbc/my_database");
  Assert.assertEquals("Verify 'create-jdbc-resource' asadmin command",ExitStatus.SUCCESS,result.getExitStatus());
  result=commandRunner.run("ping-connection-pool","my_derby_pool");
  Assert.assertEquals("Verify asadmin command 'ping-connection-pool'",ExitStatus.SUCCESS,result.getExitStatus());
  Context ctx=new InitialContext();
  DataSource myDatabase=(DataSource)ctx.lookup("jdbc/my_database");
  Assert.assertNotNull(myDatabase);
}
 

Example 4

From project arquillian-container-jbossas, under directory /jbossas-embedded-6/src/main/java/org/jboss/arquillian/container/jbossas/embedded_6/.

Source file: JBossASEmbeddedContainer.java

  18 
vote

private void initDeploymentManager() throws Exception {
  Context ctx=createContext();
  profileService=(ProfileService)ctx.lookup("ProfileService");
  deploymentManager=profileService.getDeploymentManager();
  ProfileKey defaultKey=new ProfileKey(DEFAULT_PROFILE_KEY_NAME);
  deploymentManager.loadProfile(defaultKey);
}
 

Example 5

From project arquillian-core, under directory /container/test-impl-base/src/test/java/org/jboss/arquillian/container/test/impl/enricher/resource/.

Source file: InitialContextProviderTestCase.java

  18 
vote

@Test public void shouldBeAbleToInjectContextQualified() throws Exception {
  Context contextZ=new InitialContext();
  Context contextX=new InitialContext();
  ContextClassQualifed test=execute(ContextClassQualifed.class,Context.class,contextZ,contextX);
  Assert.assertEquals(contextX,test.context);
}
 

Example 6

From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/core/lifecycle/.

Source file: PersistenceTestTrigger.java

  18 
vote

private DataSource loadDataSource(String dataSourceName){
  try {
    final Context context=contextInstance.get();
    if (context == null) {
      throw new ContextNotAvailableException("No Naming Context available.");
    }
    return (DataSource)context.lookup(dataSourceName);
  }
 catch (  NamingException e) {
    throw new DataSourceNotFoundException("Unable to find data source for given name: " + dataSourceName,e);
  }
}
 

Example 7

From project arquillian_deprecated, under directory /containers/jbossas-embedded-6/src/main/java/org/jboss/arquillian/container/jbossas/embedded_6/.

Source file: JBossASEmbeddedContainer.java

  18 
vote

private void initDeploymentManager() throws Exception {
  String profileName=configuration.getProfileName();
  Context ctx=createContext();
  profileService=(ProfileService)ctx.lookup("ProfileService");
  deploymentManager=profileService.getDeploymentManager();
  ProfileKey defaultKey=new ProfileKey(profileName);
  deploymentManager.loadProfile(defaultKey);
}
 

Example 8

From project blacktie, under directory /jatmibroker-xatmi/src/main/java/org/jboss/narayana/blacktie/jatmibroker/core/transport/.

Source file: JtsTransactionImple.java

  18 
vote

/** 
 * Lookup the JTA transaction manager
 * @return the JTA transaction manager in the VM
 * @throws NamingException
 */
private synchronized static TransactionManager getTransactionManager() throws NamingException {
  if (tm == null) {
    Context ctx=new InitialContext();
    tm=(TransactionManager)ctx.lookup("java:/TransactionManager");
  }
  return tm;
}
 

Example 9

From project capedwarf-green, under directory /javax-cache/src/main/java/org/jboss/capedwarf/cache/infinispan/tx/.

Source file: JBossAS7TransactionManagerLookup.java

  18 
vote

public TransactionManager getTransactionManager() throws Exception {
  Context context=new InitialContext();
  try {
    Object lookup=context.lookup("java:jboss/TransactionManager");
    return TransactionManager.class.cast(lookup);
  }
  finally {
    context.close();
  }
}
 

Example 10

From project components, under directory /bean/src/main/java/org/switchyard/component/bean/deploy/.

Source file: BeanDeploymentMetaData.java

  18 
vote

private static BeanManager getCDIBeanManager(String jndiLocation){
  Context javaComp=getJavaComp(jndiLocation);
  if (javaComp != null) {
    try {
      return (BeanManager)javaComp.lookup("BeanManager");
    }
 catch (    NamingException e) {
      return null;
    }
  }
 else {
    return null;
  }
}
 

Example 11

From project core_1, under directory /test/src/main/java/org/switchyard/test/mixins/.

Source file: CDIMixIn.java

  18 
vote

@Override public void initialize(){
  super.initialize();
  _weld=new Weld();
  _weldContainer=_weld.initialize();
  _weldContainer.event().select(ContainerInitialized.class).fire(new ContainerInitialized());
  try {
    Context ctx=(Context)new InitialContext().lookup(BINDING_CONTEXT);
    ctx.rebind(BEAN_MANAGER_NAME,getBeanManager());
  }
 catch (  NamingException e) {
    e.printStackTrace();
    Assert.fail("Failed to bind BeanManager into '" + BINDING_CONTEXT + "'.");
  }
}
 

Example 12

From project drools-chance, under directory /drools-informer/human-task-helpers/src/main/java/org/jbpm/task/.

Source file: HumanTaskServiceLookup.java

  18 
vote

public static TaskService lookup(){
  try {
    Context initCtx=new InitialContext();
    Context envCtx=(Context)initCtx.lookup("java:comp/env");
    TaskService service=(TaskService)envCtx.lookup("bean/HumanTaskService");
    System.out.println("GETTING JNDI TASK SERVICE INSTANCE = " + service);
    return service;
  }
 catch (  NamingException ne) {
    System.err.println(ne.getMessage());
    return null;
  }
}
 

Example 13

From project droolsjbpm-integration, under directory /drools-camel/src/test/java/org/drools/camel/component/.

Source file: BatchTest.java

  18 
vote

protected Context createJndiContext() throws Exception {
  Context context=super.createJndiContext();
  GridImpl grid=new GridImpl(new HashMap());
  node=grid.createGridNode("node");
  node.set("ksession1",this.exec);
  context.bind("node",node);
  return context;
}
 

Example 14

From project ehour, under directory /eHour-standalone/src/main/java/net/rrm/ehour/.

Source file: EhourServer.java

  18 
vote

private void registerJndiDS(ServerConfig config) throws IOException, NamingException {
  DataSource dataSource=createDataSource(config);
  Context context;
  context=new InitialContext();
  Context compCtx=(Context)context.lookup("java:comp");
  Context envCtx=compCtx.createSubcontext("env");
  NamingUtil.bind(envCtx,"jdbc/eHourDS",dataSource);
}
 

Example 15

From project gatein-naming, under directory /src/main/java/org/gatein/naming/.

Source file: InMemoryNamingStore.java

  18 
vote

private void fireEvent(final ContextNode contextNode,final Name name,final Binding existingBinding,final Binding newBinding,final int type,final String changeInfo){
  final NamingEventCoordinator coordinator=eventCoordinator;
  if (eventCoordinator != null) {
    final Context context=Context.class.cast(contextNode.binding.getObject());
    if (context instanceof EventContext) {
      coordinator.fireEvent(EventContext.class.cast(context),name,existingBinding,newBinding,type,changeInfo,NamingEventCoordinator.DEFAULT_SCOPES);
    }
  }
}
 

Example 16

From project geronimo-xbean, under directory /xbean-naming/src/main/java/org/apache/xbean/naming/context/.

Source file: AbstractContext.java

  18 
vote

public Context createSubcontext(Name name) throws NamingException {
  if (!modifiable)   throw new OperationNotSupportedException("Context is read only");
  if (name == null)   throw new NullPointerException("name is null");
  if (name.isEmpty()) {
    throw new NameAlreadyBoundException("Cannot create a subcontext if the name is empty");
  }
  Context abstractContext=createNestedSubcontext(name.toString(),Collections.EMPTY_MAP);
  addDeepBinding(name,abstractContext,false,false);
  return abstractContext;
}
 

Example 17

From project AdServing, under directory /modules/server/adserver/src/main/java/net/mad/ads/server/utils/listener/configuration/.

Source file: AdServerModule.java

  17 
vote

private void initTracking(BaseContext context){
  try {
    String classname=RuntimeContext.getProperties().getProperty(AdServerConstants.CONFIG.PROPERTIES.TRACKINGSERVICE_CLASS,"");
    TrackingService trackService=(TrackingService)Class.forName(classname).newInstance();
    if (trackService instanceof H2TrackingService) {
      Context ctx=new InitialContext();
      ctx=(Context)ctx.lookup("java:comp/env");
      DataSource ds=(DataSource)ctx.lookup("jdbc/trackingds");
      context.put(TrackingContextKeys.EMBEDDED_TRACKING_DATASOURCE,ds);
    }
    trackService.open(context);
    bind(TrackingService.class).toInstance(trackService);
  }
 catch (  NamingException se) {
    logger.error("",se);
  }
catch (  ClassCastException cce) {
    logger.error("",cce);
  }
catch (  ServiceException e) {
    logger.error("",e);
  }
catch (  InstantiationException e) {
    logger.error("",e);
  }
catch (  IllegalAccessException e) {
    logger.error("",e);
  }
catch (  ClassNotFoundException e) {
    logger.error("",e);
  }
}
 

Example 18

From project agraph-java-client, under directory /src/test/web/.

Source file: AGExampleServletContextListener.java

  17 
vote

@Override public void contextDestroyed(ServletContextEvent event){
  Closer c=new Closer();
  try {
    Context initCtx=c.closeLater(new InitialContext());
    Context envCtx=(Context)c.closeLater(initCtx.lookup("java:comp/env"));
    AGConnPool pool=(AGConnPool)envCtx.lookup("connection-pool/agraph");
    pool.close();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
 finally {
    c.close();
  }
}
 

Example 19

From project c3p0, under directory /src/java/com/mchange/v2/c3p0/jboss/.

Source file: C3P0PooledDataSource.java

  17 
vote

private void rebind(String unbindName) throws NamingException {
  InitialContext ictx=new InitialContext();
  if (unbindName != null)   ictx.unbind(unbindName);
  if (jndiName != null) {
    Name name=ictx.getNameParser(jndiName).parse(jndiName);
    Context ctx=ictx;
    for (int i=0, max=name.size() - 1; i < max; i++) {
      try {
        ctx=ctx.createSubcontext(name.get(i));
      }
 catch (      NameAlreadyBoundException ignore) {
        ctx=(Context)ctx.lookup(name.get(i));
      }
    }
    ictx.rebind(jndiName,combods);
  }
}
 

Example 20

From project capedwarf-blue, under directory /appidentity/src/main/java/org/jboss/capedwarf/appidentity/.

Source file: CDIListener.java

  17 
vote

protected BeanManager getBeanManager(){
  Context nc=null;
  try {
    nc=new InitialContext();
    return (BeanManager)nc.lookup(STANDARD_BEAN_MANAGER_JNDI_NAME);
  }
 catch (  Exception e) {
    log.warning("Cannot find BeanManager: " + e);
    return null;
  }
 finally {
    if (nc != null) {
      try {
        nc.close();
      }
 catch (      NamingException ignored) {
      }
    }
  }
}
 

Example 21

From project cipango, under directory /cipango-plus/src/main/java/org/cipango/plus/sipapp/.

Source file: SipResourceDecorator.java

  17 
vote

public void bindSipResources() throws Exception {
  ClassLoader oldLoader=Thread.currentThread().getContextClassLoader();
  Thread.currentThread().setContextClassLoader(_context.getWebAppContext().getClassLoader());
  Context context=new InitialContext();
  Context compCtx;
  try {
    compCtx=(Context)context.lookup("java:comp/env");
  }
 catch (  NameNotFoundException e) {
    compCtx=((Context)context.lookup("java:comp")).createSubcontext("env");
  }
  Context sipCtx;
  try {
    sipCtx=(Context)compCtx.lookup("sip");
  }
 catch (  NameNotFoundException e) {
    sipCtx=(Context)compCtx.createSubcontext("sip");
  }
  if (!"/".equals(_name) && !"".equals(_name)) {
    sipCtx.createSubcontext(_name);
    compCtx.bind(JNDI_SIP_PREFIX + _name + JNDI_SIP_FACTORY_POSTFIX,_context.getSipFactory());
    compCtx.bind(JNDI_SIP_PREFIX + _name + JNDI_TIMER_SERVICE_POSTFIX,_context.getTimerService());
    compCtx.bind(JNDI_SIP_PREFIX + _name + JNDI_SIP_SESSIONS_UTIL_POSTFIX,_context.getSipSessionsUtil());
  }
 else {
    compCtx.bind(JNDI_SIP_PREFIX + JNDI_SIP_FACTORY_POSTFIX.substring(1),_context.getSipFactory());
    compCtx.bind(JNDI_SIP_PREFIX + JNDI_TIMER_SERVICE_POSTFIX.substring(1),_context.getTimerService());
    compCtx.bind(JNDI_SIP_PREFIX + JNDI_SIP_SESSIONS_UTIL_POSTFIX.substring(1),_context.getSipSessionsUtil());
  }
  LOG.debug("Bind SIP Resources on app " + _name);
  Thread.currentThread().setContextClassLoader(oldLoader);
}
 

Example 22

From project core_4, under directory /impl/src/main/java/org/richfaces/application/configuration/.

Source file: ConfigurationServiceImpl.java

  17 
vote

private String getWebEnvironmentEntryValue(ConfigurationItem configurationItem){
  Context context=null;
  try {
    context=new InitialContext();
  }
 catch (  Throwable e) {
    if (!webEnvironmentUnavailableLogged.getAndSet(true)) {
      LOGGER.error(e.getMessage(),e);
    }
  }
  if (context != null) {
    for (    String envName : configurationItem.names()) {
      String qualifiedName;
      if (!envName.startsWith(JNDI_COMP_PREFIX)) {
        qualifiedName=JNDI_COMP_PREFIX + envName;
      }
 else {
        qualifiedName=envName;
      }
      String value=null;
      try {
        value=(String)context.lookup(qualifiedName);
      }
 catch (      NamingException e) {
        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug(e.getMessage(),e);
        }
      }
      if (!Strings.isNullOrEmpty(value)) {
        return value;
      }
    }
  }
  return null;
}
 

Example 23

From project datasalt-utils, under directory /src/contrib/java/org/apache/solr/core/.

Source file: SolrResourceLoader.java

  17 
vote

/** 
 * Finds the solrhome based on looking up the value in one of three places: <ol> <li>JNDI: via java:comp/env/solr/home</li> <li>The system property solr.solr.home</li> <li>Look in the current working directory for a solr/ directory</li>  </ol> The return value is normalized.  Normalization essentially means it ends in a trailing slash.
 * @return A normalized solrhome
 * @see #normalizeDir(String)
 */
public static String locateSolrHome(){
  String home=null;
  try {
    Context c=new InitialContext();
    home=(String)c.lookup("java:comp/env/" + project + "/home");
    log.info("Using JNDI solr.home: " + home);
  }
 catch (  NoInitialContextException e) {
    log.info("JNDI not configured for " + project + " (NoInitialContextEx)");
  }
catch (  NamingException e) {
    log.info("No /" + project + "/home in JNDI");
  }
catch (  RuntimeException ex) {
    log.warn("Odd RuntimeException while testing for JNDI: " + ex.getMessage());
  }
  if (home == null) {
    String prop=project + ".solr.home";
    home=System.getProperty(prop);
    if (home != null) {
      log.info("using system property " + prop + ": "+ home);
    }
  }
  if (home == null) {
    home=project + '/';
    log.info(project + " home defaulted to '" + home+ "' (could not find system property or JNDI)");
  }
  return normalizeDir(home);
}
 

Example 24

From project des, under directory /daemon/lib/apache-log4j-1.2.16/contribs/Jamie Tsao/.

Source file: JMSQueueAppender.java

  17 
vote

/** 
 * Overriding this method to activate the options for this class i.e. Looking up the Connection factory ...
 */
public void activateOptions(){
  QueueConnectionFactory queueConnectionFactory;
  try {
    Context ctx=getInitialContext();
    queueConnectionFactory=(QueueConnectionFactory)ctx.lookup(queueConnectionFactoryBindingName);
    queueConnection=queueConnectionFactory.createQueueConnection();
    queueSession=queueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
    Queue queue=(Queue)ctx.lookup(queueBindingName);
    queueSender=queueSession.createSender(queue);
    queueConnection.start();
    ctx.close();
  }
 catch (  Exception e) {
    errorHandler.error("Error while activating options for appender named [" + name + "].",e,ErrorCode.GENERIC_FAILURE);
  }
}
 

Example 25

From project fedora-client, under directory /fedora-client-messaging/src/main/java/com/yourmediashelf/fedora/client/messaging/.

Source file: JMSManager.java

  17 
vote

protected Context getContext() throws MessagingException {
  try {
    InitialContext initCtx;
    if (jndiProps != null) {
      return new InitialContext(jndiProps);
    }
    initCtx=new InitialContext();
    Context envCtx=(Context)initCtx.lookup("java:comp/env");
    if (logger.isDebugEnabled()) {
      logger.debug("InitalContext properties:");
      logger.debug("----------------");
      Hashtable<?,?> props=initCtx.getEnvironment();
      Set<?> keys=props.keySet();
      for (      Object key : keys) {
        logger.debug(key.toString() + "=" + props.get(key));
      }
      logger.debug("java:comp/env context properties:");
      logger.debug("----------------");
      props=envCtx.getEnvironment();
      keys=props.keySet();
      for (      Object key : keys) {
        logger.debug(key.toString() + "=" + props.get(key));
      }
      logger.debug("----------------");
    }
    return envCtx;
  }
 catch (  Exception e) {
    logger.error("getContext() failed with: " + e.getMessage());
    throw new MessagingException(e.getMessage(),e);
  }
}
 

Example 26

From project GoFleetLSServer, under directory /configuration/src/main/java/org/gofleet/configuration/.

Source file: Configuration.java

  17 
vote

protected AbstractConfiguration getConfiguration(){
  if (configuration == null) {
    configuration=new CompositeConfiguration();
    try {
      if (dataSource != null && dataSource.isAccessToUnderlyingConnectionAllowed() && !dataSource.isClosed())       configuration.addConfiguration(new DatabaseConfiguration(dataSource,"configuration","key","value"));
    }
 catch (    Throwable t) {
      log.error("Error loading database configuration",t);
    }
    try {
      configuration.addConfiguration(new JNDIConfiguration(new InitialContext()));
    }
 catch (    Throwable t) {
      log.error("Error loading jndi configuration",t);
    }
    try {
      final PropertiesConfiguration configurator=new PropertiesConfiguration();
      InitialContext icontext=new InitialContext();
      Context context=(Context)icontext.lookup("java:comp/env");
      NamingEnumeration<NameClassPair> propiedadesJDNI=context.list("");
      while (propiedadesJDNI.hasMoreElements()) {
        NameClassPair propiety=propiedadesJDNI.nextElement();
        configurator.addProperty(propiety.getName(),context.lookup(propiety.getName()));
        log.trace("Configuring '" + propiety.getName() + "' as '"+ configurator.getString(propiety.getName().toString())+ "'");
      }
      configuration.addConfiguration(configurator);
    }
 catch (    NamingException e) {
      log.error("Error loading configuration from context: " + e,e);
    }
  }
  return configuration;
}
 

Example 27

From project gemini.web.gemini-web-container, under directory /org.eclipse.gemini.web.tomcat/src/main/java/org/eclipse/gemini/web/tomcat/naming/factory/.

Source file: OsgiServiceFactory.java

  16 
vote

@Override public Object getObjectInstance(Object obj,Name name,Context nameCtx,Hashtable<?,?> environment) throws Exception {
  if (obj instanceof ResourceRef) {
    Reference ref=(Reference)obj;
    String mappedName=null;
    RefAddr mappedNameRefAddr=ref.get(MAPPED_NAME);
    if (mappedNameRefAddr != null) {
      Object mappedNameRefAddrContent=mappedNameRefAddr.getContent();
      if (mappedNameRefAddrContent != null) {
        mappedName=mappedNameRefAddr.getContent().toString();
      }
    }
    if (mappedName != null) {
      return new InitialContext().lookup(OSGI_JNDI_URLSCHEME + mappedName);
    }
  }
  return null;
}
 

Example 28

From project guice-jit-providers, under directory /core/test/com/google/inject/example/.

Source file: JndiProviderClient.java

  16 
vote

public static void main(String[] args) throws CreationException {
  Injector injector=Guice.createInjector(new AbstractModule(){
    protected void configure(){
      bind(Context.class).to(InitialContext.class);
      bind(DataSource.class).toProvider(fromJndi(DataSource.class,"..."));
    }
  }
);
}
 

Example 29

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: BoneCPDataSource.java

  15 
vote

public Object getObjectInstance(Object object,Name name,Context context,Hashtable<?,?> table) throws Exception {
  Reference ref=(Reference)object;
  Enumeration<RefAddr> addrs=ref.getAll();
  Properties props=new Properties();
  while (addrs.hasMoreElements()) {
    RefAddr addr=addrs.nextElement();
    if (addr.getType().equals("driverClassName")) {
      Class.forName((String)addr.getContent());
    }
 else {
      props.put(addr.getType(),addr.getContent());
    }
  }
  BoneCPConfig config=new BoneCPConfig(props);
  return new BoneCPDataSource(config);
}
 

Example 30

From project camel-webinar, under directory /part2/camel-example-eip/src/test/java/org/talend/example/.

Source file: CamelEipLoadBalanceTest.java

  15 
vote

@Override protected Context createJndiContext() throws Exception {
  JndiContext answer=new JndiContext();
  answer.bind("foo",new EchoInputBean());
  answer.bind("bar",new EchoInputBean("WIRETAP"));
  return answer;
}
 

Example 31

From project commons-dbcp-jmx, under directory /jdbc3/src/main/java/org/apache/commons/dbcp/.

Source file: ManagedBasicDataSourceFactory.java

  15 
vote

/** 
 * Create and return a new  {@link org.apache.commons.dbcp.ManagedBasicDataSource} instance.  If no instance can be created, return <code>null</code>instead.
 * @param obj         The possibly null object containing location or reference information that can be used in creating an object.
 * @param name        The name of this object relative to <code>nameCtx</code>.
 * @param nameCtx     The context relative to which the <code>name</code> parameter is specified, or <code>null</code> if <code>name</code> isrelative to the default initial context.
 * @param environment The possibly null environment that is used in creating this object.
 * @throws Exception if an exception occurs creating the instance.
 */
@Override public Object getObjectInstance(Object obj,Name name,Context nameCtx,Hashtable environment) throws Exception {
  if ((obj == null) || !(obj instanceof Reference)) {
    return null;
  }
  Reference ref=(Reference)obj;
  if (!"javax.sql.DataSource".equals(ref.getClassName())) {
    return null;
  }
  Properties properties=new Properties();
  for (int i=0; i < ALL_PROPERTIES.length; i++) {
    String propertyName=ALL_PROPERTIES[i];
    RefAddr ra=ref.get(propertyName);
    if (ra != null) {
      String propertyValue=ra.getContent().toString();
      properties.setProperty(propertyName,propertyValue);
    }
  }
  return createDataSource(properties);
}
 

Example 32

From project conversation, under directory /spi/src/main/java/org/jboss/seam/conversation/api/.

Source file: AbstractManagerObjectFactory.java

  15 
vote

public Object getObjectInstance(Object obj,Name name,Context nameCtx,Hashtable<?,?> environment) throws Exception {
  if (name.endsWith(BEAN_MANAGER)) {
    return getBeanManager();
  }
  return null;
}
 

Example 33

From project core_5, under directory /exo.core.component.ldap/src/main/java/org/exoplatform/services/ldap/impl/.

Source file: LDAPServiceImpl.java

  15 
vote

/** 
 * {@inheritDoc}
 */
public InitialContext getInitialContext() throws NamingException {
  Hashtable<String,String> props=new Hashtable<String,String>(env);
  props.put(Context.OBJECT_FACTORIES,"com.sun.jndi.ldap.obj.LdapGroupFactory");
  props.put(Context.STATE_FACTORIES,"com.sun.jndi.ldap.obj.LdapGroupFactory");
  return new InitialLdapContext(props,null);
}
 

Example 34

From project crash, under directory /shell/core/src/main/java/org/crsh/util/.

Source file: Safe.java

  15 
vote

public static void close(Context rs){
  if (rs != null) {
    try {
      rs.close();
    }
 catch (    NamingException ignore) {
    }
  }
}
 

Example 35

From project dcm4che, under directory /dcm4che-conf/dcm4che-conf-ldap/src/main/java/org/dcm4che/conf/ldap/.

Source file: LdapDicomConfiguration.java

  15 
vote

@SuppressWarnings("unchecked") public LdapDicomConfiguration(Hashtable<?,?> env) throws ConfigurationException {
  try {
    env=(Hashtable<?,?>)env.clone();
    String s=(String)env.get(Context.PROVIDER_URL);
    int end=s.lastIndexOf('/');
    ((Hashtable<Object,Object>)env).put(Context.PROVIDER_URL,s.substring(0,end));
    this.baseDN=s.substring(end + 1);
    this.ctx=new InitialDirContext(env);
  }
 catch (  Exception e) {
    throw new ConfigurationException(e);
  }
}
 

Example 36

From project doorkeeper, under directory /core/src/main/java/net/dataforte/doorkeeper/account/provider/ldap/.

Source file: LdapAccountProvider.java

  15 
vote

@Override public User authenticate(AuthenticatorToken token) throws AuthenticatorException {
  LdapContext ctx=null;
  LdapContext ctx2=null;
  PasswordAuthenticatorToken passwordToken=(PasswordAuthenticatorToken)token;
  try {
    LdapEntry entry=loadInternal(token);
    if (entry == null) {
      return null;
    }
 else {
      Hashtable<String,String> authEnv=new Hashtable<String,String>(env);
      authEnv.put(Context.SECURITY_PRINCIPAL,entry.dn);
      authEnv.put(Context.SECURITY_CREDENTIALS,passwordToken.getPassword());
      authEnv.put(COM_SUN_JNDI_LDAP_CONNECT_POOL,"false");
      ctx=new InitialLdapContext(authEnv,null);
      if (useTls) {
        StartTlsResponse tls=(StartTlsResponse)ctx.extendedOperation(new StartTlsRequest());
        tls.negotiate();
      }
      ctx2=(LdapContext)ctx.lookup(entry.dn);
      if (log.isDebugEnabled()) {
        log.debug("Authenticated successfully user " + passwordToken.getPrincipalName());
      }
      cache.put(passwordToken.getPrincipalName(),entry);
      return entry2user(passwordToken.getPrincipalName(),entry);
    }
  }
 catch (  Exception e) {
    log.error("Error during LDAP authentication",e);
    throw new AuthenticatorException(e);
  }
 finally {
    closeContexts(ctx2,ctx);
  }
}
 

Example 37

From project EasyBan, under directory /src/uk/org/whoami/easyban/util/.

Source file: DNSBL.java

  15 
vote

public DNSBL() throws NamingException {
  StringBuilder dnsServers=new StringBuilder("");
  List nameservers=ResolverConfiguration.open().nameservers();
  for (  Object dns : nameservers) {
    dnsServers.append("dns://").append(dns).append(" ");
  }
  Hashtable env=new Hashtable();
  env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.dns.DnsContextFactory");
  env.put("com.sun.jndi.dns.timeout.initial","4000");
  env.put("com.sun.jndi.dns.timeout.retries","1");
  env.put(Context.PROVIDER_URL,dnsServers.toString());
  ictx=new InitialDirContext(env);
}
 

Example 38

From project Empire, under directory /sql/src/com/clarkparsia/empire/sql/.

Source file: DSContext.java

  15 
vote

public void init() throws NamingException {
  System.setProperty(Context.INITIAL_CONTEXT_FACTORY,getContextFactoryName());
  System.setProperty(Context.PROVIDER_URL,getProviderUrl());
  setInitialContext(new InitialContext());
  Reference ref=new Reference("javax.sql.DataSource",getDataSourceFactory(),null);
  ref.add(new StringRefAddr("driverClassName",getConfig().getDriver()));
  ref.add(new StringRefAddr("url",getConfig().getUrl()));
  ref.add(new StringRefAddr("username",getConfig().getUser()));
  ref.add(new StringRefAddr("password",getConfig().getPassword()));
  ref.add(new StringRefAddr("defaultAutoCommit",getConfig().getAutocommit()));
  ref.add(new StringRefAddr("maxActive",getConfig().getMaxActive()));
  ref.add(new StringRefAddr("maxIdle",getConfig().getMaxIdle()));
  ref.add(new StringRefAddr("maxWait",getConfig().getMaxWait()));
  ref.add(new StringRefAddr("validationQuery","/* ping */"));
  getInitialContext().rebind(getContextName(),ref);
  setDataSource((DataSource)getInitialContext().lookup(getContextName()));
}
 

Example 39

From project eTrack, under directory /util/org.eclipselabs.etrack.util.security.ldap/src/org/eclipselabs/etrack/util/security/ldap/impl/.

Source file: LdapSecurityService.java

  15 
vote

@Override public boolean authenticate(String id,char[] password){
  String cachedPassword=credentialCache.get(id);
  String encodedPassword=null;
  try {
    encodedPassword=codec.encode(new String(password));
  }
 catch (  EncoderException e1) {
  }
  if (cachedPassword != null && encodedPassword != null && cachedPassword.equals(encodedPassword))   return true;
  Hashtable<String,String> environment=new Hashtable<String,String>();
  environment.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
  environment.put(Context.PROVIDER_URL,url);
  environment.put(Context.SECURITY_AUTHENTICATION,"simple");
  environment.put(Context.SECURITY_PRINCIPAL,id);
  environment.put(Context.SECURITY_CREDENTIALS,new String(password));
  try {
    InitialDirContext context=new InitialDirContext(environment);
    context.close();
    if (encodedPassword != null)     credentialCache.put(id,encodedPassword);
    return true;
  }
 catch (  NamingException e) {
    return false;
  }
}