Internal method that creates a NamingException that contains helpful
information regarding why a binding failed to resolve. <p>

The returned exception will provide similar information as the
CannotInstantiateObjectException from traditional WAS.
3374
private NamingException newCannotInstantiateObjectException(String name,
                                                                Exception cause) {
        String msgTxt = Tr.formatMessage(tc, "JNDI_CANNOT_INSTANTIATE_OBJECT_CWNEN1001E", name);
        NamingException nex = new NamingException(msgTxt);
        nex.initCause(cause);

        return nex;
    }
563696
private Object tryInitiatingObject(String targetType, String initMethodName, List<Object> fieldObjects)
        throws TransformationOperationException {
        Class<?> targetClass = loadClassByName(targetType);
        try {
            if (initMethodName == null) {
                return initiateByConstructor(targetClass, fieldObjects);
            } else {
                return initiateByMethodName(targetClass, initMethodName, fieldObjects);
            }
        } catch (Exception e) {
            String message = "Unable to create the desired object. The instantiate operation will be ignored.";
            message = String.format(message, targetType);
            getLogger().error(message);
            throw new TransformationOperationException(message, e);
        }
    }
384372
<T> InternalProviderImpl<T> toProvider(Binding<T> binding) {
    if (binding == null) {
      throw new IllegalStateException("null binding are not allowed. Should not happen unless getBindingSet is overridden.");
    }
    ConfigurationHolder.configuration.checkIllegalBinding(binding, this);

    switch (binding.getMode()) {
      case SIMPLE:
        return createInternalProvider(this,
            binding.getKey(),
            false,
            binding.isCreatingInstancesInScope(),
            binding.isCreatingSingletonInScope(),
            false);
      case CLASS:
        return createInternalProvider(this,
            binding.getImplementationClass(),
            false,
            binding.isCreatingInstancesInScope(),
            binding.isCreatingSingletonInScope(),
            false);
      case INSTANCE:
        return new InternalProviderImpl<>(binding.getInstance());
      case PROVIDER_INSTANCE:
        // to ensure providers do not have to deal with concurrency, we wrap them in a thread safe provider
        // We do not need to pass the scope here because the provider won't use any scope to create the instance
        return new InternalProviderImpl<>(binding.getProviderInstance(), binding.isProvidingSingletonInScope());
      case PROVIDER_CLASS:
        return createInternalProvider(this,
            binding.getProviderClass(),
            true,
            binding.isCreatingInstancesInScope(),
            binding.isCreatingSingletonInScope(),
            binding.isProvidingSingletonInScope());
      //JACOCO:OFF
      default:
        throw new IllegalStateException(format("mode is not handled: %s. This should not happen.", binding.getMode()));
        //JACOCO:ON
    }
  }
649688
@Override
    protected void init() throws Exception {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        try {
            PropertyService vProps = new PropertyService();
            NavigableMap<String, Object> wProps = parseConfiguration(properties, vProps);

            // Clone properties so that we can later detect modifications from the current values
            vProps = (PropertyService) vProps.clone();

            String jndiName = (String) wProps.remove(JNDI_NAME);
            String type = (String) wProps.remove(DSConfig.TYPE);

            // Trace some of the most important config settings
            if (trace && tc.isDebugEnabled())
                Tr.debug(this, tc, DATASOURCE, id, jndiName, type);

            // Get the connection manager service for this data source. If none is configured, then use defaults.
            conMgrSvc = (ConnectionManagerService) priv.locateService(componentContext,CONNECTION_MANAGER);

            boolean createdDefaultConnectionManager = false;
            
            if (conMgrSvc == null) {
                if (wProps.containsKey(DSConfig.CONNECTION_MANAGER_REF)) {
                    SQLNonTransientException failure = connectorSvc.ignoreWarnOrFail(tc, null, SQLNonTransientException.class, "MISSING_RESOURCE_J2CA8030",
                                                                                    DSConfig.CONNECTION_MANAGER_REF, "", DATASOURCE, jndiName == null ? id : jndiName);
                    if (failure != null)
                        throw failure;
                }
                conMgrSvc = ConnectionManagerService.createDefaultService(id);
                createdDefaultConnectionManager = true;

            }
            conMgrSvc.addObserver(this);

            // Obtain the data source from the JDBC driver
            // TODO: Switch to org.osgi.service.jdbc.DataSourceFactory for compatibility with OSGI JDBC drivers
            jdbcDriverSvc = (JDBCDriverService) priv.locateService(componentContext,JDBC_DRIVER);

            if (jdbcDriverSvc == null) {
                Tr.error(tc, "DSRA4003.driver.null", jndiName == null ? id : jndiName);

                throw new SQLNonTransientException(ConnectorService.getMessage("MISSING_RESOURCE_J2CA8030", DSConfig.JDBC_DRIVER_REF,
                                                                               "", DATASOURCE, jndiName == null ? id : jndiName));
            }
            jdbcDriverSvc.addObserver(this);

            Object vendorImpl;
            Class<?> ifc;

            if(type == null){
                boolean atLeastJDBC43 = jdbcRuntime.getVersion().compareTo(JDBCRuntimeVersion.VERSION_4_3) >= 0;
                vendorImpl = atLeastJDBC43 || id != null && id.contains("dataSource[DefaultDataSource]")
                                ? jdbcDriverSvc.createAnyPreferXADataSource(vProps, id)
                                : jdbcDriverSvc.createAnyPreferLegacyOrder(vProps, id);
                ifc = vendorImpl instanceof XADataSource ? XADataSource.class
                    : vendorImpl instanceof ConnectionPoolDataSource ? ConnectionPoolDataSource.class
                    : vendorImpl instanceof DataSource ? DataSource.class
                    : Driver.class;
            } else if (ConnectionPoolDataSource.class.getName().equals(type)) {
                ifc = ConnectionPoolDataSource.class;
                vendorImpl = jdbcDriverSvc.createConnectionPoolDataSource(vProps, id);
            } else if (XADataSource.class.getName().equals(type)) {
                ifc = XADataSource.class;
                vendorImpl = jdbcDriverSvc.createXADataSource(vProps, id);
            } else if (DataSource.class.getName().equals(type)) {
                ifc = DataSource.class;
                vendorImpl = jdbcDriverSvc.createDataSource(vProps, id);
            } else if (Driver.class.getName().equals(type)) {
                ifc = Driver.class;
                String url = vProps.getProperty("URL", vProps.getProperty("url"));
                if (url != null && !"".equals(url)) {
                    vendorImpl = jdbcDriverSvc.getDriver(url, vProps, id);
                } else 
                    throw new SQLNonTransientException(AdapterUtil.getNLSMessage("DSRA4014.URL.for.Driver.missing", jndiName == null ? id : jndiName));
            } else
                throw new SQLNonTransientException(ConnectorService.getMessage("MISSING_RESOURCE_J2CA8030", DSConfig.TYPE, type, DATASOURCE, jndiName == null ? id : jndiName));

            // Convert isolationLevel constant name to integer
            vendorImplClassName = vendorImpl.getClass().getName();
            parseIsolationLevel(wProps, vendorImplClassName);
            
            Object objIsolationLevel = wProps.get(DataSourceDef.isolationLevel.name());
            int wIsolationLevel = objIsolationLevel == null ? -1 : (int) objIsolationLevel;
            
            if(wIsolationLevel == Connection.TRANSACTION_NONE) {
                Object objTransactional = wProps.get(DataSourceDef.transactional.name());
                boolean wTransactional = objTransactional == null ? true : (boolean) objTransactional;
                
                if (wTransactional) {
                    throw new SQLException(AdapterUtil.getNLSMessage("DSRA4009.tran.none.transactional.unsupported", id));
                }
            }

            // Derby Embedded needs a reference count so that we can shutdown databases when no longer used.
            isDerbyEmbedded = vendorImplClassName.startsWith("org.apache.derby.jdbc.Embedded");
            if (isDerbyEmbedded) {
                String dbName = (String) vProps.get(DataSourceDef.databaseName.name());
                if (dbName != null) {
                    // Maintaining compatibility here. Variables are no longer normalized by default, but the ResourceFactoryBuilder is still
                    // using VariableRegistry.resolveString() to resolve variables in data source definitions. 
                    dbName = PathUtils.normalize(dbName);
                    embDerbyRefCount.add(dbName);
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(this, tc, "ref count for database shutdown", dbName, embDerbyRefCount);
                }
            }

            isUCP = vendorImplClassName.startsWith("oracle.ucp");
            if (isUCP) {
                if (!createdDefaultConnectionManager && !sentUCPConnMgrPropsIgnoredInfoMessage) {
                    Set<String> connMgrPropsAllowed = Collections.singleton("enableSharingForDirectLookups");
                    Tr.info(tc, "DSRA4013.ignored.connection.manager.config.used", connMgrPropsAllowed);
                    sentUCPConnMgrPropsIgnoredInfoMessage = true;
                }
                updateConfigForUCP(wProps);
            }

            dsConfigRef.set(new DSConfig(id, jndiName, wProps, vProps, connectorSvc));

            WSManagedConnectionFactoryImpl mcfImpl = new WSManagedConnectionFactoryImpl(dsConfigRef, ifc, vendorImpl, jdbcRuntime);

            if (jdbcDriverSvc.loadFromApp()) {
                // data source class loaded from thread context class loader
                mcf = null;
                mcfPerClassLoader = new ConcurrentHashMap<String, WSManagedConnectionFactoryImpl>();
                ClassLoader tccl = priv.getContextClassLoader();
                String identifier = connectorSvc.getClassLoaderIdentifierService().getClassLoaderIdentifier(tccl);
                mcfPerClassLoader.put(identifier, mcfImpl);
            } else {
                // data source class loaded from shared library
                mcf = mcfImpl;
                mcfPerClassLoader = null;
            }

            isInitialized.set(true);
        } catch (Exception x) {
            FFDCFilter.processException(x, getClass().getName(), "587", this);
            // undo any partial initialization
            if (conMgrSvc != null)
                conMgrSvc.deleteObserver(this);
            if (jdbcDriverSvc != null)
                jdbcDriverSvc.deleteObserver(this);
            throw x;
        } catch (Error x) {
            FFDCFilter.processException(x, getClass().getName(), "591", this);
            // undo any partial initialization
            if (conMgrSvc != null)
                conMgrSvc.deleteObserver(this);
            if (jdbcDriverSvc != null)
                jdbcDriverSvc.deleteObserver(this);
            throw x;
        }
    }
682331
public void addTypeBindError(final TypeBindException bindException, final CellPosition address, final String fieldName, final String label) {
        
        this.errors.createFieldConversionError(fieldName, bindException.getBindClass(), bindException.getTargetValue())
            .variables(bindException.getMessageVars())
            .variables("validatedValue", bindException.getTargetValue())
            .address(address)
            .label(label)
            .buildAndAddError();
        
    }
1161174
@Override
    public void processXML() throws InjectionException
    {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "processXML : " + ivNameSpaceConfig.getPersistenceUnitRefs());

        // d416151.3 Begins
        List<? extends PersistenceUnitRef> pUnitRefs = ivNameSpaceConfig.getPersistenceUnitRefs();
        if (pUnitRefs != null && pUnitRefs.size() > 0)
        {
            for (PersistenceUnitRef pUnitRef : pUnitRefs)
            {
                if (isTraceOn && tc.isDebugEnabled())
                    Tr.debug(tc, " pUnitRef = " + pUnitRef);

                // If XML has previously been read and an injection binding with the same
                // jndi name has been created, get the current injection binding and merge
                // the new PersistenceUnit Ref into it.
                String jndiName = pUnitRef.getName();
                InjectionBinding<PersistenceUnit> injectionBinding = ivAllAnnotationsCollection.get(jndiName);
                if (injectionBinding != null)
                {
                    ((JPAPUnitInjectionBinding) injectionBinding).merge(pUnitRef);
                }
                else
                {
                    injectionBinding = new JPAPUnitInjectionBinding(pUnitRef, ivNameSpaceConfig); // d662814
                    addInjectionBinding(injectionBinding);
                }

                ((AbstractJPAInjectionBinding<?>) injectionBinding).addRefComponents(jndiName); // F743-30682

                // Process any injection-targets that may be specified.    d429866.1
                // The code takes into account the possibility of duplicate InjectionTargets
                // and will only add if not already present, regardless of whether this is
                // a newly created binding, or a second one being merged.
                List<InjectionTarget> targets = pUnitRef.getInjectionTargets();
                if (targets != null && !targets.isEmpty())
                {
                    for (InjectionTarget target : targets)
                    {
                        String injectionClassName = target.getInjectionTargetClassName();
                        String injectionName = target.getInjectionTargetName();
                        injectionBinding.addInjectionTarget(EntityManagerFactory.class, injectionName, injectionClassName);
                    }
                }
            }
        }
        // d416151.3 Ends
        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "processXML : " + ivAllAnnotationsCollection.size());
    }
117548
public Binding create(Key<?> key) throws BindingCreationException {
    TypeLiteral<?> type = key.getTypeLiteral();

    // All steps per:
    // http://code.google.com/p/google-guice/wiki/BindingResolution

    // 1. Explicit binding - already finished at this point.

    // 2. Ask parent injector.
    // 3. Ask child injector.
    // These bindings are created in BindingResolver and are not necessary here.

    // 4. Provider injections.
    if (isProviderKey(key)) {
      return bindingFactory.getImplicitProviderBinding(key);
      // TODO(bstoler): Scope the provider binding like the thing being provided?
    }

    // 4b. AsyncProvider injections.
    if (isAsyncProviderKey(key)) {
      return bindingFactory.getAsyncProviderBinding(key);
    }

    // 5. Convert constants.
    // Already covered by resolving explicit bindings.
    if (BindConstantBinding.isConstantKey(key)) {
      throw new BindingCreationException(
          "Binding requested for constant key '%s' but no explicit binding was found", key);
    }

    // 6. If the dependency has a binding annotation, give up.
    if (key.getAnnotation() != null || key.getAnnotationType() != null) {
      throw new BindingCreationException("No implementation bound for '%s' and an implicit binding"
          + " cannot be created because the type is annotated.", key);
    }

    // 7. If the dependency is an array or enum, give up.
    // Covered by step 5 (enum) and 11 (array).

    // 8. Handle TypeLiteral injections.
    // TODO(schmitt): Implement TypeLiteral injections.

    // 9. Use resolution annotations (@ImplementedBy, @ProvidedBy)
    ImplementedBy implementedBy = type.getRawType().getAnnotation(ImplementedBy.class);
    if (implementedBy != null) {
      return createImplementedByBinding(key, implementedBy);
    }

    ProvidedBy providedBy = type.getRawType().getAnnotation(ProvidedBy.class);
    if (providedBy != null) {
      return createProvidedByBinding(key, providedBy);
    }

    // 10. If the dependency is abstract or a non-static inner class, give up.
    // Abstract classes are handled by GWT.create.
    // TODO(schmitt): Introduce check.

    // 11. Use a single @Inject or public no-arguments constructor.
    return createImplicitBindingForClass(type);
  }
1229279
@Override
    public RemoteObjectInstance getRemoteObjectInstance(JavaColonNamespace namespace, String name) throws NamingException {
        RemoteObjectInstance roi = null;
        Object o = getObjectInstance(namespace, name);
        if (o != null && o instanceof java.rmi.Remote) {
            EJBBinding ejbBinding = getEJBBinding(namespace, name);
            if (ejbBinding == null || ejbBinding.interfaceName == null) {
                throw new NamingException("Unable to determine bound EJB's remote interface");
            }
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "getObjectInstance() ==> " + o + "  interfaceName = " + ejbBinding.interfaceName);
            }

            roi = roiFactory.create((Remote) o, ejbBinding.interfaceName);
        }
        return roi;
    }
106016
@Override
    public void resolve(InjectionBinding<Context> binding)
                    throws InjectionException {
        final String methodName = "resolve";
        if (tc.isEntryEnabled()) {
            Tr.entry(tc, methodName, binding);
        }
        Class<?> injectionType = binding.getInjectionClassType();

        if (tc.isDebugEnabled()) {
            Tr.debug(tc,
                     "Setting the ContextObjectFactory on the ContextInjectionBinding for type {0}",
                     injectionType);
        }
        Reference ref = new Reference(injectionType.getName());
        binding.setReferenceObject(ref, ContextObjectFactory.class);

        if (tc.isEntryEnabled())
            Tr.exit(tc, methodName, binding);
    }
836293
@Override
    public ObjectStore createObjectStore(ObjectStore objectStore)
            throws NameConflictException {
        try {
            return objectStoreDao.createObjectStore(objectStore);
        } catch (DuplicateKeyException e) {
            throw new NameConflictException("Object store name is already in use", e);
        }
    }
574857
@Override
    public InjectionBinding<ConnectionFactoryDefinition> createInjectionBinding(ConnectionFactoryDefinition annotation, Class<?> instanceClass, Member member, String jndiName) throws InjectionException {
        InjectionBinding<ConnectionFactoryDefinition> injectionBinding =
                        new ConnectionFactoryDefinitionInjectionBinding(jndiName, ivNameSpaceConfig);
        injectionBinding.merge(annotation, instanceClass, null);
        return injectionBinding;
    }
532011
public void processBindings()
                    throws InjectionException
    {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "processBindings");

        if (ivProcessors != null) // RTC115266
        {
            for (InjectionProcessor<?, ?> processor : ivProcessors)
            {
                if (processor != null)
                {
                    try
                    {
                        InjectionProcessorContextImpl.processBindings(processor);
                    } catch (InjectionException iex)
                    {
                        FFDCFilter.processException(iex, CLASS_NAME + ".processBindings",
                                                    "480", this, new Object[] { processor });
                        // Include the cause message in the logged message, and don't
                        // unnecessarily wrap the exception.                          F53641
                        Tr.error(tc, "FAILED_TO_PROCESS_BINDINGS_CWNEN0011E", iex.getMessage());
                        throw iex;
                    } catch (Throwable t)
                    {
                        FFDCFilter.processException(t, CLASS_NAME + ".processBindings",
                                                    "815", this, new Object[] { processor });
                        // Include the cause stack in the logged message.             F53641
                        Tr.error(tc, "FAILED_TO_PROCESS_BINDINGS_CWNEN0011E", t);
                        throw new InjectionException("Failed to process bindings for metadata", t);
                    }
                }
            }
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "processBindings");
    }
174970
protected Object processJavaColon(EJBBinding binding, JavaColonNamespace jndiType, String lookupName) throws NamingException {

        Object instance = null;

        if (binding == null) {
            return null;
        }

        // Home and remote interfaces are not supported in Liberty
        if (binding.isHome() && !homeRuntime) {
            throwCannotInstanciateUnsupported(binding, jndiType, lookupName,
                                              "JNDI_CANNOT_INSTANTIATE_HOME_CNTR4008E");
        }

        if (!binding.isLocal && !remoteRuntime) {
            throwCannotInstanciateUnsupported(binding, jndiType, lookupName,
                                              "JNDI_CANNOT_INSTANTIATE_REMOTE_CNTR4009E");
        }

        try {
            EJSHome home = binding.homeRecord.getHomeAndInitialize();

            if (binding.isHome()) {
                EJSWrapperCommon wc = home.getWrapper();
                if (binding.isLocal) {
                    instance = wc.getLocalObject();
                } else {
                    instance = home.getContainer().getEJBRuntime().getRemoteReference(wc.getRemoteWrapper());
                }
            } else {
                // Use interface name to create the business object
                if (binding.isLocal) {
                    instance = home.createLocalBusinessObject(binding.interfaceIndex, null);
                } else {
                    instance = home.createRemoteBusinessObject(binding.interfaceIndex, null);
                }
            }
        } catch (Throwable t) {
            throwCannotInstanciateObjectException(binding,
                                                  jndiType,
                                                  lookupName,
                                                  t);
        }

        return instance;
    }
1248919
@Override
    public boolean hasObjectWithPrefix(JavaColonNamespace namespace, String name) throws NamingException {
        ComponentMetaData cmd = ComponentMetaDataAccessorImpl.getComponentMetaDataAccessor().getComponentMetaData();
        J2EEName j2eeName = cmd.getJ2EEName();

        boolean b;
        try {
            b = (JavaColonNamespace.APP.equals(namespace) || JavaColonNamespace.GLOBAL.equals(namespace)) &&
                clientSupportFactory.getRemoteClientSupport().hasRemoteObjectWithPrefix(j2eeName.getApplication(), j2eeName.getModule(), j2eeName.getComponent(), namespace.toString(), name);
        } catch (RemoteException ex) {
            //ffdc
            b = false;
        }
        return b;
    }
501924
@Override
	public void rebind(Name name, Object obj) throws NamingException
    {
        if (name.isEmpty())
            throw new InvalidNameException("Cannot bind empty name");

        // Extract components that belong to this namespace
        String nm = name.toString();

        // Add object to internal hash table
        bindings.put(nm, obj);
    }
912509
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
            }
         }
      }
   }
822395
private void throwCannotInstanciateUnsupported(EJBBinding binding,
                                                   JavaColonNamespace jndiType,
                                                   String lookupName,
                                                   String messageId) throws NameNotFoundException {
        J2EEName j2eeName = getJ2EEName(binding);
        String jndiName = jndiType.toString() + "/" + lookupName;
        String msgTxt = Tr.formatMessage(tc, messageId,
                                         binding.interfaceName,
                                         j2eeName.getComponent(),
                                         j2eeName.getModule(),
                                         j2eeName.getApplication(),
                                         jndiName);
        throw (new NameNotFoundException(msgTxt));
    }