Java Code Examples for javax.servlet.ServletContext#getInitParameter()

The following examples show how to use javax.servlet.ServletContext#getInitParameter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set a system property to the web application root directory.
 * The key of the system property can be defined with the "webAppRootKey"
 * context-param in {@code web.xml}. Default is "webapp.root".
 * <p>Can be used for tools that support substitution with {@code System.getProperty}
 * values, like log4j's "${key}" syntax within log file locations.
 * @param servletContext the servlet context of the web application
 * @throws IllegalStateException if the system property is already set,
 * or if the WAR file is not expanded
 * @see #WEB_APP_ROOT_KEY_PARAM
 * @see #DEFAULT_WEB_APP_ROOT_KEY
 * @see WebAppRootListener
 * @see Log4jWebConfigurer
 */
public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
	Assert.notNull(servletContext, "ServletContext must not be null");
	String root = servletContext.getRealPath("/");
	if (root == null) {
		throw new IllegalStateException(
				"Cannot set web app root system property when WAR file is not expanded");
	}
	String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
	String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
	String oldValue = System.getProperty(key);
	if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
		throw new IllegalStateException("Web app root system property already set to different value: '" +
				key + "' = [" + oldValue + "] instead of [" + root + "] - " +
				"Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
	}
	System.setProperty(key, root);
	servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");
}
 
Example 2
Source File: MonitorServlet.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** Read settings from web.xml and use them to initialise the service */
public void init() {
    try {
        ServletContext context = getServletContext();

        // load the urls of the required interfaces
        Map<String, String> urlMap = new Hashtable<String, String>();
        String engineGateway = context.getInitParameter("EngineGateway");
        if (engineGateway != null) urlMap.put("engineGateway", engineGateway);
        String engineLogGateway = context.getInitParameter("EngineLogGateway");
        if (engineGateway != null) urlMap.put("engineLogGateway", engineLogGateway);
        String resourceGateway = context.getInitParameter("ResourceGateway");
        if (engineGateway != null) urlMap.put("resourceGateway", resourceGateway);
        String resourceLogGateway = context.getInitParameter("ResourceLogGateway");
        if (resourceLogGateway != null) urlMap.put("resourceLogGateway", resourceLogGateway);

        MonitorClient.getInstance().initInterfaces(urlMap); 
    }
    catch (Exception e) {
        LogManager.getLogger(this.getClass()).error("Monitor Service Initialisation Exception", e);
    }
}
 
Example 3
Source File: ELInterpreterFactory.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Obtain the correct EL Interpreter for the given web application.
 */
public static ELInterpreter getELInterpreter(ServletContext context)
        throws Exception {

    ELInterpreter result = null;

    // Search for an implementation
    // 1. ServletContext attribute (set by application or cached by a
    //    previous call to this method).
    Object attribute = context.getAttribute(EL_INTERPRETER_CLASS_NAME);
    if (attribute instanceof ELInterpreter) {
        return (ELInterpreter) attribute;
    } else if (attribute instanceof String) {
        result = createInstance(context, (String) attribute);
    }

    // 2. ServletContext init parameter
    if (result == null) {
        String className =
                context.getInitParameter(EL_INTERPRETER_CLASS_NAME);
        if (className != null) {
            result = createInstance(context, className);
        }
    }

    // 3. Default
    if (result == null) {
        result = DEFAULT_INSTANCE;
    }

    // Cache the result for next time
    context.setAttribute(EL_INTERPRETER_CLASS_NAME, result);
    return result;
}
 
Example 4
Source File: SamlServletExtension.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static InputStream getXMLFromServletContext(ServletContext servletContext) {
    String json = servletContext.getInitParameter(AdapterConstants.AUTH_DATA_PARAM_NAME);
    if (json == null) {
        return null;
    }
    return new ByteArrayInputStream(json.getBytes());
}
 
Example 5
Source File: ServletContextParameterFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setServletContext(ServletContext servletContext) {
	if (this.initParamName == null) {
		throw new IllegalArgumentException("initParamName is required");
	}
	this.paramValue = servletContext.getInitParameter(this.initParamName);
	if (this.paramValue == null) {
		throw new IllegalStateException("No ServletContext init parameter '" + this.initParamName + "' found");
	}
}
 
Example 6
Source File: WorkletGateway.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void init() {
    if (!WorkletConstants.wsInitialised) {
        try {
            _ws = WorkletService.getInstance();
            _ws.setupEngineClient();
            _rdr = _ws.getRdrInterface();
            ServletContext context = getServletContext();

            WorkletConstants.setHomeDir(context.getRealPath("/"));

            String persistStr = context.getInitParameter("EnablePersistence");
            WorkletConstants.setPersist(persistStr.equalsIgnoreCase("TRUE"));

            WorkletConstants.setResourceServiceURL(context.getInitParameter("ResourceServiceURL"));

            String engineURI = context.getInitParameter("InterfaceB_BackEnd");
            _ws.getEngineClient().initEngineURI(engineURI);

            String ixStr = context.getInitParameter("EnableExceptionHandling");
            boolean exceptionHandlingEnabled = ixStr != null && ixStr.equalsIgnoreCase("TRUE");
            _ws.setExceptionServiceEnabled(exceptionHandlingEnabled);

            String engineLogonName = context.getInitParameter("EngineLogonUserName");
            String engineLogonPassword = context.getInitParameter("EngineLogonPassword");
            _sessions = new Sessions();
            _sessions.setupInterfaceA(engineURI.replaceFirst("/ib", "/ia"),
                    engineLogonName, engineLogonPassword);

            _ws.completeInitialisation();
        } catch (Exception e) {
            _log.error("Gateway Initialisation Exception", e);
        } finally {
            WorkletConstants.setServicetInitialised();
        }
    }
}
 
Example 7
Source File: JWTAuthenticationFilter.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
@Override
public void setServletContext(final ServletContext servletContext) {

    final Map<String, String> configuration = new HashMap<>();

    final Enumeration parameters = servletContext.getInitParameterNames();
    while (parameters.hasMoreElements()) {

        final String key = String.valueOf(parameters.nextElement());
        final String value = servletContext.getInitParameter(key);

        configuration.put(key, value);

    }

    final NodeImpl node = new NodeImpl(true,
            configuration.get(NodeService.NODE_ID),
            configuration.get(NodeService.NODE_TYPE),
            configuration.get(NodeService.NODE_CONFIG),
            configuration.get(NodeService.CLUSTER_ID),
            configuration.get(NodeService.VERSION),
            configuration.get(NodeService.BUILD_NO),
            true
    );
    node.setChannel(configuration.get(NodeService.CHANNEL));

    this.systemName = node.getId().concat("_").concat(node.getFullVersion());

    super.setServletContext(servletContext);
}
 
Example 8
Source File: CartSyncEventHandlerWrapper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ServletContext context) throws EventHandlerException {
    String targetHandlersStr = context.getInitParameter("cartUpdateSyncServiceHandlers");
    if (UtilValidate.isNotEmpty(targetHandlersStr)) {
        targetHandlers = UtilMisc.unmodifiableHashSetCopy(Arrays.asList(targetHandlersStr.split(",")));
    }
}
 
Example 9
Source File: RequestHandler.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
private RequestHandler(ServletContext context) {
    // init the ControllerConfig, but don't save it anywhere, just load it into the cache
    this.controllerConfigURL = ConfigXMLReader.getControllerConfigURL(context);
    ControllerConfig controllerConfig = null; // SCIPIO
    try {
        //ConfigXMLReader.getControllerConfig(this.controllerConfigURL);
        controllerConfig = ConfigXMLReader.getControllerConfig(this.controllerConfigURL);
    } catch (WebAppConfigurationException e) {
        // FIXME: controller.xml errors should throw an exception.
        Debug.logError(e, "Exception thrown while parsing controller.xml file: ", module);
    }
    if (controllerConfig == null) {
        // SCIPIO: 2018-11-08: If the controller fails to load here, what happens is ViewFactory/EventFactory
        // constructor throws a confusing GeneralRuntimeException following an NPE. This is because getControllerConfig returns
        // null on exception, which we can't change in code. So instead we'll handle null here and throw
        // an exception so that the server crashes with a much more informative message.
        // NOTE: We cannot allow initialization to continue, because then an incomplete RequestHandler will get stored
        // in servlet context attributes and prevent any chance at recovering after fix.
        throw new IllegalStateException("Could not initialize a RequestHandler"
                + " for webapp [" + context.getContextPath() + "] because its controller failed to load ("
                + this.controllerConfigURL + ")");
    }
    this.viewFactory = new ViewFactory(context, this.controllerConfigURL);
    this.eventFactory = new EventFactory(context, this.controllerConfigURL);

    this.trackServerHit = !"false".equalsIgnoreCase(context.getInitParameter("track-serverhit"));
    this.trackVisit = !"false".equalsIgnoreCase(context.getInitParameter("track-visit"));
    this.charset = context.getInitParameter("charset");

    // SCIPIO: New (currently true by default)
    this.allowOverrideViewUri = !"false".equalsIgnoreCase(context.getInitParameter("allowOverrideViewUri"));
}
 
Example 10
Source File: SakaiBaseURLProviderFactory.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public StaticBaseURLProvider computeBaseURLProvider(HttpServletRequest request) {
    ServletContext servletcontext = wac.getServletContext();
    // yes, these two fields are not request-scope, but not worth creating
    // a whole new class and bean file for them.
    resourceurlbase = servletcontext.getInitParameter("resourceurlbase");
    if (resourceurlbase == null) {
      resourceurlbase = ServletUtil.computeContextName(servletcontext);
    }

    // compute the baseURLprovider.
    StaticBaseURLProvider sbup = new StaticBaseURLProvider();
    String baseurl = fixSakaiURL(request, ServletUtil.getBaseURL2(request));
    String requestURL = request.getRequestURL().toString();
    int i = requestURL.indexOf("/tool/");
    if (i >= 0) {
	i = requestURL.indexOf("/", i+6);
	if (i >= 0)
	    baseurl = fixSakaiURL(request, requestURL.substring(0, i+1));
	else
	    baseurl = fixSakaiURL(request, requestURL + "/");
    }				  
    //    baseurl = fixSakaiURL(request, "http://heidelberg.rutgers.edu:8081/portal/pda/c6aff0ca-08fc-4f31-905c-ac1019e814cf/tool/54f34afe-b6f8-4218-a1f5-182edff331de/");
    sbup.setResourceBaseURL(computeResourceURLBase(baseurl));
//    baseurl += SakaiEarlyRequestParser.FACES_PATH + "/";
    sbup.setBaseURL(baseurl);
    return sbup;
  }
 
Example 11
Source File: AbstractSamlAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static InputStream getJSONFromServletContext(ServletContext servletContext) {
    String json = servletContext.getInitParameter(AdapterConstants.AUTH_DATA_PARAM_NAME);
    if (json == null) {
        return null;
    }
    return new ByteArrayInputStream(json.getBytes());
}
 
Example 12
Source File: MongoDBContextListener.java    From journaldev with MIT License 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
	try {
		ServletContext ctx = sce.getServletContext();
		MongoClient mongo = new MongoClient(
				ctx.getInitParameter("MONGODB_HOST"), 
				Integer.parseInt(ctx.getInitParameter("MONGODB_PORT")));
		System.out.println("MongoClient initialized successfully");
		sce.getServletContext().setAttribute("MONGO_CLIENT", mongo);
	} catch (UnknownHostException e) {
		throw new RuntimeException("MongoClient init failed");
	}
}
 
Example 13
Source File: CostGateway.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Read settings from web.xml and use them to initialise the service
 */
public void init() {
    try {
        ServletContext context = getServletContext();
        _service = CostService.getInstance();

        // load and process init params from web.xml
        String ixURI = context.getInitParameter("InterfaceX_BackEnd");
        if (ixURI != null) _service.setInterfaceXBackend(ixURI);

        String rsLogURI = context.getInitParameter("ResourceServiceLogGateway");
        if (rsLogURI != null) _service.setResourceLogURI(rsLogURI);

        String engineLogURI = context.getInitParameter("EngineLogGateway");
        if (engineLogURI != null) _service.setEngineLogURI(engineLogURI);

        String rsOrgDataURI = context.getInitParameter("ResourceServiceOrgDataGateway");
        if (rsOrgDataURI != null) _service.setResourceOrgDataURI(rsOrgDataURI);

        String engineLogonName = context.getInitParameter("EngineLogonUserName");
        String engineLogonPassword = context.getInitParameter("EngineLogonPassword");
        String iaURI = (ixURI != null) ? ixURI.replace("/ix", "/ia") : null;
        _service.setEngineLogonName(engineLogonName);
        _service.setEngineLogonPassword(engineLogonPassword);
        _sessions = new Sessions(iaURI, engineLogonName, engineLogonPassword);

        _service.setXSDPath(context.getResource("/xsd/costmodel.xsd"));
    }
    catch (Exception e) {
        _log.error("Cost Service Initialisation Exception", e);
    }
}
 
Example 14
Source File: FooResource.java    From resteasy-examples with Apache License 2.0 4 votes vote down vote up
@GET
public String getFoo(@Context ServletContext context) {
   return context.getInitParameter("foo");
}
 
Example 15
Source File: DatabaseSettingsHandler.java    From arctic-sea with Apache License 2.0 4 votes vote down vote up
@Inject
public void setServletContext(ServletContext ctx) {
    String name = ctx.getInitParameter(INIT_PARAM_DATA_SOURCE_CONFIG_LOCATION);
    setDelegate(new ServletContextPropertyFileHandler(ctx, name));
}
 
Example 16
Source File: AbstractRestNodeServiceImpl.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
void initNodeFromServletContext(final ServletContext servletContext) {


        final Enumeration parameters = servletContext.getInitParameterNames();
        while (parameters.hasMoreElements()) {

            final String key = String.valueOf(parameters.nextElement());
            final String value = servletContext.getInitParameter(key);

            configuration.put(key, value);

        }

        final String luceneDisabled = configuration.get(LUCENE_INDEX_DISABLED);
        final String luceneDisabledValue = luceneDisabled != null ?
                Boolean.valueOf(luceneDisabled).toString() : Boolean.FALSE.toString();
        configuration.put(LUCENE_INDEX_DISABLED, luceneDisabledValue);

        NodeImpl node = new NodeImpl(true,
                configuration.get(NODE_ID),
                configuration.get(NODE_TYPE),
                configuration.get(NODE_CONFIG),
                configuration.get(CLUSTER_ID),
                configuration.get(VERSION),
                configuration.get(BUILD_NO),
                Boolean.valueOf(luceneDisabledValue)
        );
        node.setChannel(configuration.get(CHANNEL));
        this.node = node;
        this.cluster.add(node);

        log = LoggerFactory.getLogger(node.getClusterId() + "." + node.getNodeId());

        if (log.isInfoEnabled()) {

            log.info("== REST configurations =========================================");
            log.info("");
            log.info("Node: {}", node);

            for (final Map.Entry<String, String> entry : configuration.entrySet()) {
                log.info("{}: {}", entry.getKey(), entry.getValue());
            }

            log.info("");
            log.info("================================================================");
            log.info("");

        }

    }
 
Example 17
Source File: JGroupsNodeServiceImpl.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
void initNodeFromServletContext(final ServletContext servletContext) {


        final Enumeration parameters = servletContext.getInitParameterNames();
        while (parameters.hasMoreElements()) {

            final String key = String.valueOf(parameters.nextElement());
            final String value = servletContext.getInitParameter(key);

            configuration.put(key, value);

        }

        final String luceneDisabled = configuration.get(LUCENE_INDEX_DISABLED);
        final String luceneDisabledValue = luceneDisabled != null ?
                Boolean.valueOf(luceneDisabled).toString() : Boolean.FALSE.toString();
        configuration.put(LUCENE_INDEX_DISABLED, luceneDisabledValue);

        node = new NodeImpl(true,
                configuration.get(NODE_ID),
                configuration.get(NODE_TYPE),
                configuration.get(NODE_CONFIG),
                configuration.get(CLUSTER_ID),
                configuration.get(VERSION),
                configuration.get(BUILD_NO),
                Boolean.valueOf(luceneDisabledValue)
        );
        this.cluster.add(node);

        LOG = LoggerFactory.getLogger(node.getClusterId() + "." + node.getNodeId());

        if (LOG.isInfoEnabled()) {

            final StringBuilder stats = new StringBuilder();

            stats.append("\nLoading configuration for node...");
            stats.append("\nNode: ").append(node.getId());

            for (final Map.Entry<String, String> entry : configuration.entrySet()) {
                stats.append('\n').append(entry.getKey()).append(": ").append(entry.getValue());
            }

            LOG.info(stats.toString());
        }

    }
 
Example 18
Source File: ApiRestletApplication.java    From geowave with Apache License 2.0 4 votes vote down vote up
/**
 * This method takes all the routes that were parsed and actually attaches them to the router. It
 * also generates the swagger definition file.
 */
public void attachApiRoutes(final Router router) {
  final ServletContext servlet =
      (ServletContext) router.getContext().getAttributes().get(
          "org.restlet.ext.servlet.ServletContext");
  // TODO document that this can be provided rather than discovered used
  // this servlet init param
  String apiHostPort = servlet.getInitParameter("host_port");
  if (apiHostPort == null) {
    try {
      apiHostPort = getHTTPEndPoint();
    } catch (final Exception e) {
      LOGGER.error("Unable to find httpo endpoint for swagger", e);
    }
  }

  final String defaultConfigFile = servlet.getInitParameter("config_file");

  final SwaggerApiParser apiParser =
      new SwaggerApiParser(
          apiHostPort,
          servlet.getContextPath(),
          VersionUtils.getVersion(),
          "GeoWave API",
          "REST API for GeoWave CLI commands");
  for (final RestRoute route : availableRoutes) {
    router.attach(
        "/" + route.getPath(),
        new GeoWaveOperationFinder(route.getOperation(), defaultConfigFile));

    apiParser.addRoute(route);
  }

  // determine path on file system where the servlet resides
  // so we can serialize the swagger api json file to the correct location
  final String realPath = servlet.getRealPath("/");

  if (!apiParser.serializeSwaggerJson(realPath + "swagger.json")) {
    getLogger().warning("Serialization of swagger.json Failed");
  } else {
    getLogger().info("Serialization of swagger.json Succeeded");
  }
}
 
Example 19
Source File: TagUtils.java    From ontopia with Apache License 2.0 4 votes vote down vote up
public static ActionRegistryIF getActionRegistry(ServletRequest request)
  throws JspTagException {
  ServletContext servletContext = ((HttpServletRequest)request).getSession().getServletContext();
  ActionRegistryIF registry = (ActionRegistryIF)servletContext
    .getAttribute(Constants.AA_REGISTRY);
  if (registry != null)
    return registry;

  // Read in Action Configuration and set it to application context
  String cfgpath = servletContext.getInitParameter(Constants.SCTXT_CONFIG_PATH);
  if (cfgpath == null)
    cfgpath = "classpath:actions.xml";

  log.debug("Start reading action configuration from " + cfgpath);
  
  String str_delay = servletContext.getInitParameter(Constants.SCTXT_RELOAD_DELAY);
  long delay = 6000; // every 6 seconds by default
  if (str_delay != null) {
    try {
      delay = Long.parseLong(str_delay) * 1000; // value in milliseconds
    } catch (NumberFormatException e) {
      delay = -1;
      log.warn("Warning: Falling back to no config re-reading, " +e);
    }
  }    
  String ctxtPath = ((HttpServletRequest)request).getContextPath();
  String realpath = servletContext.getRealPath("");
  ActionConfigurator aconf =
    new ActionConfigurator(ctxtPath, realpath, cfgpath, delay);
  ActionConfigRegistrator registrator =
    new ActionConfigRegistrator(servletContext);

  //!aconf.addObserver(registrator);
  //!aconf.readAndWatchRegistry();

  // HACK to make loading config files from classpath work
  aconf.readRegistryConfiguration();
  registry = aconf.getRegistry();
  registrator.configurationChanged(registry); 
  
  log.debug("Setup action configuration for the web editor and assigned it to application context.");
  
  return registry;
}
 
Example 20
Source File: WebUtils.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Return whether default HTML escaping is enabled for the web application,
 * i.e. the value of the "defaultHtmlEscape" context-param in {@code web.xml}
 * (if any).
 * <p>This method differentiates between no param specified at all and
 * an actual boolean value specified, allowing to have a context-specific
 * default in case of no setting at the global level.
 * @param servletContext the servlet context of the web application
 * @return whether default HTML escaping is enabled for the given application
 * ({@code null} = no explicit default)
 */
@Nullable
public static Boolean getDefaultHtmlEscape(@Nullable ServletContext servletContext) {
	if (servletContext == null) {
		return null;
	}
	String param = servletContext.getInitParameter(HTML_ESCAPE_CONTEXT_PARAM);
	return (StringUtils.hasText(param) ? Boolean.valueOf(param) : null);
}