Load services from bundles
6874
private function loadService()
    {
        $this->getEventManager()->dispatch(self::EVENT_BEFORE_LOAD_SERVICE, $this);

        foreach ($this->registerBundles() as $bundle) {
            $bundle->loadService();
        }

        $this->getEventManager()->dispatch(self::EVENT_AFTER_LOAD_SERVICE, $this);
    }
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;
            }
        });
    }
1362613
private function loadMiddleware()
    {
        $this->middleware = [];

        $config = Container::getInstance()->get('config');
        $list   = $config->get('global.middleware');

        foreach ($list as $name => $conf) {
            $services = $conf['services'];
            foreach ($services as $service) {
                // todo
            }
            $this->middleware[] = new $conf['class']($config);
        }
    }
737187
public static function load(BundleInterface $bundle)
    {
        if (is_dir($bundle->getPath())) {
            self::$bundlesLoaded[$bundle->getName()] = [
                'namespace' => $bundle->getNamespace(),
                'path' => $bundle->getPath()
            ];

            if (!self::$classLoader) {
                self::$classLoader = new ClassLoader();
            }

            self::$classLoader->addPsr4($bundle->getNamespace(), $bundle->getPath());
            self::$classLoader->register();
        } else {
            throw new MissingBundleException(sprintf('Bundle "%s" could not be found.', $bundle->getName()));
        }
    }
137073
@Route(method = HttpMethod.POST, uri = "")
    public Result installBundle(@FormParameter("bundle") final FileItem bundle,
                                @FormParameter("start") @DefaultValue("false") final boolean startIfNeeded) {
        if (bundle != null) {
            return async(new Callable<Result>() {
                @Override
                public Result call() throws Exception {
                    Bundle b;

                    try {
                        b = context.installBundle("file/temp/" + bundle.name(), bundle.stream());
                        logger().info("Bundle {} installed", b.getSymbolicName());
                    } catch (BundleException e) {
                        flash("error", "Cannot install bundle '" + bundle.name() + "' : "
                                + e.getMessage());
                        return bundle();
                    }

                    if (startIfNeeded  && ! isFragment(b)) {
                        try {
                            b.start();
                            flash("success", "Bundle '" + b.getSymbolicName() + "' installed and started");
                            return bundle();
                        } catch (BundleException e) {
                            flash("error", "Bundle '" + b.getSymbolicName() + "' installed but " +
                                    "failed to start: " + e.getMessage());
                            return bundle();
                        }
                    } else {
                        flash("success", "Bundle '" + b.getSymbolicName() + "' installed.");
                        return bundle();
                    }
                }
            });
        } else {
            logger().error("No bundle to install");
            flash("error", "Unable to install the bundle - no uploaded file");
            return bundle();
        }
    }
212509
def _loadServices(self):
        
        servicesPath = os.path.join(self.path, "service")
        if not os.path.isdir(servicesPath):
            return

        self._scanDirectoryForServices(servicesPath)
1061244
public void addRequiredBundles(String... requiredBundles) {
		String oldBundles = mainAttributes.get(REQUIRE_BUNDLE);
		if (oldBundles == null)
			oldBundles = "";
		BundleList oldResultList = BundleList.fromInput(oldBundles, newline);
		BundleList resultList = BundleList.fromInput(oldBundles, newline);
		for (String bundle : requiredBundles) {
			Bundle newBundle = Bundle.fromInput(bundle);
			if (name != null && name.equals(newBundle.getName()))
				continue;
			resultList.mergeInto(newBundle);
		}
		String result = resultList.toString();
		boolean changed = !oldResultList.toString().equals(result);
		modified |= changed;
		if (changed)
			mainAttributes.put(REQUIRE_BUNDLE, result);
	}
1232346
void loadAdditionalServices(ServiceRegistry registry) {
        for (ResourceLoader loader : getResourceLoaders()) {
            for (Metadata<Service> metadata : ServiceLoader.load(Service.class, loader)) {
                Service service = metadata.getValue();
                for (Class<? extends Service> serviceInterface : Services.identifyServiceInterfaces(service.getClass(), new HashSet<>())) {
                    Services.put(registry, serviceInterface, service);
                }
            }
        }
    }
379225
@Activate
    public void startUp(BundleContext bundleContext) {
        extendedBundleContext = new ExtendedBundle.ExtendedBundleContext(bundleContext);
        bundleContext.addBundleListener(this);
    }
301749
protected function loadServicesFromConfig()
    {
        foreach (Config::get('services', []) as $name => $service) {
            $service += [
                'shared' => false,
                'locked' => false,
                'definition' => []
            ];

            $this->container->set($name, $service['definition'], $service['shared'], $service['locked']);
        }
    }
741938
public void loadPropertiesBundle(final String bundleName,
			final Locale locale) {
		LOG.info("Loading properties bundle: " + bundleName);
		ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale);
		bundles.put(bundleName, bundle);
	}
1090511
def download_bundle_view(self, request, pk):
        """"""

        return self._download_response(request, pk, bundle=True)
1271767
public function load(array $config)
    {
        foreach ($config as $id => $classname) {
            $serviceId = $this->generateBundleServiceId($id);

            if (false === $this->container->hasDefinition($serviceId)) {
                $baseDir = $this->buildBundleBaseDirectoryFromClassname($classname);
                $this->bundlesBaseDir[$serviceId] = $baseDir;
                $this->container->setDefinition(
                    $serviceId,
                    $this->buildBundleDefinition($classname, $id, $baseDir)
                );

                $this->bundleInfos[$id] = [
                    'main_class' => $classname,
                    'base_dir'   => $baseDir,
                ];
            }
        }

        if (0 < count($this->bundlesBaseDir)) {
            $this->loadFullBundles();
        }
    }
405281
public function load(array $bundles)
    {
        $this->finalBundles = $bundles;

        while (!empty($this->bundleStack)) {
            $bundle = array_shift($this->bundleStack);
            $this->addBundle($bundle);
        }

        return $this->finalBundles;
    }
571929
public Object startupService(BundleContext bundleContext)
    {
        // Good, Environment activator is up. Time to start up http services trackers
        
        for (String alias : getAliases())
        {
            Dictionary<String, String> properties = new Hashtable<String, String>();
            ServiceTracker serviceTracker = this.makeServletTracker(alias, properties);
            ((ServiceTracker)serviceTracker).open();
            context.registerService(ServiceTracker.class.getName(), serviceTracker, properties);    // Why isn't this done automatically?
        }

        return null;
    }
1297211
async function bundle(opts: *) {
  const directory = process.cwd();
  const configPath = getWebpackConfig(directory, opts.config);

  const [
    configs,
    availablePlatforms,
  ] = makeReactQMLConfig(
    // $FlowFixMe: Dynamic require
    require(configPath),
    {
      root: directory,
      dev: opts.dev,
      minify: opts.minify,
      bundle: true,
    }
  );

  const config = configs[availablePlatforms.indexOf(opts.platform)];

  if (opts.assetsDest) {
    config.output.path = path.isAbsolute(opts.assetsDest)
      ? opts.assetsDest
      : path.join(directory, opts.assetsDest);
  }

  if (opts.bundleOutput) {
    config.output.filename = path.isAbsolute(opts.bundleOutput)
      ? path.relative(config.output.path, opts.bundleOutput)
      : path.relative(
          config.output.path,
          path.join(directory, opts.bundleOutput)
        );
  }

  const compiler = webpack(config);

  logger.info(
    messages.initialBundleInformation({
      entry: config.entry,
      dev: opts.dev,
    })
  );

  const stats = await new Promise((resolve, reject) =>
    compiler.run((err, info) => {
      if (err || info.hasErrors()) {
        reject(
          new MessageError(
            messages.bundleFailed({
              errors: err
                ? [err.message]
                : info.toJson({ errorDetails: true }).errors,
            })
          )
        );
      } else {
        resolve(info);
      }
    })
  );

  clear();

  logger.done(
    messages.bundleBuilt({
      stats,
      platform: opts.platform,
      assetsPath: config.output.path,
      bundlePath: config.output.filename,
    })
  );
}
623789
function compileBundle (bundle, dest) {
  return bundle.bundle()
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source(dest))
    .pipe(buffer()) // buffer file contents (is this necessary?)
    .pipe(gulp.dest(dir.prod + 'scripts/'))
}