should be using the ServiceRegistry, but getting it from the SessionFactory at startup fails in Spring
486137
protected DialectFactory createDialectFactory() {
        DialectFactoryImpl factory = new DialectFactoryImpl();
        factory.injectServices(new ServiceRegistryImplementor() {

            @Override
            public <R extends Service> R getService(Class<R> serviceRole) {
                if (serviceRole == DialectResolver.class) {
                    return (R) new StandardDialectResolver();
                } else if (serviceRole == StrategySelector.class) {
                    return (R) new StrategySelectorImpl(new ClassLoaderServiceImpl(Thread.currentThread().getContextClassLoader()));
                }
                return null;
            }

            @Override
            public <R extends Service> ServiceBinding<R> locateServiceBinding(Class<R> serviceRole) {
                return null;
            }

            @Override
            public void destroy() {

            }

            @Override
            public void registerChild(ServiceRegistryImplementor child) {
            }

            @Override
            public void deRegisterChild(ServiceRegistryImplementor child) {
            }

            @Override
            public ServiceRegistry getParentServiceRegistry() {
                return null;
            }
        });
        return factory;
    }
155808
@Override
  public ServiceRefAmp session(String name)
  {
    String address = "session:///" + name + "/";
    
    return sessionImpl(address);
  }
805467
private static Object findJarServiceProvider(final String factoryId) throws ConfigurationError {

        final String serviceId = "META-INF/services/" + factoryId;
        InputStream is = null;

        // First try the Context ClassLoader
        ClassLoader cl = ss.getContextClassLoader();
        if (cl != null) {
            is = ss.getResourceAsStream(cl, serviceId);

            // If no provider found then try the current ClassLoader
            if (is == null) {
                cl = FactoryFinder.class.getClassLoader();
                is = ss.getResourceAsStream(cl, serviceId);
            }
        } else {
            // No Context ClassLoader, try the current
            // ClassLoader
            cl = FactoryFinder.class.getClassLoader();
            is = ss.getResourceAsStream(cl, serviceId);
        }

        if (is == null) {
            // No provider found
            return null;
        }

        dPrint("found jar resource=" + serviceId + " using ClassLoader: " + cl);

        // Read the service provider name in UTF-8 as specified in
        // the jar spec. Unfortunately this fails in Microsoft
        // VJ++, which does not implement the UTF-8
        // encoding. Theoretically, we should simply let it fail in
        // that case, since the JVM is obviously broken if it
        // doesn't support such a basic standard. But since there
        // are still some users attempting to use VJ++ for
        // development, we have dropped in a fallback which makes a
        // second attempt using the platform's default encoding. In
        // VJ++ this is apparently ASCII, which is a subset of
        // UTF-8... and since the strings we'll be reading here are
        // also primarily limited to the 7-bit ASCII range (at
        // least, in English versions), this should work well
        // enough to keep us on the air until we're ready to
        // officially decommit from VJ++. [Edited comment from
        // jkesselm]
        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        } catch (final java.io.UnsupportedEncodingException e) {
            rd = new BufferedReader(new InputStreamReader(is));
        }

        String factoryClassName = null;
        try {
            // XXX Does not handle all possible input as specified by the
            // Jar Service Provider specification
            factoryClassName = rd.readLine();
            rd.close();
        } catch (final IOException x) {
            // No provider found
            return null;
        }

        if (factoryClassName != null && !"".equals(factoryClassName)) {
            dPrint("found in resource, value=" + factoryClassName);

            // Note: here we do not want to fall back to the current
            // ClassLoader because we want to avoid the case where the
            // resource file was found using one ClassLoader and the
            // provider class was instantiated using a different one.
            return newInstance(factoryClassName, cl, false);
        }

        // No provider found
        return null;
    }
255850
@Override
	public void registerServlet(final String alias, final Servlet servlet,
								@SuppressWarnings("rawtypes") final Dictionary initParams,
								final HttpContext httpContext) throws ServletException,
			NamespaceException {
		LOG.warn("Http service has already been stopped");
	}
1141975
@Override
    public SessionFactory provide() {
        logger.trace("Creating hibernate session factory.");

        // Build the service registry.
        SessionFactory factory = new MetadataSources(serviceRegistry)
                .buildMetadata()
                .buildSessionFactory();

        // Register our event listeners.
        injectEventListeners(((SessionFactoryImpl) factory)
                .getServiceRegistry());

        return factory;
    }
201298
protected void registerSelf() {
        publishSelf();
        serviceRegistry.get().registerService(getServiceDescription());
        serviceRegistry.get().subscribe((pair, err) -> {
            serviceEvent(pair.car(), pair.cdr(), err);
        });
        heartBeat();
        Log.Info(this, "registered at serviceRegistry.");
    }
268197
def register(self, service, name=''):
        
        # expose a sub-factory
        if isinstance(service, ApiFactory):
            self.services[name] = (service.factory, None)

        # expose a module dynamically as a service
        elif inspect.ismodule(service):
            name = name or service.__name__.split('.')[-1]

            # exclude endpoints with patterns
            for obj in vars(service).values():
                endpoint = getattr(obj, 'endpoint', None)
                if isinstance(endpoint, Endpoint) and endpoint.pattern:
                    route = Route('', endpoint.pattern)
                    self.routes.append((route, endpoint))

            self.services[name] = (ModuleService, service)

        # expose a class dynamically as a service
        elif inspect.isclass(service):
            name = name or service.__name__
            self.services[name] = (ClassService, service)

        # expose an endpoint directly
        elif isinstance(getattr(service, 'endpoint', None), Endpoint):
            if service.endpoint.pattern:
                route = Route('', service.endpoint.pattern)
                self.routes.append((route, service.endpoint))
            else:
                self.services[service.endpoint.name] = (service.endpoint, None)

        # expose a scope
        elif isinstance(service, dict):
            for srv in service.values():
                try:
                    self.register(srv)
                except RuntimeError:
                    pass

        # expose a list of services
        elif isinstance(service, list):
            for srv in service:
                try:
                    self.register(srv)
                except RuntimeError:
                    pass

        # expose a service directly
        else:
            raise RuntimeError('Invalid service provide: {0} ({1}).'.format(service, type(service)))
949027
@Override
    public void start(BundleContext ctx) throws Exception {
        // Call the base EclipseLink provider to register it within the service registry
        // There is currently a bug in the base class where it registers the provider name
        // using the incorrect property.  This prevents the service locator from finding
        // more than one JPA provider.  For now, register the EclipseLink provider here instead of
        // calling super to do the registration.
        // super.start(ctx);

        // Register the EclipseLink provider
        PersistenceProvider provider = new org.eclipse.persistence.jpa.PersistenceProvider();
        Hashtable<String, Object> props = new Hashtable<String, Object>();
        props.put(PERSISTENCE_PROVIDER, EL_OSGI_PERSISTENCE_PROVIDER);
        props.put("javax.persistence.provider", EL_OSGI_PERSISTENCE_PROVIDER);
        props.put("osgi.jpa.provider.version", "1.3.0");
        props.put(JPA_WEAVING_PACKAGES, JPA_PACKAGES);
        elSvcReg = ctx.registerService(PERSISTENCE_PROVIDER, provider, props);
    }
521335
public void registerUserService() throws Exception {
		Debug.logVerbose("[JdonFramework] note: registe user pojoservice ", module);
		try {
			TargetMetaDefXmlLoader targetMetaDefXmlLoader = (TargetMetaDefXmlLoader) containerWrapper.lookup(ComponentKeys.SERVICE_METALOADER_NAME);
			targetMetaDefXmlLoader.loadXML();
			TargetMetaDefHolder targetMetaDefHolder = (TargetMetaDefHolder) containerWrapper.lookup(ComponentKeys.SERVICE_METAHOLDER_NAME);
			if (targetMetaDefHolder == null)
				return;
			Map metaDefs = targetMetaDefHolder.loadMetaDefs();
			Iterator iter = metaDefs.keySet().iterator();
			while (iter.hasNext()) {
				String name = (String) iter.next();
				TargetMetaDef tgm = (TargetMetaDef) metaDefs.get(name);
				if (!tgm.isEJB()) {
					xmlcontainerRegistry.registerPOJOTargetMetaDef((POJOTargetMetaDef) tgm);
				}
			}
		} catch (Exception ex) {
			Debug.logError("[JdonFramework] registerUserService error:" + ex, module);
			throw new Exception(ex);
		}
	}
513886
public void start()
   {
      // responsible for:
      // 1. reading parameters (such as repoWorkspaceName, repoPath) from
      // registryService (if present) or init params
      // 2. initializing artifact service Registry Entry if registryService is
      // present
      // if Entry is not initialized yet (first launch)
      // 3. initializing maven root if not initialized

      if (LOG.isDebugEnabled())
      {
         LOG.debug("Starting ArtifactManagingService ...");
      }

      sessionProvider = SessionProvider.createSystemProvider();

      try
      {
         InputStream xml = getClass().getResourceAsStream(NT_FILE);
         ManageableRepository rep = repositoryService.getCurrentRepository();
         rep.getNodeTypeManager().registerNodeTypes(xml, ExtendedNodeTypeManager.IGNORE_IF_EXISTS,
            NodeTypeDataManager.TEXT_XML);
         readParamsFromRegistryService(sessionProvider);
         prepareRootNode(sessionProvider, rootNodePath);
      }
      catch (PathNotFoundException e)
      {
         try
         {
            readParamsFromFile();
            writeParamsToRegistryService(sessionProvider);

            prepareRootNode(sessionProvider, rootNodePath);
         }
         catch (RepositoryException exc)
         {
            LOG.error("Cannot write init configuration to RegistryService", exc);
         }
         catch (IOException exc)
         {
            LOG.error("Cannot write init configuration to RegistryService", exc);
         }
         catch (SAXException exc)
         {
            LOG.error("Cannot write init configuration to RegistryService", exc);
         }
         catch (ParserConfigurationException exc)
         {
            LOG.error("Cannot write init configuration to RegistryService", exc);
         }
      }
      catch (RepositoryException e)
      {
         LOG.error("Error while register nodetypes/checking existance", e);
      }
      finally
      {
         sessionProvider.close();
      }
   }
460102
public void init(String webAppRfsPath, String servletMapping, String defaultWebApplication) {

        try {
            // explicit set to null to overwrite exiting values from session
            m_availableModules = null;
            m_fullDatabaseKey = null;
            m_databaseKey = null;
            m_databaseKeys = null;
            m_databaseProperties = null;
            m_configuration = null;
            m_installModules = null;
            m_moduleDependencies = null;
            m_sortedDatabaseKeys = null;
            m_moduleFilenames = null;

            if (servletMapping == null) {
                servletMapping = "/opencms/*";
            }
            if (defaultWebApplication == null) {
                defaultWebApplication = "ROOT";
            }
            m_servletMapping = servletMapping;
            m_defaultWebApplication = defaultWebApplication;

            setWebAppRfsPath(webAppRfsPath);
            m_errors = new ArrayList<String>();

            if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(webAppRfsPath)) {
                m_configuration = new CmsParameterConfiguration(m_configRfsPath + CmsSystemInfo.FILE_PROPERTIES);
                readDatabaseConfig();
            }

            if (m_workplaceImportThread != null) {
                if (m_workplaceImportThread.isAlive()) {
                    m_workplaceImportThread.kill();
                }
                m_workplaceImportThread = null;
                m_newLoggingOffset = 0;
                m_oldLoggingOffset = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            m_errors.add(e.toString());
        }
    }
714678
private static ServiceRegistrarFactory createFactory(final Path path) {
    final ServiceRegistrarFactory factory;
    final Path absolutePath = path.toAbsolutePath();
    try {
      factory = ServiceRegistrarLoader.load(absolutePath);
      final String name = factory.getClass().getName();
      log.info("Loaded service registrar plugin: {} ({})", name, absolutePath);
    } catch (ServiceRegistrarLoadingException e) {
      throw new RuntimeException("Unable to load service registrar plugin: "
                                 + absolutePath, e);
    }
    return factory;
  }
702203
function(serviceRegistry) {
			this._serviceRegistry = serviceRegistry;
			this._prefService = serviceRegistry.getService("orion.core.preference"); //$NON-NLS-1$

			if (this._prefService) {
				// Get the overrides from the preference store
				this._getBindingOverrides().then(function(overrides) {
					this._bindingOverrides = overrides;
					
					// Update all folks that are listening
					this._updateBindingOverrides();
				}.bind(this));
	
				// listen for changes from other pages
				this._prefService.addEventListener("changed", function (e) {
					if (e.namespace === "/KeyBindings") { //$NON-NLS-1$
						// Refresh the binding overrides
						this._getBindingOverrides().then(function(overrides) {
							if (overrides.length > this._bindingOverrides.length) {
								// handle any new changes
								for (var i = this._bindingOverrides.length; i < overrides.length; i++) {
									var override = overrides[i];
									var bindingChangeEvent = {type: "bindingChanged", id: override.id, newBinding: override.newBinding,  //$NON-NLS-1$
																prevBinding: override.prevBinding};
									this.dispatchEvent(bindingChangeEvent);
								}
							}
							this._bindingOverrides = overrides;
						}.bind(this));
					}
				}.bind(this));
			}
		}
90810
public static RegisteredService getRegisteredService(final RequestContext context) {
        return context != null ? (RegisteredService) context.getFlowScope().get(PARAMETER_REGISTERED_SERVICE) : null;
    }
305119
@SuppressWarnings("unchecked")
  private RaftServiceContext initializeService(PrimitiveId primitiveId, PrimitiveType primitiveType, String serviceName, byte[] config) {
    RaftServiceContext oldService = raft.getServices().getService(serviceName);
    ServiceConfig serviceConfig = config == null ? new ServiceConfig() : Serializer.using(primitiveType.namespace()).decode(config);
    RaftServiceContext service = new RaftServiceContext(
        primitiveId,
        serviceName,
        primitiveType,
        serviceConfig,
        primitiveType.newService(serviceConfig),
        raft,
        threadContextFactory);
    raft.getServices().registerService(service);

    // If a service with this name was already registered, remove all of its sessions.
    if (oldService != null) {
      raft.getSessions().removeSessions(oldService.serviceId());
    }
    return service;
  }
961872
@SuppressWarnings("unchecked")
    public static <E> ServiceRegistry<E> getInstance() {
        if (instance == null) {
            synchronized (ServiceRegistry.class) {
                if (instance == null) {
                    instance = new ServiceRegistry<E>();
                }
            }
        }
        return instance;
    }
685608
@Override
    public QueryDefinition registerQuery(QueryDefinition queryDefinition) {
        QueryDefinition result = null;
        if (config.isRest()) {

            Map<String, Object> valuesMap = new HashMap<String, Object>();
            valuesMap.put(QUERY_NAME, queryDefinition.getName());

            result = makeHttpPostRequestAndCreateCustomResponse(build(loadBalancer.getUrl(), QUERY_DEF_URI + "/" + CREATE_QUERY_DEF_POST_URI, valuesMap), queryDefinition, QueryDefinition.class);

        } else {
            CommandScript script = new CommandScript(Collections.singletonList((KieServerCommand) new DescriptorCommand("QueryDataService", "registerQuery", serialize(queryDefinition), marshaller.getFormat().getType(), new Object[]{queryDefinition.getName()})));
            ServiceResponse<QueryDefinition> response = (ServiceResponse<QueryDefinition>) executeJmsCommand(script, DescriptorCommand.class.getName(), "BPM").getResponses().get(0);

            throwExceptionOnFailure(response);
            if (shouldReturnWithNullResponse(response)) {
                return null;
            }
            result = response.getResult();
        }

        return result;
    }