Example usage for javax.servlet ServletConfig getServletContext

List of usage examples for javax.servlet ServletConfig getServletContext

Introduction

In this page you can find the example usage for javax.servlet ServletConfig getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Returns a reference to the ServletContext in which the caller is executing.

Usage

From source file:org.accada.epcis.repository.query.QueryInitServlet.java

private EPCISServicePortType setupQueryOperationsModule(ServletConfig servletConfig) {
    loadApplicationProperties(servletConfig);
    String jndiName = properties.getProperty(PROP_JNDI_DATASOURCE_NAME);
    DataSource dataSource = loadDataSource(jndiName);

    LOG.debug("Initializing query operations module");
    QueryOperationsModule module = new QueryOperationsModule();
    module.setMaxQueryRows(Integer.parseInt(properties.getProperty(PROP_MAX_QUERY_ROWS)));
    module.setMaxQueryTime(Integer.parseInt(properties.getProperty(PROP_MAX_QUERY_TIME)));
    module.setTriggerConditionMinutes(properties.getProperty(PROP_TRIGGER_CHECK_MIN));
    module.setTriggerConditionSeconds(properties.getProperty(PROP_TRIGGER_CHECK_SEC));
    module.setServiceVersion(properties.getProperty(PROP_SERVICE_VERSION));
    module.setDataSource(dataSource);//ww w  . j  av a2  s . c om
    module.setServletContext(servletConfig.getServletContext());
    module.setBackend(new QueryOperationsBackendSQL());

    LOG.debug("Initializing query operations web service");
    QueryOperationsWebService service = new QueryOperationsWebService(module);
    return service;
}

From source file:org.codice.proxy.http.HttpProxyCamelHttpTransportServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    String ignore = config.getInitParameter("ignoreDuplicateServletName");
    Boolean bool = ObjectConverter.toBoolean(ignore);
    if (bool != null) {
        ignoreDuplicateServletName = bool;
    } else {/* www.j a v a2s .  c o  m*/
        // always log so people can see it easier
        String msg = "Invalid parameter value for init-parameter ignoreDuplicateServletName with value: "
                + ignore;
        LOG.error(msg);
        throw new ServletException(msg);
    }

    String name = config.getServletName();
    String contextPath = config.getServletContext().getContextPath();

    if (httpRegistry == null) {
        httpRegistry = DefaultHttpRegistry.getHttpRegistry(name);
        CamelServlet existing = httpRegistry.getCamelServlet(name);
        if (existing != null) {
            String msg = "Duplicate ServetName detected: " + name + ". Existing: " + existing + " This: "
                    + this.toString() + ". Its advised to use unique ServletName per Camel application.";
            // always log so people can see it easier
            if (isIgnoreDuplicateServletName()) {
                LOG.warn(msg);
            } else {
                LOG.error(msg);
                throw new ServletException(msg);
            }
        }
        httpRegistry.register(this);
    }

    LOG.info("Initialized CamelHttpTransportServlet[name={}, contextPath={}]", getServletName(), contextPath);
}

From source file:org.sakaiproject.vm.VelocityServlet.java

/**
 * Called by the VelocityServlet init(). We want to set a set of properties so that templates will be found in the webapp root. This makes this easier to work with as an example, so a new user doesn't have to worry about config issues when first
 * figuring things out/*w w  w.ja  v  a 2  s .co  m*/
 */
protected ExtendedProperties loadConfiguration(ServletConfig config) throws IOException, FileNotFoundException {
    // This is to support old config property.
    String configPath = config.getInitParameter("properties");
    ExtendedProperties p;
    if (configPath != null && configPath.length() > 0) {
        p = new ExtendedProperties();
        if (!configPath.startsWith("/")) {
            configPath = "/" + configPath;
        }
        p.load(getServletContext().getResourceAsStream(configPath));
    } else {
        // load the properties as configured in the servlet init params
        p = super.loadConfiguration(config);
    }

    /*
     * first, we set the template path for the FileResourceLoader to the root of the webapp. This probably won't work under in a WAR under WebLogic, but should under tomcat :)
     */

    String path = config.getServletContext().getRealPath("/");

    if (path == null) {
        getVelocityEngine().getLog().debug(" VelocityServlet.loadConfiguration() : unable to "
                + "get the current webapp root.  Using '/'. Please fix.");
        path = "/";
    }

    p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);

    /**
     * and the same for the log file
     */
    p.setProperty("runtime.log", path + p.getProperty("runtime.log"));

    return p;
}

From source file:zutil.jee.upload.AjaxFileUpload.java

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    try {/*from   w w w .  j  av a  2 s  .c  om*/
        // Read the javascript file to memory
        String path = JAVASCRIPT_FILE;
        if (config.getInitParameter("JAVASCRIPT_FILE") != null)
            path = config.getInitParameter("JAVASCRIPT_FILE");
        JAVASCRIPT = FileUtil.getContent(FileUtil.findURL(path));

        // Read temp dir
        if (config.getInitParameter("TEMP_PATH") != null) {
            if (config.getInitParameter("TEMP_PATH").equalsIgnoreCase("SYSTEM"))
                TEMPFILE_PATH = new File(System.getProperty("java.io.tmpdir"));
            else if (config.getInitParameter("TEMP_PATH").equalsIgnoreCase("SERVLET"))
                TEMPFILE_PATH = (File) config.getServletContext().getAttribute("javax.servlet.context.tempdir");
            else
                TEMPFILE_PATH = new File(config.getInitParameter("TEMP_PATH"));
        }

        // Read allowed file types
        if (config.getInitParameter("ALLOWED_EXTENSIONS") != null) {
            String[] tmp = config.getInitParameter("ALLOWED_EXTENSIONS").split(",");
            StringBuilder ext_log = new StringBuilder("Allowed extensions: ");
            for (String ext : tmp) {
                ALLOWED_EXTENSIONS.add(ext.trim().toLowerCase());
                ext_log.append(ext).append(", ");
            }
            logger.info(ext_log.toString());
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.iff.infra.util.servlet.ProxyServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    {//add by tylerchen
        Enumeration<String> names = servletConfig.getInitParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = servletConfig.getInitParameter(name);
            initParameterMap.put(name, StringHelper.replaceBlock(value,
                    MapHelper.toMap("CPATH", servletConfig.getServletContext().getContextPath()), null));
        }//from  w  w  w  .ja v  a 2 s .c  o  m
    }

    String doLogStr = servletConfig.getInitParameter(P_LOG);
    if (doLogStr != null) {
        this.doLog = Boolean.parseBoolean(doLogStr);
    }

    String doForwardIPString = servletConfig.getInitParameter(P_FORWARDEDFOR);
    if (doForwardIPString != null) {
        this.doForwardIP = Boolean.parseBoolean(doForwardIPString);
    }

    try {// get target url
        String paramName = initParameterMap.get("paramName");
        if (paramName != null) {
            String targetUri = null;//TODO ResourceKit.getValue(paramName);
            if (targetUri == null || targetUri.length() < 1) {
                targetUri = servletConfig.getInitParameter(P_TARGET_URI);
            }
            targetUriObj = new URI(targetUri);
        }
    } catch (Exception e) {
        throw new RuntimeException("Trying to process targetUri init parameter: " + e, e);
    }
    targetUri = targetUriObj.toString();

    HttpParams hcParams = new BasicHttpParams();
    readConfigParam(hcParams, ClientPNames.HANDLE_REDIRECTS, Boolean.class);
    proxyClient = createHttpClient(hcParams);
}

From source file:org.wso2.carbon.bridge.EquinoxFrameworkLauncher.java

public void init(ServletConfig servletConfig) {
    this.servletConfig = servletConfig;
    context = servletConfig.getServletContext();
    init();
}

From source file:org.wso2.carbon.registry.resource.ui.clients.ResourceServiceClient.java

public ResourceServiceClient(ServletConfig config, HttpSession session) throws RegistryException {
    this.session = session;
    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
    ConfigurationContext configContext = (ConfigurationContext) config.getServletContext()
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
    epr = backendServerURL + "ResourceAdminService";

    try {/*  w ww.j  av a 2 s. c  o m*/
        stub = new ResourceAdminServiceStub(configContext, epr);

        ServiceClient client = stub._getServiceClient();
        Options option = client.getOptions();
        option.setManageSession(true);
        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);

    } catch (AxisFault axisFault) {
        String msg = "Failed to initiate resource service client. " + axisFault.getMessage();
        log.error(msg, axisFault);
        throw new RegistryException(msg, axisFault);
    }
}

From source file:org.protorabbit.servlet.ProtoRabbitServlet.java

public void init(ServletConfig cfg) throws ServletException {
    super.init(cfg);
    this.ctx = cfg.getServletContext();
    statsManager = (StatsManager) ctx.getAttribute(StatsManager.STATS_MANAGER);
    if (statsManager == null) {
        throw new ServletException(
                "You need to configure the Statis Manager as a servlet context listener in your web.xml.\n"
                        + "<listener>" + " <listener-class>org.protorabbit.stats.impl.StatsManager"
                        + " </listener-class>" + "</listener>");
    }//from  w w w  .j a v a2s.  co m
    cg = statsManager.getClientIdGenerator(ctx);
    // get default properties
    String handlerName = ctx.getInitParameter("prt-handler-name");
    Properties p = new Properties();
    InputStream is = getClass().getResourceAsStream("/org/protorabbit/resources/default.properties");

    try {
        p.load(is);
        version = p.getProperty("version");
        buildDate = p.getProperty("buildDate");
        cleanupTimeout = Long.parseLong((p.getProperty("cleanupTimeout")));
        maxAge = Long.parseLong((p.getProperty("maxAge")));
        maxTries = Integer.parseInt((p.getProperty("maxTries")));
        if (handlerName == null) {
            handlerName = p.getProperty("handlerName");
        }
    } catch (Exception e1) {
        getLogger().severe("Error loading default propeteries.");
        e1.printStackTrace();
    }
    if (handlerName != null) {
        ctx.setAttribute(HandlerFactory.HANDLER_NAME, handlerName);
    }
    // set the lastCleanup to current
    lastCleanup = (new Date()).getTime();

    getLogger().info("Protorabbit version : " + version);
    getLogger().info("Protorabbit build date : " + buildDate);
    lastUpdated = new HashMap<String, Long>();

    if (ctx.getInitParameter("prt-dev-mode") != null) {
        isDevMode = ("true".equals(ctx.getInitParameter("prt-dev-mode").toLowerCase()));
    }
    if (ctx.getInitParameter("prt-profile") != null) {
        profile = ("true".equals(ctx.getInitParameter("prt-profile").toLowerCase()));
    }
    if (ctx.getInitParameter("prt-service-uri") != null) {
        serviceURI = ctx.getInitParameter("prt-service-uri");
    }
    if (ctx.getInitParameter("prt-expires-mappings") != null) {
        String expiresMappings = ctx.getInitParameter("prt-expires-mappings");
        if (expiresMappings.indexOf(",") != -1) {
            writeHeaders = expiresMappings.split(",");
        } else {
            writeHeaders = new String[1];
            writeHeaders[0] = expiresMappings;
        }
    }
    if (ctx.getInitParameter("prt-engine-class") != null) {
        engineClassName = ctx.getInitParameter("prt-engine-class");
    }
    if (ctx.getInitParameter("prt-max-timeout") != null) {
        String maxTimeoutString = ctx.getInitParameter("prt-max-timeout");
        try {
            maxAge = (new Long(maxTimeoutString)).longValue();
        } catch (Exception e) {
            getLogger().warning("Non-fatal: Error processing configuration : prt-service-uri must be a long.");
        }
    }
    if (ctx.getInitParameter("prt-templates") != null) {
        String tString = ctx.getInitParameter("prt-templates");
        // clean up the templates string
        tString = tString.trim();
        tString = tString.replace(" ", "");
        templates = tString.split(",");
    } else {
        templates = new String[] { defaultTemplateURI };
    }
    jcfg = Config.getInstance(serviceURI, maxAge);
    jcfg.setDevMode(isDevMode);
    jcfg.setProfile(profile);
    if (engineClassName != null) {
        jcfg.setEngineClassName(engineClassName);
    }
    try {
        updateConfig();
    } catch (IOException e) {
        getLogger().log(Level.SEVERE, "Fatal Error: Unable to instanciate engine class " + engineClassName, e);
        throw new ServletException("Fatal Error: Unable to reading in configuration class " + engineClassName,
                e);
    }
    engine = jcfg.getEngine();

}

From source file:ume.pareva.it.ITDr.java

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
}

From source file:com.github.peholmst.springsecuritydemo.servlet.SpringApplicationServlet.java

@SuppressWarnings("unchecked")
@Override//www  .  j  a  v  a  2 s . co  m
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    /*
     * Look up the name of the Vaadin application bean. The bean should be
     * either a prototype or have session scope.
     */
    applicationBean = servletConfig.getInitParameter("applicationBean");
    if (applicationBean == null) {
        if (logger.isErrorEnabled()) {
            logger.error("ApplicationBean not specified in servlet parameters");
        }
        throw new ServletException("ApplicationBean not specified in servlet parameters");
    }

    if (logger.isInfoEnabled()) {
        logger.info("Using applicationBean '" + applicationBean + "'");
    }

    /*
     * Fetch the Spring web application context
     */
    applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());

    if (applicationContext.isSingleton(applicationBean)) {
        if (logger.isErrorEnabled()) {
            logger.error("ApplicationBean must not be a singleton");
        }
        throw new ServletException("ApplicationBean must not be a singleton");
    }
    if (!applicationContext.isPrototype(applicationBean) && logger.isWarnEnabled()) {
        logger.warn("ApplicationBean is not a prototype");
    }

    /*
     * Get the application class from the application context
     */
    applicationClass = (Class<? extends Application>) applicationContext.getType(applicationBean);
    if (logger.isDebugEnabled()) {
        logger.debug("Vaadin application class is [" + applicationClass + "]");
    }
    /*
     * Initialize the locale resolver
     */
    initLocaleResolver(applicationContext);
}