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.wapama.web.EditorHandler.java

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    _profileService = ProfileServiceImpl.INSTANCE;
    _profileService.init(config.getServletContext());
    _pluginService = PluginServiceImpl.getInstance(config.getServletContext());

    String editor_file = config.getServletContext().getRealPath("/editor.html");
    try {/*from  w w  w.  j  av  a  2 s  . c  om*/
        _doc = readDocument(editor_file);
    } catch (Exception e) {
        throw new ServletException("Error while parsing editor.html", e);
    }
    if (_doc == null) {
        _logger.error("Invalid editor.html, " + "could not be read as a document.");
        throw new ServletException("Invalid editor.html, " + "could not be read as a document.");
    }

    Element root = _doc.getRootElement();
    Element head = root.getChild("head", root.getNamespace());
    if (head == null) {
        _logger.error("Invalid editor.html. No html or head tag");
        throw new ServletException("Invalid editor.html. " + "No html or head tag");
    }

    try {
        initEnvFiles(getServletContext());
    } catch (IOException e) {
        throw new ServletException(e);
    }
}

From source file:com.portfolio.data.attachment.XSLService.java

@Override
public void init(ServletConfig config) throws ServletException {
    sc = config.getServletContext();
    servletDir = sc.getRealPath("/");
    int last = servletDir.lastIndexOf(File.separator);
    last = servletDir.lastIndexOf(File.separator, last - 1);
    baseDir = servletDir.substring(0, last);
    server = config.getInitParameter("redirectedServer");

    //Setting up the JAXP TransformerFactory
    this.transFactory = TransformerFactory.newInstance();

    //Setting up the FOP factory
    this.fopFactory = FopFactory.newInstance();

    try {//from  w  w w .  j  av a  2s  .co  m
        String dataProviderName = config.getInitParameter("dataProviderClass");
        dataProvider = (DataProvider) Class.forName(dataProviderName).newInstance();

        InitialContext cxt = new InitialContext();

        /// Init this here, might fail depending on server hosting
        ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/portfolio-backend");
        if (ds == null) {
            throw new Exception("Data  jdbc/portfolio-backend source not found!");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.extensiblecatalog.ncip.v2.responder.implprof1.NCIPServlet.java

/**
 * Initialize the servlet// ww  w .j a v a2s  .  co  m
 * @param config
 * @throws ServletException
 */
@Override
public void init(ServletConfig config) throws ServletException {

    super.init(config);
    String appName = ConfigurationHelper.getAppName(config.getServletContext());

    try {

        if (messageHandler == null) {

            messageHandler = MessageHandlerFactory.buildMessageHandler(appName);

        }

        if (translator == null) {

            translator = TranslatorFactory.buildTranslator(appName);

        }

        if (statisticsBean == null) {

            statisticsBean = StatisticsBeanFactory.buildStatisticsBean(appName);

        }

        if (serviceValidator == null) {

            serviceValidator = ServiceValidatorFactory.buildServiceValidator(appName);

        }

        includeStackTracesInProblemResponse = ConfigurationHelper.getCoreConfiguration()
                .getIncludeStackTracesInProblemResponses();

    } catch (ToolkitException e) {

        throw new ServletException("Exception during init method:", e);

    }

}

From source file:net.wastl.webmail.server.WebMailServlet.java

public void init(ServletConfig config) throws ServletException {
    final ServletContext sc = config.getServletContext();
    log.debug("Init");
    final String depName = (String) sc.getAttribute("deployment.name");
    final Properties rtProps = (Properties) sc.getAttribute("meta.properties");
    log.debug("RT configs retrieved for application '" + depName + "'");
    srvlt_config = config;/*from   w  w  w  . j  av a2 s .c  om*/
    this.config = new Properties();
    final Enumeration enumVar = config.getInitParameterNames();
    while (enumVar.hasMoreElements()) {
        final String s = (String) enumVar.nextElement();
        this.config.put(s, config.getInitParameter(s));
        log.debug(s + ": " + config.getInitParameter(s));
    }

    /*
     * Issue a warning if webmail.basepath and/or webmail.imagebase are not
     * set.
     */
    if (config.getInitParameter("webmail.basepath") == null) {
        log.warn("webmail.basepath initArg should be set to the WebMail " + "Servlet's base path");
        basepath = "";
    } else {
        basepath = config.getInitParameter("webmail.basepath");
    }
    if (config.getInitParameter("webmail.imagebase") == null) {
        log.error("webmail.basepath initArg should be set to the WebMail " + "Servlet's base path");
        imgbase = "";
    } else {
        imgbase = config.getInitParameter("webmail.imagebase");
    }

    /*
     * Try to get the pathnames from the URL's if no path was given in the
     * initargs.
     */
    if (config.getInitParameter("webmail.data.path") == null) {
        this.config.put("webmail.data.path", sc.getRealPath("/data"));
    }
    if (config.getInitParameter("webmail.lib.path") == null) {
        this.config.put("webmail.lib.path", sc.getRealPath("/lib"));
    }
    if (config.getInitParameter("webmail.template.path") == null) {
        this.config.put("webmail.template.path", sc.getRealPath("/lib/templates"));
    }
    if (config.getInitParameter("webmail.xml.path") == null) {
        this.config.put("webmail.xml.path", sc.getRealPath("/lib/xml"));
    }
    if (config.getInitParameter("webmail.log.facility") == null) {
        this.config.put("webmail.log.facility", "net.wastl.webmail.logger.ServletLogger");
    }

    // Override settings with webmail.* meta.properties
    final Enumeration rte = rtProps.propertyNames();
    int overrides = 0;
    String k;
    while (rte.hasMoreElements()) {
        k = (String) rte.nextElement();
        if (!k.startsWith("webmail.")) {
            continue;
        }
        overrides++;
        this.config.put(k, rtProps.getProperty(k));
    }
    log.debug(Integer.toString(overrides) + " settings passed to WebMailServer, out of " + rtProps.size()
            + " RT properties");

    /*
     * Call the WebMailServer's initialization method and forward all
     * Exceptions to the ServletServer
     */
    try {
        doInit();
    } catch (final Exception e) {
        log.error("Could not intialize", e);
        throw new ServletException("Could not intialize: " + e.getMessage(), e);
    }
    Helper.logThreads("Bottom of WebMailServlet.init()");
}

From source file:org.xsystem.sql2.http.PageServlet2.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    this.config = config;
    repositoryPath = config.getInitParameter("repository");
    repositoryPath = config.getServletContext().getRealPath(repositoryPath);
    loadRepository();/*from   w  w  w  .j  av a  2 s.com*/
}

From source file:org.wso2.carbon.governance.generic.ui.clients.ManageGenericArtifactServiceClient.java

public List<InstalledRxt> getInstalledRXTs(String cookie, ServletConfig config, HttpSession session)
        throws Exception {
    List<InstalledRxt> listInstalledRxts = new ArrayList<InstalledRxt>();
    String user = (String) session.getAttribute("logged-user");
    String tenantDomain = (String) session.getAttribute("tenantDomain");
    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);

    String adminCookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    WSRegistryServiceClient registry = new WSRegistryServiceClient(backendServerURL, adminCookie);
    RealmService realmService = registry.getRegistryContext().getRealmService();

    String configurationPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH
            + RegistryConstants.GOVERNANCE_COMPONENT_PATH + "/types/";
    if (realmService.getTenantUserRealm(realmService.getTenantManager().getTenantId(tenantDomain))
            .getAuthorizationManager().isUserAuthorized(user, configurationPath, ActionConstants.GET)) {
        Collection collection = (Collection) registry.get(configurationPath);
        String[] resources = collection.getChildren();
        for (int i = 0; i < resources.length; i++) {
            if (resources[i] != null && resources[i].contains("/")) {
                String rxt = resources[i].substring(resources[i].lastIndexOf("/") + 1).split("\\.")[0];
                InstalledRxt rxtObj = new InstalledRxt();
                rxtObj.setRxt(rxt);//from  ww  w .  jav  a  2 s .  c o m
                if (realmService.getTenantUserRealm(realmService.getTenantManager().getTenantId(tenantDomain))
                        .getAuthorizationManager().isUserAuthorized(user, resources[i], ActionConstants.GET)) {
                    rxtObj.setDeleteAllowed();
                }
                listInstalledRxts.add(rxtObj);
            }
        }

    }
    if (listInstalledRxts.size() > 1) {
        Collections.sort(listInstalledRxts, InstalledRxt.installedRxtComparator);
    }
    return listInstalledRxts;

}

From source file:org.carrot2.webapp.QueryProcessorServlet.java

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

    final ServletContext servletContext = config.getServletContext();

    /*/*ww w. jav a  2s .  co m*/
     * If initialized, custom logging initializer will be here. Save its reference for
     * deferred initialization (for servlet APIs < 2.5).
     */
    logInitializer = (LogInitContextListener) servletContext.getAttribute(LogInitContextListener.CONTEXT_ID);

    /*
     * Initialize global configuration and publish it.
     */
    this.webappConfig = WebappConfig.getSingleton(servletContext);
    this.unknownToDefaultTransformer = new UnknownToDefaultTransformer(webappConfig, false);
    this.unknownToDefaultTransformerWithMaxResults = new UnknownToDefaultTransformer(webappConfig, true);

    /*
     * Initialize the controller.
     */
    List<IResourceLocator> locators = Lists.newArrayList();
    locators.add(
            new PrefixDecoratorLocator(new ServletContextLocator(getServletContext()), "/WEB-INF/resources/"));

    if (Boolean.getBoolean(ENABLE_CLASSPATH_LOCATOR))
        locators.add(Location.CONTEXT_CLASS_LOADER.locator);

    controller = ControllerFactory.createCachingPooling(ResultsCacheModel.toClassArray(webappConfig.caches));
    controller.init(ImmutableMap.<String, Object>of(
            AttributeUtils.getKey(DefaultLexicalDataFactory.class, "resourceLookup"),
            new ResourceLookup(locators)), webappConfig.components.getComponentConfigurations());

    jawrUrlGenerator = new JawrUrlGenerator(servletContext);
}

From source file:org.apache.oodt.cas.product.rdf.RDFDatasetServlet.java

/**
 * Initializes the servlet.//from w  w  w. j av a 2 s .  c om
 */
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    try {
        this.rdfConf = RDFUtils.initRDF(config);
    } catch (FileNotFoundException e) {
        LOG.log(Level.SEVERE, e.getMessage());
        throw new ServletException(e.getMessage());
    }

    String fileManagerUrl;
    try {
        fileManagerUrl = PathUtils
                .replaceEnvVariables(config.getServletContext().getInitParameter("filemgr.url"));
    } catch (Exception e) {
        throw new ServletException("Failed to get filemgr url : " + e.getMessage(), e);
    }

    fClient = null;

    try {
        fClient = new XmlRpcFileManagerClient(new URL(fileManagerUrl));
    } catch (MalformedURLException e) {
        LOG.log(Level.SEVERE, "Unable to initialize file manager url in RDF Servlet: [url=" + fileManagerUrl
                + "], Message: " + e.getMessage());
    } catch (ConnectionException e) {
        LOG.log(Level.SEVERE, "Unable to initialize file manager url in RDF Servlet: [url=" + fileManagerUrl
                + "], Message: " + e.getMessage());
    }

}

From source file:org.xmlactions.web.conceal.HttpPager.java

/**
 * @see Servlet#init(ServletConfig)/*from   www  . jav  a2  s.  c om*/
 */
public void init(ServletConfig config) throws ServletException {

    String value;

    value = config.getServletContext().getRealPath("");
    if (StringUtils.isNotEmpty(value)) {
        realPath = value;
    }

    value = config.getInitParameter("pager.namespace");
    if (StringUtils.isNotEmpty(value)) {
        nameSpace = value;
    }

    value = config.getInitParameter("pager.wrapperPage");
    if (StringUtils.isNotEmpty(value)) {
        wrapperPage = value;
    }

    value = config.getInitParameter("pager.pre.page");
    if (StringUtils.isNotEmpty(value)) {
        prePage = value;
    }

    value = config.getInitParameter("pager.post.page");
    if (StringUtils.isNotEmpty(value)) {
        postPage = value;
    }

    // applicationContext =
    // WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
}

From source file:com.iorga.iraj.servlet.AgglomeratorServlet.java

private long searchAndAppendAfter(final ServletConfig config, final Element agglomerateElement,
        final String scriptSrc, final String pathPrefix, final String pathSuffix, final String urlAttribute,
        long lastModified) throws MalformedURLException, IOException, URISyntaxException {
    if (mode == Mode.DEVELOPMENT) {
        // add a watch for that directory
        final Path path = Paths.get(config.getServletContext().getRealPath(scriptSrc));
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
    }/*from www  . j  ava2  s .  c o m*/
    final Set<String> childrenPaths = config.getServletContext().getResourcePaths(scriptSrc);
    for (final String path : childrenPaths) {
        if (path.endsWith(pathSuffix)) {
            // add that JS
            final StringBuilder targetScript = new StringBuilder("<");
            targetScript.append(agglomerateElement.tagName());
            // copy all the origin attributes
            for (final Attribute attribute : agglomerateElement.attributes()) {
                final String key = attribute.getKey();
                if (!ATTRIBUTE_NAME.equalsIgnoreCase(key) && !urlAttribute.equalsIgnoreCase(key)
                        && !URL_ATTRIBUTE_ATTRIBUTE_NAME.equalsIgnoreCase(key)) {
                    targetScript.append(" ").append(attribute.html());
                }
            }
            // specify the src path
            final String childUrl = StringUtils.removeStart(path, pathPrefix);
            targetScript.append(" ").append(new Attribute(urlAttribute, childUrl).html()).append(" />");
            agglomerateElement.after(targetScript.toString());
            lastModified = Math.max(
                    config.getServletContext().getResource(childUrl).openConnection().getLastModified(),
                    lastModified);
        } else if (path.endsWith("/")) {
            // it's a directory, recurse search & append
            lastModified = Math.max(searchAndAppendAfter(config, agglomerateElement, path, pathPrefix,
                    pathSuffix, urlAttribute, lastModified), lastModified);
        }
    }
    return lastModified;
}