/*
Maps a default context (whithout whiteboard-service) to a ServletContextDTO
7435
private ServletContextDTO mapServletContext(Map.Entry<ServiceReference<ServletContext>, ServletContext> mapEntry) {
        final ServiceReference<ServletContext> ref = mapEntry.getKey();
        final ServletContext servletContext = mapEntry.getValue();

        ServletContextDTO dto = new ServletContextDTO();
        dto.serviceId = (long) ref.getProperty(Constants.SERVICE_ID);
        // the actual ServletContext might use "" instead of "/" (depends on the
        // container). DTO must use "/" for root
        dto.contextPath = servletContext.getContextPath().trim().length() == 0 ? "/" : servletContext.getContextPath();
        dto.name = servletContext.getServletContextName();

        dto.attributes = Collections.list(servletContext.getAttributeNames()).stream()
                .map(name -> new SimpleEntry<>(name, servletContext.getAttribute(name)))
                .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));
        dto.initParams = Collections.list(servletContext.getInitParameterNames()).stream()
                .map(name -> new SimpleEntry<>(name, servletContext.getInitParameter(name)))
                .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));

        return dto;
    }
662729
function Context() {
	/**
	 * @member {Object}
	 * @property {Object} client
	 * @property {Object<Call>} client.map - map from call name and call id
	 * @property {Array<Call>} client.list
	 * @property {Object} server
	 * @property {Object<Call>} server.map - map from call name and call id
	 * @property {Array<Call>} server.list
	 * @private
	 */
	this._calls = {
		client: {
			map: Object.create(null),
			list: []
		},
		server: {
			map: Object.create(null),
			list: []
		}
	}

	/**
	 * @member {Object}
	 * @property {Object} client
	 * @property {Object<Message>} client.map - map from message name and message id
	 * @property {Array<Message>} client.list
	 * @property {Object} server
	 * @property {Object<Message>} server.map - map from message name and message id
	 * @property {Array<Message>} server.list
	 * @private
	 */
	this._messages = {
		client: {
			map: Object.create(null),
			list: []
		},
		server: {
			map: Object.create(null),
			list: []
		}
	}
}
399769
protected String resolveResourceContextPath(HttpServletRequest request, String resource) {
        final String resourceContextPath = this.getResourceServerContextPath();
        
        this.logger.debug("Attempting to locate resource serving webapp with context path: {}", resourceContextPath);
        
        //Try to resolve the 
        final ServletContext resourceContext = this.servletContext.getContext(resourceContextPath);
        if (resourceContext == null || !resourceContextPath.equals(resourceContext.getContextPath())) {
            this.logger.warn("Could not find resource serving webapp under context path {} ensure the resource server is deployed and cross context dispatching is enable for this web application", resourceContextPath);
            return request.getContextPath();
        }
        
        this.logger.debug("Found resource serving webapp at: {}", resourceContextPath);
        
        URL url = null;
        try {
            url = resourceContext.getResource(resource);
        }
        catch (MalformedURLException e) {
            //Ignore
        }
        
        if (url == null) {
            this.logger.debug("Resource serving webapp {} doesn't contain resource {} Falling back to the local resource.", resourceContextPath, resource);
            return request.getContextPath();
        }
        
        this.logger.debug("Resource serving webapp {} contains resource {} Using resource server.", resourceContextPath, resource);
        return resourceContextPath;
    }
1204813
@Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

        // The jerseyServletModule injects the servicing classes using guice,
        // instead of letting jersey do it natively
        AbstractJoynrServletModule jerseyServletModule = getJoynrServletModule();
        List<Module> joynrModules = getJoynrModules();
        joynrModules.add(jerseyServletModule);

        injector = Guice.createInjector(joynrModules);

        //registerGuiceFilter(servletContextEvent);

        super.contextInitialized(servletContextEvent);
    }
707268
@Override
    public void contextInitialized(ServletContextEvent event) {
        // On Windows, URL caches can cause problems, particularly with
        // undeployment
        // So, here we attempt to disable them if we detect that we are running
        // on Windows
        try {
            String osName = System.getProperty("os.name");

            if (osName != null && osName.toLowerCase().contains("windows")) {
                URL url = new URL("http://localhost/");
                URLConnection urlConn = url.openConnection();
                urlConn.setDefaultUseCaches(false);
            }
        } catch (Throwable t) {
            // Any errors thrown in disabling the caches aren't significant to
            // the normal execution of the application, so we ignore them
        }
    }
1367340
public void plug(final Map<String, Object> dataModel, final RequestContext context) {
        String content = (String) dataModel.get(Plugin.PLUGINS);

        if (null == content) {
            dataModel.put(Plugin.PLUGINS, "");
        }

        handleLangs(dataModel);
        fillDefault(dataModel);

        postPlug(dataModel, context);

        content = (String) dataModel.get(Plugin.PLUGINS);
        final StringBuilder contentBuilder = new StringBuilder(content);

        contentBuilder.append(getViewContent(dataModel));

        final String pluginsContent = contentBuilder.toString();

        dataModel.put(Plugin.PLUGINS, pluginsContent);

        LOGGER.log(Level.DEBUG, "Plugin[name={0}] has been plugged", getName());

    }
751296
public static <T> T getContext(ELContext context, Class<T> key, T defaultValue) {
        @SuppressWarnings("unchecked")
        final T result = (T) context.getContext(key);
        return result == null ? defaultValue : result;
    }
242048
function createContext(req, res, context, done) {
  debug('default createContext - does nothing', context);
  process.nextTick(done.bind(null, null, context));
}
900796
public static GeoLocationRequest getHttpServletRequestGeoLocationFromRequestContext(final RequestContext context) {
        val servletRequest = getHttpServletRequestFromExternalWebflowContext(context);
        return getHttpServletRequestGeoLocation(servletRequest);
    }
324268
public static final <T> T getContextAttribute(HttpServlet servlet, String name, Class<T> cls, Set<GetOpts> opts, T defaultValue)
	{
		return getContextAttribute((ServletConfig)servlet, name, cls, opts, defaultValue);
	}
1075171
private ApiResponse buildResponseFromContext(Context c) {
		Map<String, String> fields = new HashMap<>();
		fields.put("name", c.getName());
		fields.put("id", Integer.toString(c.getIndex()));
		fields.put("description", c.getDescription());
		fields.put("inScope", Boolean.toString(c.isInScope()));
		fields.put("excludeRegexs", jsonEncodeList(c.getExcludeFromContextRegexs()));
		fields.put("includeRegexs", jsonEncodeList(c.getIncludeInContextRegexs()));
		
		AuthenticationMethod authenticationMethod = c.getAuthenticationMethod();
		if(authenticationMethod != null){
			Pattern pattern = authenticationMethod.getLoggedInIndicatorPattern();
			fields.put("loggedInPattern",  pattern == null ? "" : pattern.toString());
			pattern = authenticationMethod.getLoggedOutIndicatorPattern();
			fields.put("loggedOutPattern", pattern == null ? "" : pattern.toString());
			AuthenticationMethodType type = authenticationMethod.getType();
			fields.put("authType", type == null ? "" : type.getName());
		}
		
		AuthorizationDetectionMethod authorizationDetectionMethod = c.getAuthorizationDetectionMethod();
		if(authorizationDetectionMethod != null){
			fields.put("authenticationDetectionMethodId",String.valueOf(authorizationDetectionMethod.getMethodUniqueIdentifier()));
		}
		
		fields.put("urlParameterParserClass", c.getUrlParamParser().getClass().getCanonicalName());
		fields.put("urlParameterParserConfig", c.getUrlParamParser().getConfig());
		fields.put("postParameterParserClass", c.getPostParamParser().getClass().getCanonicalName());
		fields.put("postParameterParserConfig", c.getPostParamParser().getConfig());
		
		return new ApiResponseSet<String>("context", fields);
	}
803378
public static ServletResponse getContextResponse()
    {
        ServiceContext context = (ServiceContext) _localContext.get();

        if (context != null)
            return context._response;
        else
            return null;
    }
1085518
@Override
    public void contextInitialized(final ServletContextEvent servletContextEvent) {
        servletContext = servletContextEvent.getServletContext();

        Latkes.init();
        LOGGER.info("Initializing the context....");

        Latkes.setLocale(Locale.SIMPLIFIED_CHINESE);
        LOGGER.log(Level.INFO, "Default locale [{0}]", Latkes.getLocale());

        final String realPath = servletContext.getRealPath("/");
        LOGGER.log(Level.INFO, "Server [realPath={0}, contextPath={1}]", realPath, servletContext.getContextPath());

        try {
            final Collection<Class<?>> beanClasses = Discoverer.discover(Latkes.getScanPath());
            BeanManager.start(beanClasses);
        } catch (final Exception e) {
            LOGGER.log(Level.ERROR, "Initializes request processors failed", e);

            throw new IllegalStateException("Initializes request processors failed");
        }
    }
299738
function ComponentContext(zuixInstance, options, eventCallback) {
    zuix = zuixInstance;
    this._options = null;
    this.contextId = (options == null || options.contextId == null) ? null : options.contextId;
    this.componentId = null;
    this.trigger = function(context, eventPath, eventValue) {
        if (typeof eventCallback === 'function') {
            eventCallback(context, eventPath, eventValue);
        }
    };

    /** @protected */
    this._container = null;

    /** @protected */
    this._model = null;
    /** @protected */
    this._view = null;
    /** @protected */
    this._css = null;
    /** @protected */
    this._style = null;
    /**
     * @protected
     * @type {ContextControllerHandler}
     */
    this._controller = null;

    /**
     * Define the local behavior handler for this context instance only.
     * Any global behavior matching the same `componentId` will be overridden.
     *
     * @function behavior
     * @param handler_fn {function}
     */
    this.behavior = null;

    /** @package */
    this._eventMap = [];
    /** @package */
    this._behaviorMap = [];

    /**
     * @package
     * @type {ContextController}
     */
    this._c = null;

    this.options(options);

    return this;
}
479823
function(contextObj) {
        if(contextObj === undefined) {
            contextObj = {};
        }
        var context = new Array(this.dimensionsList.length);
        for(var i=0; i<this.dimensionsList.length; i++) {
            var dimension = this.dimensionsList[i];
            if(contextObj.hasOwnProperty(dimension)) {
                var value = contextObj[dimension];
                if(value.constructor === Array) {
                    var newValue = [];
                    for(var j=0; j<value.length; j++) {
                        var numValue = this.valueToNumber[dimension][value[j]];
                        if(numValue !== undefined) {
                            newValue.push(numValue);
                        }
                    }
                    if(newValue.length) {
                        context[i] = newValue;
                        continue;
                    }
                } else {
                    numValue = this.valueToNumber[dimension][value];
                    if(numValue !== undefined) {
                        context[i] = numValue;
                        continue;
                    }
                }
            }
            context[i] = 0;
        }
        return context;
    }
1308319
public static ServiceContext createServiceContext(ServletRequest request) {
        if (!(request instanceof HttpServletRequest)) {
            throw new IllegalArgumentException("Expected HttpServletRequest");
        }
        return createServiceContext((HttpServletRequest) request);
    }
612387
public void contextInitialized(ServletContextEvent servletContextEvent) {
		ServletContext servletContext = servletContextEvent.getServletContext();

		File tempWriteDir = (File) servletContext
				.getAttribute("javax.servlet.context.tempdir");
		servletContext.setAttribute("audioFilePath", FILE_PROTOCOL + tempWriteDir
				.getAbsolutePath() + File.separatorChar);
		for (int i = 0; i < AUDIO_FILES.length; i++) {
			String audioFile = AUDIO_FILES[i];
			logger.info("Writing " + audioFile + " to webapp temp dir : "
					+ tempWriteDir);			
			InputStream is = servletContext.getResourceAsStream(AUDIO_DIR + "/" + audioFile);
			copyToTempDir(is, tempWriteDir, audioFile);
		} 

		Enumeration<String> initParamNames = servletContext
				.getInitParameterNames();
		logger.info("Setting init Params into application context");
		while (initParamNames.hasMoreElements()) {
			String initParamName = (String) initParamNames.nextElement();
			servletContext.setAttribute(initParamName, servletContext
					.getInitParameter(initParamName));
			logger.info("Param key=" + initParamName + ", value = "
					+ servletContext.getInitParameter(initParamName));
		}
		// map acting as a registrar
		servletContext.setAttribute("registeredUsersMap", new HashMap<String, String>());
		
		if(servletContextEvent.getServletContext().getAttribute(MS_CONTROL_FACTORY) == null) {
			DriverImpl d = new DriverImpl();
			properties = new Properties();
			properties.setProperty(MGCP_STACK_NAME, "SipServlets");
			properties.setProperty(MGCP_PEER_IP, PEER_ADDRESS);
			properties.setProperty(MGCP_PEER_PORT, MGW_PORT);
	
			properties.setProperty(MGCP_STACK_IP, LOCAL_ADDRESS);
			properties.setProperty(MGCP_STACK_PORT, CA_PORT);
	
			try {
				// create the Media Session Factory
				final MsControlFactory msControlFactory = new DriverImpl().getFactory(properties); 
				MsControlObjects.msControlFactory = msControlFactory;
				servletContextEvent.getServletContext().setAttribute(MS_CONTROL_FACTORY, msControlFactory);
				
				MMSUtil.msControlFactory = MsControlObjects.msControlFactory;
				String pathToAudioDirectory = (String)servletContextEvent.getServletContext().getAttribute("audioFilePath");
				MMSUtil.audioFilePath = pathToAudioDirectory;
				logger.info("started MGCP Stack on " + LOCAL_ADDRESS + "and port " + CA_PORT + " obj: " + MsControlObjects.msControlFactory);
			} catch (Exception e) {
				logger.error("couldn't start the underlying MGCP Stack", e);
			}
		} else {
			logger.info("MGCP Stack already started on " + LOCAL_ADDRESS + "and port " + CA_PORT);
		}
	}