/*
There are no public API to reset the InitialContextFactoryBuilder or
ObjectFactoryBuilder on the NamingManager so try to use reflection.
553648
private static void setField(Class<?> expectedType, Object value, boolean saveOriginal) throws IllegalStateException {
        try {
            for (Field field : NamingManager.class.getDeclaredFields()) {
                if (expectedType.equals(field.getType())) {
                    field.setAccessible(true);
                    if (saveOriginal) {
                        if (expectedType.equals(InitialContextFactoryBuilder.class)) {
                            originalICFBuilder = (InitialContextFactoryBuilder) field.get(null);
                        } else {
                            originalOFBuilder = (ObjectFactoryBuilder) field.get(null);
                        }
                    }

                    field.set(null, value);
                }
            }
        } catch (Throwable t) {
            // Ignore
            LOGGER.debug("Error setting field.", t);
            throw new IllegalStateException(t);
        }
    }
1263984
@Override
    public boolean setInitParameter(String name, String value) throws IllegalStateException, IllegalArgumentException {
        if (name == null) {
            logger.logp(Level.SEVERE, CLASS_NAME, "setInitParameter", servlet40NLS.getString("name.is.null"));
            throw new java.lang.NullPointerException(servlet40NLS.getString("name.is.null"));
        }

        return super.setInitParameter(name, value);
    }
702108
public static void resetBean(MethodSpec.Builder methodBuilder, TypeName beanClass, String beanName,
			ModelProperty property, String cursorName, String indexName) {
		SQLTransform transform = lookup(property.getElement().asType());

		if (transform == null) {
			throw new IllegalArgumentException("Transform of " + property.getElement().asType() + " not supported");
		}
		transform.generateResetProperty(methodBuilder, beanClass, beanName, property, cursorName, indexName);

	}
447805
private void createInstanceUsingConstructor() throws InvocationTargetException {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "createInstanceUsingConstructor");

        try {
            if (isTraceOn && tc.isDebugEnabled())
                Tr.debug(tc, "calling Constructor.newInstance");
            Constructor<?> con = home.beanMetaData.getEnterpriseBeanClassConstructor();
            setEnterpriseBean(con.newInstance());
        } catch (InvocationTargetException e) {
            FFDCFilter.processException(e, CLASS_NAME + ".createInstanceUsingConstructor", "360", this);
            throw e;
        } catch (Exception e) {
            // Reflection exceptions are unexpected.
            FFDCFilter.processException(e, CLASS_NAME + ".createInstanceUsingConstructor", "364", this);
            throw new EJBException(home.beanMetaData.enterpriseBeanClassName, e);
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "createInstanceUsingConstructor");
    }
1248466
@Override
    public void setConstraintValidatorFactory(Configuration<?> apiConfig) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "setConstraintValidatorFactory", apiConfig);
        }
        Class<? extends ConstraintValidatorFactory> clazz = null;
        ConstraintValidatorFactory cvf = null;
        if (constraintValidatorFactory != null) {

            try {
                clazz = loadClass(constraintValidatorFactory).asSubclass(ConstraintValidatorFactory.class);
                cvf = instantiateClass(clazz);
            } catch (Throwable t) {
                FFDCFilter.processException(t, CLASS_NAME + ".setConstraintValidatorFactory", "313");
                // message and exception printed out in previous method called.
                // however since we can not create a validation factory throw validationException
                ValidationException e = new ValidationException(t);
                throw e;
            }
        }

        if (cvf != null) {
            apiConfig.constraintValidatorFactory(cvf);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "setConstraintValidatorFactory", cvf);
        }
    }
425568
void reset() {
        cleanup(); // cleaning up all context before reseting producer registry instance

        listeners.clear();
        registry.clear();

        String junittest = System.getProperty("JUNITTEST");
        if (junittest != null && junittest.equalsIgnoreCase("true")) // preventing listener's initialization for JUnit run's
            return;

        addListener(new JMXBridgeListener());

    }
229380
@Override
	public void afterPropertiesSet() throws Exception {

		Assert.state(annotation != null, "Annotation type must be configured!");
		Assert.state(linkBuilderFactory != null, "LinkBuilderFactory must be configured!");
		super.afterPropertiesSet();
	}
276565
@Override
    protected void init() throws Exception {
        BootstrapContextImpl bootstrapContext = bootstrapContextRef.getServiceWithException();

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(this, tc, "loading", mcfImplClassName);
        if (mcfImplClassName == null) // TODO: get the real config element name of the nested properties
            throw new IllegalArgumentException(Utils.getMessage("J2CA8504.incorrect.props.list", "properties", configElementName, id));
        mcf = (ManagedConnectionFactory) bootstrapContext.loadClass(mcfImplClassName).newInstance();
        bootstrapContext.configure(mcf, jndiName, properties, null, null, null);

        if (connectionManagerRef == null)
            conMgrSvc = ConnectionManagerService.createDefaultService(jndiName);
        else
            conMgrSvc = (ConnectionManagerService) priv.locateService(componentContext, CONNECTION_MANAGER);
        conMgrSvc.addObserver(this);
        isInitialized.set(true);

        conMgrSvc.addRaClassLoader(bootstrapContext.getRaClassLoader());
    }
976553
protected void initializeContext(
            @Nonnull List<BeanDefinitionReference> contextScopeBeans,
            @Nonnull List<BeanDefinitionReference> processedBeans) {

        if (CollectionUtils.isNotEmpty(contextScopeBeans)) {
            final Collection<BeanDefinition> contextBeans = new ArrayList<>();

            for (BeanDefinitionReference contextScopeBean : contextScopeBeans) {
                try {
                    loadContextScopeBean(contextScopeBean, contextBeans::add);
                } catch (Throwable e) {
                    throw new BeanInstantiationException("Bean definition [" + contextScopeBean.getName() + "] could not be loaded: " + e.getMessage(), e);
                }
            }
            filterProxiedTypes((Collection) contextBeans, true, false);
            filterReplacedBeans((Collection) contextBeans);

            for (BeanDefinition contextScopeDefinition: contextBeans) {
                try {
                    loadContextScopeBean(contextScopeDefinition);
                } catch (Throwable e) {
                    throw new BeanInstantiationException("Bean definition [" + contextScopeDefinition.getName() + "] could not be loaded: " + e.getMessage(), e);
                }
            }
            contextBeans.clear();
        }

        if (!processedBeans.isEmpty()) {

            @SuppressWarnings("unchecked") Stream<BeanDefinitionMethodReference<?, ?>> methodStream = processedBeans
                    .stream()
                    // is the bean reference enabled
                    .filter(ref -> ref.isEnabled(this))
                    // ok - continue and load it
                    .map((Function<BeanDefinitionReference, BeanDefinition<?>>) reference -> {
                        try {
                            return reference.load(this);
                        } catch (Exception e) {
                            throw new BeanInstantiationException("Bean definition [" + reference.getName() + "] could not be loaded: " + e.getMessage(), e);
                        }
                    })
                    // is the bean itself enabled
                    .filter(bean -> bean.isEnabled(this))
                    // ok continue and get all of the ExecutableMethod references
                    .flatMap(beanDefinition ->
                            beanDefinition.getExecutableMethods()
                                    .parallelStream()
                                    .map((Function<ExecutableMethod<?, ?>, BeanDefinitionMethodReference<?, ?>>) executableMethod ->
                                            BeanDefinitionMethodReference.of((BeanDefinition) beanDefinition, executableMethod)
                                    )
                    );

            // group the method references by annotation type such that we have a map of Annotation -> MethodReference
            // ie. Class<Scheduled> -> @Scheduled void someAnnotation()
            Map<Class<? extends Annotation>, List<BeanDefinitionMethodReference<?, ?>>> byAnnotation = methodStream
                    .collect(
                            Collectors.groupingBy((Function<ExecutableMethod<?, ?>, Class<? extends Annotation>>) executableMethod ->
                                    executableMethod.getAnnotationTypeByStereotype(Executable.class)
                                            .orElseThrow(() ->
                                                    new IllegalStateException("BeanDefinition.requiresMethodProcessing() returned true but method has no @Executable definition. This should never happen. Please report an issue.")
                                            )));

            // Find ExecutableMethodProcessor for each annotation and process the BeanDefinitionMethodReference
            for (Map.Entry<Class<? extends Annotation>, List<BeanDefinitionMethodReference<?, ?>>> entry : byAnnotation.entrySet()) {
                Class<? extends Annotation> annotationType = entry.getKey();
                streamOfType(ExecutableMethodProcessor.class, Qualifiers.byTypeArguments(annotationType))
                        .forEach(processor -> {
                            for (BeanDefinitionMethodReference<?, ?> method : entry.getValue()) {

                                BeanDefinition<?> beanDefinition = method.getBeanDefinition();

                                // Only process the method if the the annotation is not declared at the class level
                                // If declared at the class level it will already have been processed by AnnotationProcessorListener
                                if (!beanDefinition.hasStereotype(annotationType)) {
                                    //noinspection unchecked
                                    if (method.hasDeclaredStereotype(Parallel.class)) {
                                        ForkJoinPool.commonPool().execute(() -> {
                                            try {
                                                processor.process(beanDefinition, method);
                                            } catch (Throwable e) {
                                                if (LOG.isErrorEnabled()) {
                                                    LOG.error("Error processing bean method " + beanDefinition + "." + method + " with processor (" + processor + "): " + e.getMessage(), e);
                                                }
                                                Boolean shutdownOnError = method.getValue(Parallel.class, "shutdownOnError", Boolean.class).orElse(true);
                                                if (shutdownOnError) {
                                                    stop();
                                                }
                                            }
                                        });
                                    } else {
                                        processor.process(beanDefinition, method);
                                    }
                                }
                            }

                            if (processor instanceof Completable) {
                                ((Completable) processor).onComplete();
                            }

                        });
            }
        }

        final Runnable runnable = () ->
                beanDefinitionsClasses.removeIf((BeanDefinitionReference beanDefinitionReference) ->
                        !beanDefinitionReference.isEnabled(this));
        if (ClassLoadingReporter.isReportingEnabled()) {
            // do this in a blocking manner so that reporting is immediately aware of missing classes
            runnable.run();
        } else {
            // proactively remove bean definitions that are not enabled
            new Thread(runnable).start();
        }

    }
73538
public void initFrom(SessionFactory sessionFactory) {
    Assert.notNull(sessionFactory);
    Stopwatch watch = new Stopwatch().start();
    Map<String, ClassMetadata> classMetadatas = sessionFactory.getAllClassMetadata();
    int entityCount = entityTypes.size();
    int collectionCount = collectionTypes.size();
    for (Iterator<ClassMetadata> iter = classMetadatas.values().iterator(); iter.hasNext();) {
      ClassMetadata cm = (ClassMetadata) iter.next();
      buildEntityType(sessionFactory, cm.getEntityName());
    }
    logger.info("Find {} entities,{} collections from hibernate in {}", new Object[] {
        entityTypes.size() - entityCount, collectionTypes.size() - collectionCount, watch });
    if (logger.isDebugEnabled()) loggerTypeInfo();
    collectionTypes.clear();
  }
589607
public void initialized(AppContextWrapper context) {
		ContainerRegistryBuilder cb = (ContainerRegistryBuilder) context.getAttribute(ContainerRegistryBuilder.APPLICATION_CONTEXT_ATTRIBUTE_NAME);
		if (cb != null)
			return;
		try {
			synchronized (context) {
				cb = containerBuilderContext.createContainerBuilder(context);
				context.setAttribute(ContainerRegistryBuilder.APPLICATION_CONTEXT_ATTRIBUTE_NAME, cb);
				Debug.logVerbose("[JdonFramework] Initialize the container OK ..");
			}
		} catch (Exception e) {
			Debug.logError("[JdonFramework] initialized error: " + e, module);
		}
	}
355281
@Override
  public final synchronized void init() throws Exception {
    FactoryBldAccServices<ResultSet> factoryBldAccServices =
      new FactoryBldAccServices<ResultSet>();
    factoryBldAccServices.setFactoryAppBeans(this);
    setFactoryBldServices(factoryBldAccServices);
    FactoryAccServices<ResultSet> factoryAccServices =
      new FactoryAccServices<ResultSet>();
    factoryAccServices.setFactoryAppBeans(this);
    factoryAccServices.setFactoryBldAccServices(factoryBldAccServices);
    factoryBldAccServices.setFactoryAccServices(factoryAccServices);
    setFactoryOverBeans(factoryAccServices);
    FactoryAccReplicatorXmlHttps<ResultSet> factoryReplicatorXmlHttps =
      new FactoryAccReplicatorXmlHttps<ResultSet>();
    factoryReplicatorXmlHttps.setFactoryAppBeans(this);
    setFactoryReplicatorXmlHttps(factoryReplicatorXmlHttps);
    FactoryAccDatabaseWriterXml<ResultSet> factoryDatabaseWriterXml =
      new FactoryAccDatabaseWriterXml<ResultSet>();
    factoryDatabaseWriterXml.setFactoryAppBeans(this);
    setFactoryDatabaseWriterXml(factoryDatabaseWriterXml);
  }
161715
private static Object invokeNullaryFactoryMethod(final String fqcn, final String methodName) {
        try {
            final Class<?> type = Class.forName(fqcn);
            final Method method = type.getMethod(methodName);

            return method.invoke(null);
            // any exception is really unexpected since the type name has
            // already been verified
        } catch (final Exception e) {
            throw new InstantiationException(
                    String.format("Could not create %s#%s(): %s", fqcn, methodName, e), e);
        }
    }
965067
@FFDCIgnore(CacheException.class)
    private void cacheInit() {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        // Attempt lazy initialization if necessary
        try{
            if (cacheStoreService.cacheManager == null)
                cacheStoreService.activateLazily();

            // Build a unique per-application cache name by starting with the application context root and percent encoding
            // the / and : characters (JCache spec does not allow these in cache names)
            // and also the % character (which is necessary because of percent encoding)
            String a = PERCENT.matcher(_iStore.getId()).replaceAll("%25"); // must be done first to avoid replacing % that is added when replacing the others
            a = SLASH.matcher(a).replaceAll(".");
            a = COLON.matcher(a).replaceAll(".");

            // Session Meta Information Cache

            String metaCacheName = new StringBuilder(24 + a.length()).append("com.ibm.ws.session.meta.").append(a).toString();

            if (trace && tc.isDebugEnabled())
                tcInvoke(cacheStoreService.tcCacheManager, "getCache", metaCacheName, "String", "ArrayList");

            sessionMetaCache = cacheStoreService.cacheManager.getCache(metaCacheName, String.class, ArrayList.class);
            boolean create;
            if (create = sessionMetaCache == null) {
                if (trace && tc.isDebugEnabled())
                    tcReturn(cacheStoreService.tcCacheManager, "getCache", "null");

                @SuppressWarnings("rawtypes")
                MutableConfiguration<String, ArrayList> config = new MutableConfiguration<String, ArrayList>()
                .setTypes(String.class, ArrayList.class)
                .setExpiryPolicyFactory(EternalExpiryPolicy.factoryOf());
                if (cacheStoreService.supportsStoreByReference)
                    config = config.setStoreByValue(false);
                try {
                    if (trace && tc.isDebugEnabled())
                        tcInvoke(cacheStoreService.tcCacheManager, "createCache", metaCacheName, config);

                    sessionMetaCache = cacheStoreService.cacheManager.createCache(metaCacheName, config);
                } catch (CacheException x) {
                    create = false;
                    if (trace && tc.isDebugEnabled()) {
                        tcReturn(cacheStoreService.tcCacheManager, "createCache", x);
                        tcInvoke(cacheStoreService.tcCacheManager, "getCache", metaCacheName, "String", "ArrayList");
                    }
                    sessionMetaCache = cacheStoreService.cacheManager.getCache(metaCacheName, String.class, ArrayList.class);
                    if (sessionMetaCache == null)
                        throw x;
                }
            }

            tcSessionMetaCache = "MetaCache" + Integer.toHexString(System.identityHashCode(sessionMetaCache));
            if (trace && tc.isDebugEnabled())
                tcReturn(cacheStoreService.tcCacheManager, create ? "createCache" : "getCache", tcSessionMetaCache, sessionMetaCache);

            cacheStoreService.configureMonitoring(metaCacheName);

            // Session Attributes Cache

            String attrCacheName = new StringBuilder(24 + a.length()).append("com.ibm.ws.session.attr.").append(a).toString();

            if (trace && tc.isDebugEnabled())
                tcInvoke(cacheStoreService.tcCacheManager, "getCache", attrCacheName, "String", "byte[]");

            sessionAttributeCache = cacheStoreService.cacheManager.getCache(attrCacheName, String.class, byte[].class);

            if (create = sessionAttributeCache == null) {
                if (trace && tc.isDebugEnabled())
                    tcReturn(cacheStoreService.tcCacheManager, "getCache", "null");

                MutableConfiguration<String, byte[]> config = new MutableConfiguration<String, byte[]>()
                                .setTypes(String.class, byte[].class)
                                .setExpiryPolicyFactory(EternalExpiryPolicy.factoryOf());
                if (cacheStoreService.supportsStoreByReference)
                    config = config.setStoreByValue(false);
                try {
                    if (trace && tc.isDebugEnabled())
                        tcInvoke(cacheStoreService.tcCacheManager, "createCache", attrCacheName, config);

                    sessionAttributeCache = cacheStoreService.cacheManager.createCache(attrCacheName, config);
                } catch (CacheException x) {
                    create = false;
                    if (trace && tc.isDebugEnabled()) {
                        tcReturn(cacheStoreService.tcCacheManager, "createCache", x);
                        tcInvoke(cacheStoreService.tcCacheManager, "getCache", attrCacheName, "String", "byte[]");
                    }
                    sessionAttributeCache = cacheStoreService.cacheManager.getCache(attrCacheName, String.class, byte[].class);
                    if (sessionAttributeCache == null)
                        throw x;
                }
            }

            tcSessionAttrCache = "AttrCache" + Integer.toHexString(System.identityHashCode(sessionAttributeCache));
            if (trace && tc.isDebugEnabled())
                tcReturn(cacheStoreService.tcCacheManager, create ? "createCache" : "getCache", tcSessionAttrCache, sessionAttributeCache);

            cacheStoreService.configureMonitoring(attrCacheName);
        } catch(Exception ex) {
            //auto ffdc
            Tr.error(tc, "ERROR_SESSION_INIT", ex);
            throw new RuntimeException(Tr.formatMessage(tc, "INTERNAL_SERVER_ERROR"));
        }
    }
1105436
public synchronized void setFactoryMethod(String factoryMethodName)
    {
        Method newMethod = null;
        this.factoryMethodName = factoryMethodName;

        if (factoryMethodName != null)
        {
            try
            {
                // see if we have a publicly accessible method by the name
                newMethod = getFactoryClass().getMethod(factoryMethodName, NO_PARAMS);
            }
            catch (NoSuchMethodException e)
            {
                try
                {
                    // no publicly accessible method, see if there is a private/protected one
                    newMethod = getFactoryClass().getDeclaredMethod(factoryMethodName, NO_PARAMS);
                }
                catch (NoSuchMethodException e2)
                {
                    // there is no such method available
                    throw new MetadataException(
                        "Invalid factory method, there is not"
                            + " a zero argument method named "
                            + factoryMethodName
                            + " on class "
                            + getFactoryClass().getName()
                            + ".");
                }
            }
        }
        setFactoryMethod(newMethod);
    }
13684
public Reflect create() throws ReflectionException {
      try {
         return on(clazz.getConstructor(), accessAll);
      } catch (NoSuchMethodException e) {
         if (accessAll) {
            try {
               return on(clazz.getDeclaredConstructor(), accessAll);
            } catch (NoSuchMethodException e2) {
               throw new ReflectionException(e2);
            }
         }
         throw new ReflectionException(e);
      }
   }
227621
public static void reset() {
		globalBeanBoxContext.close();
		globalNextAllowAnnotation = true;
		globalNextAllowSpringJsrAnnotation = true;
		globalNextValueTranslator = new DefaultValueTranslator();
		CREATE_METHOD = "create";
		CONFIG_METHOD = "config";
		globalBeanBoxContext = new BeanBoxContext();

	}