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.oclc.oai.server.OAIHandler.java

/**
 * init is called one time when the Servlet is loaded. This is the place where one-time initialization is done.
 * Specifically, we load the properties file for this application, and create the AbstractCatalog object for subsequent
 * use.//  w  w  w  . ja v  a  2  s.c  o  m
 *
 * @param config servlet configuration information
 * @throws ServletException there was a problem with initialization
 */
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    try {
        Map<String, Object> attributes = null;
        ServletContext context = getServletContext();
        Properties properties = (Properties) context.getAttribute(PROPERTIES_SERVLET_CONTEXT_ATTRIBUTE);
        if (properties == null) {
            final String PROPERTIES_INIT_PARAMETER = "properties";
            log.debug("OAIHandler.init(..): No '" + PROPERTIES_SERVLET_CONTEXT_ATTRIBUTE
                    + "' servlet context attribute. Trying to use init parameter '" + PROPERTIES_INIT_PARAMETER
                    + "'");

            String fileName = config.getServletContext().getInitParameter(PROPERTIES_INIT_PARAMETER);
            InputStream in;
            try {
                log.debug("fileName=" + fileName);
                in = new FileInputStream(fileName);
            } catch (FileNotFoundException e) {
                log.debug("file not found. Try the classpath: " + fileName);
                in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            }
            if (in != null) {
                log.debug("file was found: Load the properties");
                properties = new Properties();
                properties.load(in);
                attributes = getAttributes(properties);
                if (debug)
                    System.out.println("OAIHandler.init: fileName=" + fileName);
            }
        } else {
            log.debug("Load context properties");
            attributes = getAttributes(properties);
        }
        log.debug("Store global properties");
        attributesMap.put("global", attributes);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw new ServletException(e.getMessage());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        throw new ServletException(e.getMessage());
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        throw new ServletException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new ServletException(e.getMessage());
    } catch (Throwable e) {
        e.printStackTrace();
        throw new ServletException(e.getMessage());
    }
}

From source file:lucee.runtime.engine.CFMLEngineImpl.java

@Override
public void addServletConfig(ServletConfig config) throws ServletException {
    servletConfigs.add(config);/* w  ww .j av a  2  s. c  om*/
    String real = ReqRspUtil.getRootPath(config.getServletContext());
    if (!initContextes.containsKey(real)) {
        CFMLFactory jspFactory = loadJSPFactory(getConfigServerImpl(), config, initContextes.size());
        initContextes.put(real, jspFactory);
    }
}

From source file:lucee.runtime.engine.CFMLEngineImpl.java

@Override
public CFMLFactory getCFMLFactory(ServletConfig srvConfig, HttpServletRequest req) throws ServletException {
    ServletContext srvContext = srvConfig.getServletContext();

    String real = ReqRspUtil.getRootPath(srvContext);
    ConfigServerImpl cs = getConfigServerImpl();

    // Load JspFactory

    CFMLFactory factory = contextes.get(real);
    if (factory == null) {
        factory = initContextes.get(real);
        if (factory == null) {
            factory = loadJSPFactory(cs, srvConfig, initContextes.size());
            initContextes.put(real, factory);
        }//from www .  j a  v  a2  s.  co  m
        contextes.put(real, factory);

        try {
            String cp = req.getContextPath();
            if (cp == null)
                cp = "";
            ((CFMLFactoryImpl) factory)
                    .setURL(new URL(req.getScheme(), req.getServerName(), req.getServerPort(), cp));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    return factory;
}

From source file:org.tinygroup.jspengine.servlet.JspServlet.java

public void init(ServletConfig config) throws ServletException {

    if (!(config instanceof TinyServletConfig)) {
        JspServlet servlet = BeanContainerFactory.getBeanContainer(this.getClass().getClassLoader())
                .getBean("jspServlet");
        TinyServletConfig tinyServletConfig = (TinyServletConfig) servlet.getServletConfig();
        if (tinyServletConfig == null) {
            tinyServletConfig = new TinyServletConfig();
        }/*from  w  w w  . j a v a2s  .co m*/
        tinyServletConfig.setServletConfig(config);
        servlet.setServletConfig(tinyServletConfig);
        config = tinyServletConfig;
    }
    this.config = config;
    this.context = config.getServletContext();

    // Initialize the JSP Runtime Context
    options = new EmbeddedServletOptions(config, context);
    rctxt = new JspRuntimeContext(context, options);

    // Instantiate and init our resource injector
    String resourceInjectorClassName = config
            .getInitParameter(Constants.JSP_RESOURCE_INJECTOR_CONTEXT_ATTRIBUTE);
    if (resourceInjectorClassName != null) {
        try {
            ResourceInjector ri = (ResourceInjector) Class.forName(resourceInjectorClassName).newInstance();
            ri.setContext(this.context);
            this.context.setAttribute(Constants.JSP_RESOURCE_INJECTOR_CONTEXT_ATTRIBUTE, ri);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    // START SJSWS 6232180
    // Determine which HTTP methods to service ("*" means all)
    httpMethodsString = config.getInitParameter("httpMethods");
    if (httpMethodsString != null && !httpMethodsString.equals("*")) {
        httpMethodsSet = new HashSet();
        StringTokenizer tokenizer = new StringTokenizer(httpMethodsString, ", \t\n\r\f");
        while (tokenizer.hasMoreTokens()) {
            httpMethodsSet.add(tokenizer.nextToken());
        }
    }
    // END SJSWS 6232180

    // START GlassFish 750
    taglibs = new ConcurrentHashMap<String, TagLibraryInfo>();
    context.setAttribute(Constants.JSP_TAGLIBRARY_CACHE, taglibs);

    tagFileJarUrls = new ConcurrentHashMap<String, URL>();
    context.setAttribute(Constants.JSP_TAGFILE_JAR_URLS_CACHE, tagFileJarUrls);
    // END GlassFish 750

    if (log.isTraceEnabled()) {
        log.trace(Localizer.getMessage("jsp.message.scratch.dir.is", options.getScratchDir().toString()));
        log.trace(Localizer.getMessage("jsp.message.dont.modify.servlets"));
    }
}

From source file:net.openkoncept.vroom.VroomController.java

public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    try {//w w  w  . j  a v a  2 s. co m
        fileUploadSizeThreshold = Integer.parseInt(getInitParameter(FILE_UPLOAD_SIZE_THRESHOLD));
    } catch (NumberFormatException ex) {
        fileUploadSizeThreshold = 32768;
    }
    String folderName = getInitParameter(FILE_UPLOAD_TEMP_FOLDER);
    if (folderName == null) {
        folderName = "/WEB-INF/temp";
    }
    fileUploadTempFolder = new File(servletConfig.getServletContext().getRealPath(folderName));
    if (!fileUploadTempFolder.isDirectory()) {
        try {
            fileUploadTempFolder.mkdirs();
        } catch (Exception ex) {
            throw new ServletException(
                    "Failed to create file upload temp folder [" + fileUploadTempFolder + "]", ex);
        }
    } else if (!(fileUploadTempFolder.canRead() && fileUploadTempFolder.canWrite())) {
        throw new ServletException("Application does not read/write permissions on file upload temp folder ["
                + fileUploadTempFolder + "]");
    }
}

From source file:com.netspective.sparx.navigate.NavigationControllerServlet.java

protected void executAntBuild(ServletConfig servletConfig, File buildFile, String target)
        throws ServletException {
    log.debug("Executing Ant build " + buildFile + " target " + target);

    org.apache.tools.ant.Project antProject = AntProject.getConfiguredProject(buildFile);
    antProject.setProperty("app.home", servletConfig.getServletContext().getRealPath("/"));
    antProject.setProperty("app.init-count", Long.toString(getInitializationCount()));

    Properties servletOptionsProps = servletOptions.setProperties(new Properties(), "app.servlet-options",
            false);/*from  w w w. j a v  a 2  s.  c  o m*/
    for (Iterator i = servletOptionsProps.keySet().iterator(); i.hasNext();) {
        String propName = (String) i.next();
        antProject.setProperty(propName, servletOptionsProps.getProperty(propName));
    }

    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
    PrintStream pstream = new PrintStream(ostream);

    BuildLogger logger = new NoBannerLogger();
    logger.setMessageOutputLevel(org.apache.tools.ant.Project.MSG_INFO);
    logger.setOutputPrintStream(pstream);
    logger.setErrorPrintStream(pstream);

    PrintStream saveOut = System.out;
    PrintStream saveErr = System.err;
    System.setOut(pstream);
    System.setErr(pstream);

    antProject.addBuildListener(logger);
    Exception exceptionThrown = null;
    try {
        Vector targets = new Vector();
        if (target != null) {
            String[] targetNames = TextUtils.getInstance().split(target, ",", true);
            for (int i = 0; i < targetNames.length; i++)
                targets.add(targetNames[i]);
        } else
            targets.add(antProject.getDefaultTarget());
        antProject.executeTargets(targets);
    } catch (Exception e) {
        exceptionThrown = e;
    }

    if (exceptionThrown != null) {
        log.error(ostream.toString());
        log.error("Error running ant build file " + buildFile + " target " + target, exceptionThrown);
    } else
        log.debug(ostream.toString());

    int extnPos = buildFile.getName().lastIndexOf('.');
    String nameNoExtn = extnPos != -1 ? buildFile.getName().substring(0, extnPos) : buildFile.getName();
    File logFile = servletOptions.getInitUsingAntLogFile() != null
            ? new File(servletOptions.getInitUsingAntLogFile())
            : new File(buildFile.getParentFile(), nameNoExtn + ".log");

    FileOutputStream fos = null;
    PrintWriter logWriter = null;
    try {
        fos = new FileOutputStream(logFile.getAbsolutePath(), logFile.exists());
        logWriter = new PrintWriter(fos);
        logWriter.println("-----------------------------------------------------------------------------");
        logWriter.println("Started build at " + SimpleDateFormat.getDateTimeInstance().format(new Date())
                + " in Servlet " + getServletName() + " (Context " + getServletContext().getServletContextName()
                + ", BuildFile " + buildFile.getAbsolutePath() + ")");
        logWriter.write(ostream.toString());
        if (exceptionThrown != null)
            logWriter.write(TextUtils.getInstance().getStackTrace(exceptionThrown));
        logWriter.println("Ended build at " + SimpleDateFormat.getDateTimeInstance().format(new Date())
                + " in Servlet " + getServletName() + " (Context " + getServletContext().getServletContextName()
                + ", BuildFile " + buildFile.getAbsolutePath() + ")");
    } catch (IOException e) {
        throw new ServletException(e);
    } finally {
        logWriter.close();
        try {
            fos.close();
        } catch (IOException e) {
            throw new ServletException(e);
        }
    }

    System.setOut(saveOut);
    System.setErr(saveErr);
}

From source file:edu.umd.lib.servlets.permissions.PermissionsServlet.java

private void parseInitParameters(ServletConfig config) throws ServletException {
    bindingAddress = getConfigurationParameter(REPOSITORY_BINDING_PARAM, DEFAULT_REPOSITORY_BINDING);
    repositoryConfig = getConfigurationParameter(REPOSITORY_CONFIG_PARAM, DEFAULT_REPOSITORY_CONFIG);
    storageLocation = getConfigurationParameter(REPOSITORY_DIRECTORY_PARAM, DEFAULT_REPOSITORY_DIRECTORY);
    startRemoteServer = Boolean/*w w w .jav a  2  s  . com*/
            .valueOf(getConfigurationParameter(START_REMOTE_SERVER, DEFAULT_START_REMOTE_SERVER));

    // check for absolute path
    if (!storageLocation.startsWith("/") && !storageLocation.startsWith("file:")) {
        // try to parse the relative path
        final String storagePath = config.getServletContext().getRealPath(storageLocation);

        // ServletContext#getRealPath() may return null especially when
        // unpackWARs="false".
        if (storagePath == null) {
            log.warn(
                    "Cannot determine the real path of the repository storage location, '{}'. Defaults to './{}'",
                    storageLocation, DEFAULT_REPOSITORY_DIRECTORY_UNDER_CURRENT_WORKING_DIR);
            storageLocation = DEFAULT_REPOSITORY_DIRECTORY_UNDER_CURRENT_WORKING_DIR;
        } else {
            storageLocation = storagePath;
        }
    }
}

From source file:lucee.runtime.engine.CFMLEngineImpl.java

@Override
public void cli(Map<String, String> config, ServletConfig servletConfig)
        throws IOException, JspException, ServletException {
    ServletContext servletContext = servletConfig.getServletContext();
    HTTPServletImpl servlet = new HTTPServletImpl(servletConfig, servletContext,
            servletConfig.getServletName());

    // webroot//from  w  w w.j  a  v  a2 s  . c om
    String strWebroot = config.get("webroot");
    if (StringUtil.isEmpty(strWebroot, true))
        throw new IOException("missing webroot configuration");
    Resource root = ResourcesImpl.getFileResourceProvider().getResource(strWebroot);
    root.mkdirs();

    // serverName
    String serverName = config.get("server-name");
    if (StringUtil.isEmpty(serverName, true))
        serverName = "localhost";

    // uri
    String strUri = config.get("uri");
    if (StringUtil.isEmpty(strUri, true))
        throw new IOException("missing uri configuration");
    URI uri;
    try {
        uri = lucee.commons.net.HTTPUtil.toURI(strUri);
    } catch (URISyntaxException e) {
        throw Caster.toPageException(e);
    }

    // cookie
    Cookie[] cookies;
    String strCookie = config.get("cookie");
    if (StringUtil.isEmpty(strCookie, true))
        cookies = new Cookie[0];
    else {
        Map<String, String> mapCookies = HTTPUtil.parseParameterList(strCookie, false, null);
        int index = 0;
        cookies = new Cookie[mapCookies.size()];
        Entry<String, String> entry;
        Iterator<Entry<String, String>> it = mapCookies.entrySet().iterator();
        Cookie c;
        while (it.hasNext()) {
            entry = it.next();
            c = ReqRspUtil.toCookie(entry.getKey(), entry.getValue(), null);
            if (c != null)
                cookies[index++] = c;
            else
                throw new IOException("cookie name [" + entry.getKey() + "] is invalid");
        }
    }

    // header
    Pair[] headers = new Pair[0];

    // parameters
    Pair[] parameters = new Pair[0];

    // attributes
    StructImpl attributes = new StructImpl();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    HttpServletRequestDummy req = new HttpServletRequestDummy(root, serverName, uri.getPath(), uri.getQuery(),
            cookies, headers, parameters, attributes, null);
    req.setProtocol("CLI/1.0");
    HttpServletResponse rsp = new HttpServletResponseDummy(os);

    serviceCFML(servlet, req, rsp);
    String res = os.toString(ReqRspUtil.getCharacterEncoding(null, rsp).name());
    System.out.println(res);
}

From source file:org.wso2.carbon.registry.core.servlet.RegistryServlet.java

public void init(final ServletConfig config) throws ServletException {
    super.init(config);
    EmbeddedRegistryService embeddedRegistryService;

    try {/*from   ww w . j a  v  a2  s  .co m*/
        // read the registry.xml file from the configured location. if not configured, read the
        // default registry.xml file bundled with the webapp.
        String configPath = config.getInitParameter(RegistryConstants.REGISTRY_CONFIG_PATH);
        InputStream configStream;
        if (configPath != null) {
            try {
                configStream = new FileInputStream(configPath);
            } catch (FileNotFoundException e) {
                throw new ServletException("Couldn't find specified config file '" + configPath + "'", e);
            }
        } else {
            configStream = config.getServletContext().getResourceAsStream("/WEB-INF/registry.xml");
        }

        RegistryContext registryContext = RegistryContext.getBaseInstance(configStream,
                new RegistryContext.RegURLSupplier() {
                    public String getURL() {
                        return config.getServletContext().getRealPath("/WEB-INF");
                    }
                });

        embeddedRegistryService = registryContext.getEmbeddedRegistryService();

        // create a system registry and put it in the context
        UserRegistry systemRegistry = embeddedRegistryService.getConfigSystemRegistry();

        // add configured handers to the jdbc registry
        // note: no need to do this here. this is done inside the registry context
        //Iterator<HandlerConfiguration> handlers =
        //        registryContext.getHandlerConfigurations().iterator();
        //while (handlers.hasNext()) {
        //    HandlerConfiguration handlerConfiguration = handlers.next();
        //    registryContext.getHandlerManager().addHandler(0,
        //            handlerConfiguration.getFilter(), handlerConfiguration.getHandler());
        //}

        // create system resources

        NodeGroupLock.lock(NodeGroupLock.INITIALIZE_LOCK);

        if (log.isTraceEnabled()) {
            log.trace("Creating system collections used in WSO2 Registry server.");
        }

        if (!systemRegistry.resourceExists("/system")) {

            try {
                boolean inTransaction = Transaction.isStarted();
                if (!inTransaction) {
                    systemRegistry.beginTransaction();
                }
                Collection systemCollection = systemRegistry.newCollection();
                String systemDesc = "This collection is used to store system data of the "
                        + "WSO2 Registry server. User nor the admins of the registry are not expected "
                        + "to edit any content of this collection. Changing content of this collection "
                        + "may result in unexpected behaviors.";
                systemCollection.setDescription(systemDesc);
                systemRegistry.put("/system", systemCollection);

                Collection advancedQueryCollection = systemRegistry.newCollection();
                String advaceDesc = "This collection is used to store auto generated queries "
                        + "to support various combinations of advanced search criteria. "
                        + "This is initialy empty and gets filled as advanced search is "
                        + "executed from the web UI.";
                advancedQueryCollection.setDescription(advaceDesc);
                systemRegistry.put("/system/queries/advanced", advancedQueryCollection);
                if (!inTransaction) {
                    systemRegistry.commitTransaction();
                }
            } catch (Exception e) {
                String msg = "Unable to setup system collections used by the Carbon server.";
                log.error(msg, e);
                systemRegistry.rollbackTransaction();
                throw new RegistryException(e.getMessage(), e);
            }
        }

        try {
            AuthorizationManager ac = systemRegistry.getUserRealm().getAuthorizationManager();
            RealmConfiguration realmConfig;
            realmConfig = registryContext.getRealmService().getBootstrapRealmConfiguration();
            String systemUserName = CarbonConstants.REGISTRY_SYSTEM_USERNAME;

            ac.clearResourceAuthorizations("/system");

            ac.authorizeUser(systemUserName, "/system", ActionConstants.GET);
            ac.authorizeUser(systemUserName, "/system", ActionConstants.PUT);
            ac.authorizeUser(systemUserName, "/system", ActionConstants.DELETE);
            ac.authorizeUser(systemUserName, "/system", AccessControlConstants.AUTHORIZE);

            String adminUserName = CarbonConstants.REGISTRY_SYSTEM_USERNAME;

            ac.authorizeUser(adminUserName, "/system", ActionConstants.GET);

            String adminRoleName = realmConfig.getAdminRoleName();
            ac.authorizeRole(adminRoleName, "/system", ActionConstants.GET);

            // any user should be able to execute auto generated queries, though the results
            // of such queries are filtered to match current users permission level.
            String everyoneRoleName = realmConfig.getEveryOneRoleName();
            ac.authorizeRole(everyoneRoleName, "/system/queries/advanced", ActionConstants.GET);

        } catch (UserStoreException e) {
            String msg = "Failed to set permissions for the system collection.";
            log.fatal(msg, e);
            throw new RegistryException(msg, e);
        }

        if (log.isTraceEnabled()) {
            log.trace("System collections for WSO2 Registry server created successfully.");
        }

        NodeGroupLock.unlock(NodeGroupLock.INITIALIZE_LOCK);

        // todo: we should make this decision according to the registry.xml or web.xml config
        //try {
        //    RemoteRegistry remote = new RemoteRegistry(new URL("http://localhost:8080/wso2registry/atom"));
        //    config.getServletContext().setAttribute(RegistryConstants.REGISTRY, remote);
        //} catch (MalformedURLException e) {
        //    config.getServletContext().setAttribute(RegistryConstants.REGISTRY, coreRegistry);
        //}

        config.getServletContext().setAttribute(RegistryConstants.REGISTRY, embeddedRegistryService);

        //config.getServletContext()
        //        .setAttribute(RegistryConstants.REGISTRY_REALM, userRealm);
        System.getProperties().put(RegistryConstants.REGISTRY, embeddedRegistryService);
        System.getProperties().put(RegistryConstants.SYSTEM_REGISTRY, systemRegistry);
        //System.getProperties().put(RegistryConstants.REGISTRY_REALM, userRealm);

    } catch (RegistryException e) {
        String msg = "Registry initialization failed. " + e.getMessage();
        log.fatal(msg, e);
        throw new ServletException(msg, e);
    }
    /*if (log.isDebugEnabled()) {
    log.debug(Messages.getMessage("server.initalized"));
    }*/
}

From source file:org.jasig.cas.web.init.SafeDispatcherServlet.java

public void init(final ServletConfig config) {
    try {//from w w w . ja  va2s.  c o m
        this.delegate.init(config);

    } catch (final Throwable t) {
        // let the service method know initialization failed.
        this.initSuccess = false;

        /*
         * no matter what went wrong, our role is to capture this error and
         * prevent it from blocking initialization of the servlet. logging
         * overkill so that our deployer will find a record of this problem
         * even if unfamiliar with Commons Logging and properly configuring
         * it.
         */

        final String message = "SafeDispatcherServlet: \n"
                + "The Spring DispatcherServlet we wrap threw on init.\n"
                + "But for our having caught this error, the servlet would not have initialized.";

        // log it via Commons Logging
        log.fatal(message, t);

        // log it to System.err
        System.err.println(message);
        t.printStackTrace();

        // log it to the ServletContext
        ServletContext context = config.getServletContext();
        context.log(message, t);

        /*
         * record the error so that the application has access to later
         * display a proper error message based on the exception.
         */
        context.setAttribute(CAUGHT_THROWABLE_KEY, t);

    }
}