Track http contexts.

@param bundleContext the BundleContext associated with this bundle
@param httpServiceRuntime
347281
private void trackHttpContexts(final BundleContext bundleContext, ExtendedHttpServiceRuntime httpServiceRuntime) {
		final ServiceTracker<HttpContext, HttpContextElement> httpContextTracker = HttpContextTracker
				.createTracker(extenderContext, bundleContext, httpServiceRuntime);

		httpContextTracker.open();
		trackers.add(0, httpContextTracker);

		final ServiceTracker<HttpContextMapping, HttpContextElement> httpContextMappingTracker = HttpContextMappingTracker
				.createTracker(extenderContext, bundleContext, httpServiceRuntime);

		httpContextMappingTracker.open();
		trackers.add(0, httpContextMappingTracker);
	}
237227
public static HttpCallContext set(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext)
	{
		final HttpCallContext ctx = new HttpCallContext(generateTraceId(request), request, response, servletContext);

		contexts.set(ctx);

		return ctx;
	}
70938
public synchronized void setContexts(HttpContext[] contexts)
    {
        List old = Arrays.asList(getContexts());
        
        for (int i=0;i<contexts.length;i++)
        {
            boolean existing=old.remove(contexts[i]);
            if (!existing)
                addContext(contexts[i]);
        }

        for (int i=0;i<old.size();i++)
            removeContext((HttpContext)old.get(i));
    }

    
     */
    public synchronized HttpContext[] getContexts()
    {
        if (_virtualHostMap==null)
            return new HttpContext[0];
        
        ArrayList contexts = new ArrayList(33);
        Iterator maps=_virtualHostMap.values().iterator();
        while (maps.hasNext())
        {
            PathMap pm=(PathMap)maps.next();
            Iterator lists=pm.values().iterator();
            while(lists.hasNext())
            {
                List list=(List)lists.next();
                for (int i=0;i<list.size();i++)
                {
                    HttpContext context=(HttpContext)list.get(i);
                    if (!contexts.contains(context))
                        contexts.add(context);
                }
            }
        }
        return (HttpContext[])contexts.toArray(new HttpContext[contexts.size()]);
    }

     */
    /** Add a context.
     * @param context 
     */
    public HttpContext addContext(HttpContext context)
    {
        if (context.getContextPath()==null ||
            context.getContextPath().length()==0)
            throw new IllegalArgumentException("No Context Path Set");
        boolean existing=removeMappings(context);
        if (!existing)
        {
            context.setHttpServer(this);
            addComponent(context);
        }
        addMappings(context);
        return context;
    }

     */
    /** Remove a context or Web application.
     * @exception IllegalStateException if context not stopped
     */
    public boolean removeContext(HttpContext context)
        throws IllegalStateException
    {
        if (removeMappings(context))
        {
            removeComponent(context);
            if (context.isStarted())
                try{context.stop();} catch (InterruptedException e){log.warn(LogSupport.EXCEPTION,e);}
            context.setHttpServer(null);
            return true;
        }
        return false;
    }
    

     */
    /** Add a context.
     * As contexts cannot be publicly created, this may be used to
     * alias an existing context.
     * @param virtualHost The virtual host or null for all hosts.
     * @param context 
     */
    public HttpContext addContext(String virtualHost,
                                  HttpContext context)
    {
        if (virtualHost!=null)
            context.addVirtualHost(virtualHost);
        addContext(context);
        return context;
    }


     */
    /** Create and add a new context.
     * Note that multiple contexts can be created for the same
     * virtualHost and contextPath. Requests are offered to multiple
     * contexts in the order they where added to the HttpServer.
     * @param contextPath
     * @return A HttpContext instance created by a call to newHttpContext.
     */
    public HttpContext addContext(String contextPath)
    {
        HttpContext hc = newHttpContext();
        hc.setContextPath(contextPath);
        addContext(hc);
        return hc;
    }
    
     */
    /** Create and add a new context.
     * Note that multiple contexts can be created for the same
     * virtualHost and contextPath. Requests are offered to multiple
     * contexts in the order they where added to the HttpServer.
     * @param virtualHost Virtual hostname or null for all hosts.
     * @param contextPathSpec Path specification relative to the context path.
     * @return A HttpContext instance created by a call to newHttpContext.
     */
    public HttpContext addContext(String virtualHost, String contextPathSpec)
    {
        if (virtualHost!=null && virtualHost.length()==0)
            virtualHost=null;
        HttpContext hc = newHttpContext();
        hc.setContextPath(contextPathSpec);
        if (virtualHost!=null)
            hc.addVirtualHost(virtualHost);
        addContext(hc);
        return hc;
    }
    
    
     */
    /** Get specific context. 
     * @param virtualHost The virtual host or null for all hosts.
     * @param contextPathSpec Path specification relative to the context path.
     * @param i Index among contexts of same virtualHost and pathSpec.
     * @return The HttpContext or null.
     */
    public HttpContext getContext(String virtualHost, String contextPathSpec, int i)
    {
        HttpContext hc=null;
        contextPathSpec=HttpContext.canonicalContextPathSpec(contextPathSpec);

        PathMap contextMap=(PathMap)_virtualHostMap.get(virtualHost);
        if (contextMap!=null)
        {
            List contextList = (List)contextMap.get(contextPathSpec);
            if (contextList!=null)
            {
                if (i>=contextList.size())
                    return null;
                hc=(HttpContext)contextList.get(i);
            }
        }

        return hc;
    }

    
     */
    /** Get or create context. 
     * @param virtualHost The virtual host or null for all hosts.
     * @param contextPathSpec
     * @return HttpContext. If multiple contexts exist for the same
     * virtualHost and pathSpec, the most recently added context is returned.
     * If no context exists, a new context is created by a call to newHttpContext.
     */
    public HttpContext getContext(String virtualHost, String contextPathSpec)
    { 
        HttpContext hc=null;
        contextPathSpec=HttpContext.canonicalContextPathSpec(contextPathSpec);
        PathMap contextMap=(PathMap)_virtualHostMap.get(virtualHost);
        
        if (contextMap!=null)
        {
            List contextList = (List)contextMap.get(contextPathSpec);
            if (contextList!=null && contextList.size()>0)
                hc=(HttpContext)contextList.get(contextList.size()-1);
        }
        if (hc==null)
            hc=addContext(virtualHost,contextPathSpec);

        return hc;
    }
    
     */
    /** Get or create context. 
     * @param contextPathSpec Path specification relative to the context path.
     * @return The HttpContext  If multiple contexts exist for the same
     * pathSpec, the most recently added context is returned.
     * If no context exists, a new context is created by a call to newHttpContext.
     */
    public HttpContext getContext(String contextPathSpec)
    {
        return getContext(null,contextPathSpec);
    }    
 
     */
    /** Create a new HttpContext.
     * Specialized HttpServer classes may override this method to
     * return subclasses of HttpContext.
     * @return A new instance of HttpContext or a subclass of HttpContext
     */
    protected HttpContext newHttpContext()
    {
        return new HttpContext();
    }

     */    
    synchronized void addMapping(String virtualHost, HttpContext context)
    {
        // Get the map of contexts
        PathMap contextMap=(PathMap)_virtualHostMap.get(virtualHost);
        if (contextMap==null)
        {
            contextMap=new PathMap(7);
            _virtualHostMap.put(virtualHost,contextMap);
        }
        
        // Generalize contextPath
        String contextPathSpec=
            HttpContext.canonicalContextPathSpec(context.getContextPath());
        
        // Get the list of contexts at this path
        List contextList = (List)contextMap.get(contextPathSpec);
        if (contextList==null)
        {
            contextList=new ArrayList(1);
            contextMap.put(contextPathSpec,contextList);
        }
        
        // Add the context to the list
        contextList.add(context);
            
        if(log.isDebugEnabled())log.debug("Added "+context+" for host "+(virtualHost==null?"*":virtualHost));
    }
175696
protected void registerInstrumentationService(BundleContext systemContext) {
        Instrumentation inst = config.getInstrumentation();
        if (inst != null) {
            // Register a wrapper so we can trace callers.
            inst = (Instrumentation) Proxy.newProxyInstance(TraceInstrumentation.class.getClassLoader(),
                                                            new Class[] { Instrumentation.class },
                                                            new TraceInstrumentation(inst));
            Hashtable<String, String> svcProps = new Hashtable<String, String>();
            systemContext.registerService(Instrumentation.class.getName(), inst, svcProps);
        }
    }
633855
@Override
	public void start(BundleContext context) throws Exception {
		final String sourceMethod = "start"; //$NON-NLS-1$
		boolean isTraceLogging = log.isLoggable(Level.FINER);
		if (isTraceLogging) {
			log.entering(Activator.class.getName(), sourceMethod, new Object[]{context});
		}
		super.start(context);

		// Verify the bundle id.
		if (!context.getBundle().getSymbolicName().equals(BUNDLE_NAME)) {
			throw new IllegalStateException();
		}
		serviceRegistrations = new LinkedList<ServiceRegistration<?>>();
		Activator.context = context;
		Dictionary<String, String> dict = new Hashtable<String, String>();
		dict.put("name", BUNDLE_NAME); //$NON-NLS-1$

		ServiceRegistration<?> commandProviderReg = registerCommandProvider();
		if (commandProviderReg != null) {
			serviceRegistrations.add(commandProviderReg);
		}
		// Create the executors provider.  The executors provider is created by the
		// activator primarily to allow executors to be shared by all of the
		// aggregators created by this bundle.
		dict = new Hashtable<String, String>();
		dict.put("name", BUNDLE_NAME); //$NON-NLS-1$
		executors = newExecutors();
		serviceRegistrations.add(
				context.registerService(IExecutors.class.getName(), executors, dict));

		if (isTraceLogging) {
			log.exiting(Activator.class.getName(), sourceMethod);
		}
	}
73034
private BundleContext getBundleContext(Bundle bundle, long timeout) {
        long endTime = System.currentTimeMillis() + timeout;
        BundleContext bc = null;
        while (bc == null) {
            bc = bundle.getBundleContext();
            if (bc == null) {
                if (System.currentTimeMillis() >= endTime) {
                    throw new TestContainerException(
                        "Unable to retrieve bundle context from bundle " + bundle);
                }
                try {
                    Thread.sleep(100);
                }
                catch (InterruptedException e) {
                    // Ignore
                }
            }
        }
        return bc;
    }
5092
protected void activate(ComponentContext ctxt) {
        this.bundle = ctxt.getUsingBundle();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            Tr.event(this, tc, "Activating for bundle " + this.bundle);
        }

        this.localServlets = new HashSet<Servlet>();
        this.localFilters = new HashSet<Filter>();

        this.contextManager = new ServletContextManager(this.bundle, ctxt.getProperties());
    }
1270106
public void addAppIDHeader(Context contextValue) {
        BaseAppIdentity appIdDetails = new BaseAppIdentity(contextValue);
        headers.add(APPLICATION_BUNDLE_ID, appIdDetails.getId());
    }
1308688
public void stop(BundleContext bc) throws Exception {
		if (httpService != null) {
			bc.ungetService(httpServiceRef);
			httpServiceRef = null;
			httpService = null;
		}
	}
1254163
private void trackWebSockets(final BundleContext bundleContext) {
		final ServiceTracker<Object, WebSocketElement> webSocketTracker = WebSocketTracker.createTracker(extenderContext, bundleContext);
		webSocketTracker.open();
		trackers.add(0, webSocketTracker);
	}
335967
@Override
    public void start(BundleContext context) {

        initialContextFactories = initServiceTracker(context, InitialContextFactory.class, ServiceTrackerCustomizers.ICF_CACHE);
        objectFactories = initServiceTracker(context, ObjectFactory.class, ServiceTrackerCustomizers.URL_FACTORY_CACHE);
        icfBuilders = initServiceTracker(context, InitialContextFactoryBuilder.class, ServiceTrackerCustomizers.LAZY);
        urlObjectFactoryFinders = initServiceTracker(context, URLObjectFactoryFinder.class, ServiceTrackerCustomizers.LAZY);
        environmentAugmentors = initServiceTracker(context, EnvironmentAugmentation.class, null);
        environmentUnaugmentors = initServiceTracker(context, EnvironmentUnaugmentation.class, null);

        try {
            OSGiInitialContextFactoryBuilder builder = new OSGiInitialContextFactoryBuilder();
            setField(InitialContextFactoryBuilder.class, builder, true);
            icfBuilder = builder;
        } catch (IllegalStateException e) {
            // Log the problem at info level, but only log the exception at debug level, as in many cases this is not a real issue and people
            // don't want to see stack traces at info level when everything it working as expected.
            LOGGER.info(Utils.MESSAGES.getMessage("unable.to.set.static.ICFB.already.exists", getClassName(InitialContextFactoryBuilder.class)));
            LOGGER.debug(Utils.MESSAGES.getMessage("unable.to.set.static.ICFB.already.exists", getClassName(InitialContextFactoryBuilder.class)), e);
        }

        try {
            OSGiObjectFactoryBuilder builder = new OSGiObjectFactoryBuilder(context);
            setField(ObjectFactoryBuilder.class, builder, true);
            ofBuilder = builder;
        } catch (IllegalStateException e) {
            // Log the problem at info level, but only log the exception at debug level, as in many cases this is not a real issue and people
            // don't want to see stack traces at info level when everything it working as expected.
            LOGGER.info(Utils.MESSAGES.getMessage("unable.to.set.static.OFB.already.exists", getClassName(ObjectFactoryBuilder.class)));
            LOGGER.debug(Utils.MESSAGES.getMessage("unable.to.set.static.OFB.already.exists", getClassName(ObjectFactoryBuilder.class)), e);
        }

        context.registerService(JNDIProviderAdmin.class.getName(),
                                new ProviderAdminServiceFactory(context),
                                null);

        context.registerService(InitialContextFactoryBuilder.class.getName(),
                                new JREInitialContextFactoryBuilder(),
                                null);

        context.registerService(JNDIContextManager.class.getName(),
                                new ContextManagerServiceFactory(),
                                null);

        context.registerService(AugmenterInvoker.class.getName(),
                                AugmenterInvokerImpl.getInstance(),
                                null);

        //Start the bundletracker that clears out the cache. (only interested in stopping events)
        // bt = new BundleTracker(context, Bundle.STOPPING, new ServiceTrackerCustomizers.CacheBundleTrackerCustomizer());
        // bt.open();
    }
379225
@Activate
    public void startUp(BundleContext bundleContext) {
        extendedBundleContext = new ExtendedBundle.ExtendedBundleContext(bundleContext);
        bundleContext.addBundleListener(this);
    }
800752
private synchronized RemoteBundleContext getRemoteBundleContext() {
        if (remoteBundleContext == null) {

            // !! Absolutely necesary for RMI class loading to work
            // TODO maybe use ContextClassLoaderUtils.doWithClassLoader
            Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
            LOG.info("Waiting for remote bundle context.. on " + registry + " name: " + name
                + " timout: " + rmiLookupTimeout);
            // TODO create registry here
            Throwable reason = null;
            long startedTrying = System.currentTimeMillis();

            do {
                try {
                    remoteBundleContext = (RemoteBundleContext) getRegistry(registry).lookup(name);
                }
                catch (RemoteException e) {
                    reason = e;
                }
                catch (NotBoundException e) {
                    reason = e;
                }
            }
            while (remoteBundleContext == null
                && (rmiLookupTimeout.isNoTimeout() || System.currentTimeMillis() < startedTrying
                    + rmiLookupTimeout.getValue()));
            if (remoteBundleContext == null) {
                throw new RuntimeException("Cannot get the remote bundle context", reason);
            }
            LOG.debug("Remote bundle context found after "
                + (System.currentTimeMillis() - startedTrying) + " millis");
        }
        return remoteBundleContext;

    }
777508
private ContextModel getOrCreateContext(final HttpContext httpContext) {
		// org.osgi.service.http.HttpContext -> org.ops4j.pax.web.service.WebContainerContext
		final WebContainerContext context;
		if (httpContext == null) {
			context = createDefaultHttpContext();
		} else if (!(httpContext instanceof WebContainerContext)) {
			context = new WebContainerContextWrapper(serviceBundle, httpContext);
		} else {
			context = (WebContainerContext) httpContext;
		}

		// sanity check - non shared context should be associated to single bundle
		serverModel.associateHttpContext(context, serviceBundle, httpContext instanceof SharedWebContainerContext);

		ContextModel contextModel = serviceModel.getContextModel(context);
		if (contextModel == null) {
			contextModel = new ContextModel(context, serviceBundle,
					bundleClassLoader);
			contextModel.setVirtualHosts(serverController.getConfiguration()
					.getVirtualHosts());
		}
		return contextModel;
	}
981711
@Override
    public boolean shutdownService(Object service, BundleContext context)
    {
        for (String alias : getAliases())
        {
            HttpServiceTracker serviceTracker = getServiceTracker(context, BaseWebappServlet.ALIAS, alias);
            if (serviceTracker != null)
                serviceTracker.close();
        }
        return true;
    }
979480
protected void registerPauseableComponentController(BundleContext systemContext) {
        PauseableComponentControllerImpl pauseableComponentController = new PauseableComponentControllerImpl(systemContext);
        if (pauseableComponentController != null) {
            Hashtable<String, String> svcProps = new Hashtable<String, String>();
            systemContext.registerService(PauseableComponentController.class.getName(), pauseableComponentController, svcProps);
        }
    }
513599
private static BundleContext checkBundleContext() {
        if (bundleContext == null) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "BundleContext is null and should not be");
            }
        }
        return bundleContext;
    }