Registers all factories found in the given bundle

        :param bundle: A bundle
183312
def _register_bundle_factories(self, bundle):
        # type: (Bundle) -> None
        
        # Load the bundle factories
        factories = _load_bundle_factories(bundle)

        for context, factory_class in factories:
            try:
                # Register each found factory
                self._register_factory(context.name, factory_class, False)
            except ValueError as ex:
                # Already known factory
                _logger.error(
                    "Cannot register factory '%s' of bundle %d (%s): %s",
                    context.name,
                    bundle.get_bundle_id(),
                    bundle.get_symbolic_name(),
                    ex,
                )
                _logger.error(
                    "class: %s -- module: %s",
                    factory_class,
                    factory_class.__module__,
                )
            else:
                # Instantiate components
                for name, properties in context.get_instances().items():
                    self.instantiate(context.name, name, properties)
322225
def _unregister_all_factories(self):
        
        factories = list(self.__factories.keys())
        for factory_name in factories:
            self.unregister_factory(factory_name)
823957
def register_options(cls, register):
    """"""
    super(BundleMixin, cls).register_options(register)
    register('--archive', choices=list(archive.TYPE_NAMES),
             fingerprint=True,
             help='Create an archive of this type from the bundle. '
                  'This option is also defined in app target. '
                  'Precedence is CLI option > target option > pants.ini option.')
    # `target.id` ensures global uniqueness, this flag is provided primarily for
    # backward compatibility.
    register('--use-basename-prefix', advanced=True, type=bool,
             help='Use target basename to prefix bundle folder or archive; otherwise a unique '
                  'identifier derived from target will be used.')
476080
public static Bundle addBundle(final CFMLEngineFactory factory, final BundleContext context, final File bundle, final Log log) throws IOException, BundleException {

	return addBundle(factory, context, bundle.getAbsolutePath(), new FileInputStream(bundle), true, log);
    }
547817
public static function register($bundle, $config = array())
	{
		$defaults = array('handles' => null, 'auto' => false);

		// If the given configuration is actually a string, we will assume it is a
		// location and set the bundle name to match it. This is common for most
		// bundles that simply live in the root bundle directory.
		if (is_string($config))
		{
			$bundle = $config;

			$config = array('location' => $bundle);
		}

		// If no location is set, we will set the location to match the name of
		// the bundle. This is for bundles that are installed on the root of
		// the bundle directory so a location was not set.
		if ( ! isset($config['location']))
		{
			$config['location'] = $bundle;
		}

		static::$bundles[$bundle] = array_merge($defaults, $config);

		// It is possible for the developer to specify auto-loader mappings
		// directly on the bundle registration. This provides a convenient
		// way to register mappings without a bootstrap.
		if (isset($config['autoloads']))
		{
			static::autoloads($bundle, $config);
		}
	}
345055
private List<String> findFactoryCandidates(BundleContext context) throws IOException {
        Bundle[] bundles = context.getBundles();
        List<String> factoryCandidates = new ArrayList<String>();
        for (Bundle bundle : bundles) {
            if (bundle == null) {
                continue;
            }
            if ("system.bundle".equals(bundle.getSymbolicName())) {
                continue;
            }
            Enumeration urls = bundle.findEntries("META-INF/services", "javax.script.ScriptEngineFactory", false);
            if (urls == null) {
                continue;
            }
            while (urls.hasMoreElements()) {
                URL u = (URL) urls.nextElement();
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(
                            new InputStreamReader(u.openStream(), "UTF-8"));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        line = line.trim();
                        if (!line.startsWith("#") && line.length() > 0) {
                            factoryCandidates.add(line);
                        }
                    }
                } finally {
                    IOUtil.closeResource(reader);
                }
            }
        }

        // Add java built in JavaScript ScriptEngineFactory's
        addJavaScriptEngine(factoryCandidates);

        return factoryCandidates;
    }
1348553
@Override
    public void registerFactory(String name, Class<? extends ChannelFactory> factory) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "registerFactory: " + name + "; " + factory);
        }
        synchronized (this.factories) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Class<? extends ChannelFactory> prevFactory = this.factories.get(name);
                if (null != prevFactory && factory != prevFactory) {
                    Tr.event(tc, "WARNING: overlaying existing factory: " + prevFactory);
                }
            }
            this.factories.put(name, factory);
        } // end-sync

        // now that we have a new factory type, tell ChannelUtils to process
        // any delayed config that might be waiting for it
        ChannelUtils.loadConfig(null);
    }
177951
def _register_factory(self):
        
        for name, info in self._plugins.items():
            if info['priority']:
                factory = getattr(info['plugin'], 'factory', None)
                if callable(factory):
                    registry[info['factory']] = info['plugin'].factory
        registry.freeze()
793813
public void setBundles(java.util.Collection<Bundle> bundles) {
        if (bundles == null) {
            this.bundles = null;
            return;
        }

        this.bundles = new java.util.ArrayList<Bundle>(bundles);
    }
763321
protected function registerFactory(): void
    {
        $this->app->singleton('facebook.factory', function () {
            return new FacebookFactory();
        });

        $this->app->alias('facebook.factory', FacebookFactory::class);
    }
471525
protected function registerStrategyInterfaceBindings()
    {
        $this->app->singleton(RepositoriesContracts\ActivateStrategyResolverInterface::class, Repositories\ActivateStrategies\ActivateStrategyResolver::class);
        $this->app->singleton(RepositoriesContracts\OrderableStrategyResolverInterface::class, Repositories\OrderableStrategies\OrderableStrategyResolver::class);
        $this->app->singleton(FactoriesContracts\FilterStrategyFactoryInterface::class, Factories\FilterStrategyFactory::class);
        $this->app->singleton(FactoriesContracts\ListDisplayStrategyFactoryInterface::class, Factories\ListDisplayStrategyFactory::class);
        $this->app->singleton(FactoriesContracts\ShowFieldStrategyFactoryInterface::class, Factories\ShowFieldStrategyFactory::class);
        $this->app->singleton(FactoriesContracts\FormFieldStrategyFactoryInterface::class, Factories\FormFieldStrategyFactory::class);
        $this->app->singleton(FactoriesContracts\FormStoreStrategyFactoryInterface::class, Factories\FormStoreStrategyFactory::class);
        $this->app->singleton(FactoriesContracts\ActionStrategyFactoryInterface::class, Factories\ActionStrategyFactory::class);
        $this->app->singleton(FactoriesContracts\DeleteStrategyFactoryInterface::class, Factories\DeleteStrategyFactory::class);
        $this->app->singleton(FactoriesContracts\DeleteConditionStrategyFactoryInterface::class, Factories\DeleteConditionStrategyFactory::class);
        $this->app->singleton(FactoriesContracts\ExportColumnStrategyFactoryInterface::class, Factories\ExportColumnStrategyFactory::class);
        $this->app->singleton(FactoriesContracts\ExportStrategyFactoryInterface::class, Factories\ExportStrategyFactory::class);

        return $this;
    }
874448
private void startBundle( final Bundle bundle )
        throws BundleException
    {
        // Don't start if bundle already active
        int bundleState = bundle.getState();
        if( bundleState == Bundle.ACTIVE )
        {
            return;
        }

        // Don't start if bundle is a fragment bundle
        Dictionary bundleHeaders = bundle.getHeaders();
        if( bundleHeaders.get( Constants.FRAGMENT_HOST ) != null )
        {
            return;
        }

        // Start bundle
        bundle.start();

        bundleState = bundle.getState();
        if( bundleState != Bundle.ACTIVE )
        {
            long bundleId = bundle.getBundleId();
            String bundleName = bundle.getSymbolicName();
            String bundleStateStr = bundleStateToString( bundleState );
            throw new BundleException(
                "Bundle (" + bundleId + ", " + bundleName + ") not started (still " + bundleStateStr + ")"
            );
        }
    }
1226049
def get_bundles():
    
    global _cached_bundles

    if not _cached_bundles:
        _cached_bundles = BundleManager()

        for bundle_conf in bundles_settings.BUNDLES:
            _cached_bundles[bundle_conf[0]] = Bundle(bundle_conf)

    return _cached_bundles
1161558
def symlink_bundles(self, app, bundle_dir):
    
    for bundle_counter, bundle in enumerate(app.bundles):
      count = 0
      for path, relpath in bundle.filemap.items():
        bundle_path = os.path.join(bundle_dir, relpath)
        count += 1
        if os.path.exists(bundle_path):
          continue

        if os.path.isfile(path):
          safe_mkdir(os.path.dirname(bundle_path))
          os.symlink(path, bundle_path)
        elif os.path.isdir(path):
          safe_mkdir(bundle_path)

      if count == 0:
        raise TargetDefinitionException(app.target,
                                        'Bundle index {} of "bundles" field '
                                        'does not match any files.'.format(bundle_counter))
208424
public SerializerRegistry register(Class<?> type, TypeSerializerFactory factory) {
    return register(type, calculateTypeId(type), factory);
  }
460253
def staticbundle(bundle, mimetype=None, **attrs):
    
    config = getattr(settings, 'STATIC_BUNDLES', {})

    if settings.DEBUG and 'packages' in config and bundle in config['packages']:
        cache_root = os.path.join(settings.STATIC_ROOT, config.get('cache') or DEFAULT_CACHE_DIR)

        bundle_opts = config['packages'][bundle]

        root = os.path.join(cache_root, bundle_opts.get('cwd', ''))

        changed = set()
        src_list = bundle_opts['src']
        is_mapping = isinstance(src_list, dict)

        for src in src_list:
            src_path = os.path.join(bundle_opts.get('cwd', ''), src)
            abs_src = os.path.join(settings.STATIC_ROOT, src_path)

            if is_mapping and not os.path.exists(os.path.join(root, src_list[src])):
                    changed.add(src)

            if abs_src is not None:
                cached_mtime = BUNDLE_CACHE.get(abs_src)
                current_mtime = os.stat(abs_src).st_mtime
                if cached_mtime is None:
                    try:
                        BUNDLE_CACHE[abs_src] = cached_mtime = current_mtime
                    except OSError:
                        cached_mtime = 0
                else:
                    cached_mtime = BUNDLE_CACHE[abs_src]

                if current_mtime != cached_mtime:
                    changed.add(src_path)
                    BUNDLE_CACHE[abs_src] = current_mtime

            elif settings.TEMPLATE_DEBUG:
                raise template.TemplateSyntaxError(
                    "The source file '%s' could not be located." % src_path)

        if changed:
            logger.info('Regenerating %s due to changes: %s', bundle, ' '.join(changed))
            call_command('compilestatic', bundle)

    #     if isinstance(src_list, dict):
    #         src_list = src_list.values()

    src_list = [bundle]

    output = []
    for src_path in src_list:
        url = staticfiles_storage.url(src_path)

        # Some storages backends will yield urls with querystring attached
        path = urlparse.urlparse(url).path
        if path.endswith('.css'):
            mimetype = 'text/css'
        elif path.endswith('.js'):
            mimetype = 'text/javascript'

        output.append(TEMPLATES[mimetype] % dict(
            url=url,
            mimetype=mimetype,
            attrs=' '.join('%s="%s"' % (k, escape(v)) for k, v in attrs.iteritems()),
        ))

    return '\n'.join(output)
1081966
public void installBundles(final BundleContext bContext,
                               final BundleList bundleList,
                               final BundleInstallStatus installStatus,
                               final int minStartLevel, final int defaultStartLevel,
                               final int defaultInitialStartLevel,
                               final WsLocationAdmin locSvc) {

        if (bundleList == null || bundleList.isEmpty())
            return;
        final FrameworkWiring fwkWiring = featureManager.bundleContext.getBundle(Constants.SYSTEM_BUNDLE_LOCATION).adapt(FrameworkWiring.class);
        final File bootFile = getBootJar();
        bundleList.foreach(new BundleList.FeatureResourceHandler() {
            @Override
            @FFDCIgnore({ IllegalStateException.class, Exception.class })
            public boolean handle(FeatureResource fr) {
                Bundle bundle = null;
                WsResource resource = null;
                String urlString = fr.getLocation();

                try {
                    String bundleRepositoryType = fr.getBundleRepositoryType();
                    BundleRepositoryHolder bundleRepositoryHolder = featureManager.getBundleRepositoryHolder(bundleRepositoryType);
                    if (bundleRepositoryHolder == null) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Bundle repository not found for type=" + bundleRepositoryType);
                        }
                        Tr.error(tc, "UPDATE_MISSING_BUNDLE_ERROR", fr.getMatchString());
                        installStatus.addMissingBundle(fr);
                        return true;
                    }
                    // Get the product name for which the bundles are being installed.
                    String productName = bundleRepositoryHolder.getFeatureType();

                    if (libertyBoot) {
                        bundle = installLibertyBootBundle(productName, fr, fwkWiring);
                    } else {
                        bundle = installFeatureBundle(urlString, productName, bundleRepositoryHolder, fr);
                    }
                    if (bundle == null) {
                        return true;
                    }

                    BundleStartLevel bsl = bundle.adapt(BundleStartLevel.class);
                    BundleRevision bRev = bundle.adapt(BundleRevision.class);

                    int level = 0;

                    // For non-fragment bundles set the bundle startLevel then
                    // add to the list of bundles to be started.
                    // The order is important because the bundles are sorted by
                    // start level to preserve the start level ordering during
                    // dynamic feature additions.
                    if ((bRev.getTypes() & BundleRevision.TYPE_FRAGMENT) != BundleRevision.TYPE_FRAGMENT) {

                        level = bsl.getStartLevel();

                        // Set the start level on the bundle to the selected value
                        // if it hasn't been set before
                        if (level == defaultInitialStartLevel) {
                            int sl = fr.getStartLevel();
                            int newLevel = (sl == 0) ? defaultStartLevel : (sl < minStartLevel) ? minStartLevel : sl;
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(this, tc, "Changing the start level of bundle {0} from {1} to the current level of {2}", bundle, level, newLevel);
                            }
                            level = newLevel;
                            bsl.setStartLevel(level);
                        }

                        installStatus.addBundleToStart(bundle);
                    }

                    // need to get a resource for the bundle list createAssociation
                    // call, if we end up with a null resource then bad things
                    // happen, like we fail to uninstall bundles when we should
                    File bundleFile = getBundleFile(bundle);
                    resource = locSvc.asResource(bundleFile, bundleFile.isFile());

                    // Update bundle list with resolved information
                    bundleList.createAssociation(fr, bundle, resource, level);
                } catch (IllegalStateException e) {
                    // The framework is stopping: this is an expected but not ideal occurrence.
                    installStatus.markContextInvalid(e);
                    return false;
                } catch (Exception e) {
                    // We encountered an error installing a bundle, add it to
                    // the status, and continue. The caller will handle as appropriate
                    installStatus.addInstallException("INSTALL " + urlString + " (resolved from: " + fr + ")", e);
                }
                return true;
            }

            private File getBundleFile(Bundle bundle) {
                if (libertyBoot) {
                    return bootFile;
                }
                // make sure we have a File for the bundle that is already
                // installed. Get this by processing the location. We
                // need to get past the reference:file: part of the URL.
                String location = bundle.getLocation();
                int index = location.indexOf(BUNDLE_LOC_REFERENCE_TAG);
                location = location.substring(index + BUNDLE_LOC_REFERENCE_TAG.length());
                // This file path is URL form, convert it back to a valid system File path
                return new File(URI.create(location));
            }

            private Bundle installLibertyBootBundle(String productName, FeatureResource fr, FrameworkWiring fwkWiring) throws BundleException, IOException {
                //getting the LibertyBootRuntime instance and installing the boot bundle
                LibertyBootRuntime libertyBoot = featureManager.getLibertyBoot();
                if (libertyBoot == null) {
                    throw new IllegalStateException("No LibertBootRuntime service available!");
                }

                Bundle bundle = libertyBoot.installBootBundle(fr.getSymbolicName(), fr.getVersionRange(), BUNDLE_LOC_FEATURE_TAG);
                if (bundle == null) {
                    installStatus.addMissingBundle(fr);
                    return null;
                }

                Region productRegion = getProductRegion(productName);
                Region current = featureManager.getDigraph().getRegion(bundle);
                if (!productRegion.equals(current)) {
                    current.removeBundle(bundle);
                    productRegion.addBundle(bundle);
                }
                return bundle;
            }

            private Bundle installFeatureBundle(String urlString, String productName, BundleRepositoryHolder bundleRepositoryHolder,
                                                FeatureResource fr) throws BundleException, IOException {
                Bundle bundle = fetchInstalledBundle(urlString, productName);
                if (bundle == null) {
                    ContentBasedLocalBundleRepository lbr = bundleRepositoryHolder.getBundleRepository();
                    // Try to find the file, hopefully using the cached path
                    File bundleFile = lbr.selectBundle(urlString, fr.getSymbolicName(), fr.getVersionRange());

                    if (bundleFile == null) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Bundle not matched", lbr, fr);
                        }
                        Tr.error(tc, "UPDATE_MISSING_BUNDLE_ERROR", fr.getMatchString());
                        installStatus.addMissingBundle(fr);
                        return null;
                    }

                    // Get URL from filename
                    URI uri = bundleFile.toURI();
                    urlString = uri.toURL().toString();

                    urlString = PathUtils.normalize(urlString);

                    // Install this bundle as a "reference"-- this means that the
                    // framework will not copy this bundle into it's private cache,
                    // it will run from the actual jar (wherever it is).
                    urlString = BUNDLE_LOC_REFERENCE_TAG + urlString;

                    // Get the bundle location.
                    // The location format being returned must match the format in SchemaBundle and BundleList.
                    String location = getBundleLocation(urlString, productName);

                    Region productRegion = getProductRegion(productName);
                    // Bundle will just be returned if something from this location exists already.
                    bundle = productRegion.installBundleAtLocation(location, new URL(urlString).openStream());
                }
                return bundle;
            }

            private Bundle fetchInstalledBundle(String urlString, String productName) {
                // We install bundles as references so we need to ensure that we add reference: to the file url.
                String location = getBundleLocation(BUNDLE_LOC_REFERENCE_TAG + urlString, productName);
                Bundle b = featureManager.bundleContext.getBundle(location);

                if (b != null && b.getState() == Bundle.UNINSTALLED) {
                    b = null;
                }

                return b;
            }
        });
    }