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.apache.axis2.jaxws.description.builder.JAXWSRIWSDLGenerator.java

/**
 * This method will drive the call to WsGen to generate a WSDL file for
 * applications deployed without WSDL. We will then read this file in from
 * disk and create a Definition. After we are done with the file we will
 * remove it from disk.  This method accepts a CatalogManager as a parameter
 * for the eventual use in by an XMLSchemaCollection.
 *///from ww  w . ja  v a  2 s  .  co m
public void generateWsdl(String className, String bindingType, JAXWSCatalogManager catalogManager)
        throws WebServiceException {

    if (this.axisConfiguration == null) {
        this.axisConfiguration = axisService.getAxisConfiguration();
    }
    File tempFile = (File) axisConfiguration.getParameterValue(Constants.Configuration.ARTIFACTS_TEMP_DIR);
    if (tempFile == null) {
        tempFile = new File(getProperty_doPriv("java.io.tmpdir"), "_axis2");
    }

    Parameter servletConfigParam = axisConfiguration.getParameter(HTTPConstants.HTTP_SERVLETCONFIG);

    String webBase = null;
    if (servletConfigParam != null) {
        Object obj = servletConfigParam.getValue();
        ServletContext servletContext;

        if (obj instanceof ServletConfig) {
            ServletConfig servletConfig = (ServletConfig) obj;
            servletContext = servletConfig.getServletContext();
            webBase = servletContext.getRealPath("/WEB-INF");
        }
    }

    if (classPath == null) {
        this.classPath = getDefaultClasspath(webBase);
    }
    if (log.isDebugEnabled()) {
        log.debug("For implementation class " + className + " WsGen classpath: " + classPath);
    }
    String localOutputDirectory = tempFile.getAbsolutePath() + className + "_" + axisService.getName();
    if (log.isDebugEnabled()) {
        log.debug("Output directory for generated WSDL file: " + localOutputDirectory);
    }
    try {

        if (log.isDebugEnabled()) {
            log.debug("Generating new WSDL Definition");
        }

        createOutputDirectory(localOutputDirectory);
        Class clazz;
        try {
            // Try the one in JDK16
            clazz = Class.forName("com.sun.tools.internal.ws.spi.WSToolsObjectFactory");
        } catch (Throwable t) {
            // Look for the RI
            clazz = Class.forName("com.sun.tools.ws.spi.WSToolsObjectFactory");
        }
        Method m1 = clazz.getMethod("newInstance", new Class[] {});
        Object factory = m1.invoke(new Object[] {});
        String[] arguments = getWsGenArguments(className, bindingType, localOutputDirectory);
        OutputStream os = new ByteArrayOutputStream();
        Method m2 = clazz.getMethod("wsgen", new Class[] { OutputStream.class, String[].class });
        m2.invoke(factory, os, arguments);
        os.close();
        wsdlDefMap = readInWSDL(localOutputDirectory);
        if (wsdlDefMap.isEmpty()) {
            throw new Exception(
                    "A WSDL Definition could not be generated for " + "the implementation class: " + className);
        }
        docMap = readInSchema(localOutputDirectory, catalogManager);
    } catch (Throwable t) {
        String msg = "Error occurred generating WSDL file for Web service implementation class " + "{"
                + className + "}";
        log.error(msg, t);
        throw new WebServiceException(msg, t);
    }
}

From source file:org.jfree.eastwood.ChartServlet.java

/**
 * Initialise the servlet.//from  ww  w . j  a va2  s. c o m
 *
 * @param config  the config.
 *
 * @throws ServletException
 */
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    String fontSizeParam = config.getInitParameter("fontSize");
    String fontResourceParam = config.getInitParameter("fontResource");
    String fontFileParam = config.getInitParameter("fontFile");
    String fontParam = config.getInitParameter("font");

    float fontSize = 12f;
    if (fontSizeParam != null) {
        fontSize = Integer.parseInt(fontSizeParam);
    }

    if (fontResourceParam != null) {
        ServletContext ctx = config.getServletContext();
        this.font = readFontResource(ctx, fontResourceParam, fontSize);
    } else if (fontFileParam != null) {
        this.font = readFontFile(fontFileParam, fontSize);
    } else if (fontParam != null) {
        this.font = new Font(fontParam, Font.PLAIN, (int) fontSize);
    } else {
        this.font = new Font("Dialog", Font.PLAIN, (int) fontSize);
    }
}

From source file:com.hortonworks.amstore.view.AmbariStoreServlet.java

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

    ServletContext context = config.getServletContext();
    viewContext = (ViewContext) context.getAttribute(ViewContext.CONTEXT_ATTRIBUTE);

    // main Store Instance (this)
    mainStoreApplication = new MainStoreApplication(viewContext);
}

From source file:edu.internet2.middleware.shibboleth.idp.StatusServlet.java

/** {@inheritDoc} */
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    allowedIPs = new LazyList<IPRange>();

    String cidrBlocks = DatatypeHelper.safeTrimOrNullString(config.getInitParameter(IP_PARAM_NAME));
    if (cidrBlocks != null) {
        for (String cidrBlock : cidrBlocks.split(" ")) {
            allowedIPs.add(IPRange.parseCIDRBlock(cidrBlock));
        }//from  ww w.  j a  v  a 2 s .  com
    }

    dateFormat = ISODateTimeFormat.dateTimeNoMillis();
    startTime = new DateTime(ISOChronology.getInstanceUTC());
    attributeResolver = HttpServletHelper.getAttributeResolver(config.getServletContext());
    rpConfigManager = HttpServletHelper.getRelyingPartyConfirmationManager(config.getServletContext());
}

From source file:com.concursive.connect.web.controller.hooks.SecurityHook.java

/**
 * Checks to see if a User session object exists, if not then the security
 * check fails./*from w  w  w  . j a  v a 2  s . c om*/
 *
 * @param servlet  Description of the Parameter
 * @param request  Description of the Parameter
 * @param response Description of the Parameter
 * @return Description of the Return Value
 */
public String beginRequest(Servlet servlet, HttpServletRequest request, HttpServletResponse response) {
    LOG.debug("Security request made");
    ServletConfig config = servlet.getServletConfig();
    ServletContext context = config.getServletContext();
    // Application wide preferences
    ApplicationPrefs prefs = (ApplicationPrefs) context.getAttribute(Constants.APPLICATION_PREFS);
    // Get the intended action, if going to the login module, then let it proceed
    String s = request.getServletPath();
    int slash = s.lastIndexOf("/");
    s = s.substring(slash + 1);
    // If not setup then go to setup
    if (!s.startsWith("Setup") && !prefs.isConfigured()) {
        return "NotSetupError";
    }
    // External calls
    if (s.startsWith("Service")) {
        return null;
    }
    // Set the layout relevant to this request
    if ("text".equals(request.getParameter("out")) || "text".equals(request.getAttribute("out"))) {
        // do not use a layout, send the raw output
    } else if ("true".equals(request.getParameter(Constants.REQUEST_PARAM_POPUP))) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
    } else if ("true".equals(request.getParameter(Constants.REQUEST_PARAM_STYLE))) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
    } else {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, context.getAttribute(Constants.REQUEST_TEMPLATE));
    }
    // If going to Setup then allow
    if (s.startsWith("Setup")) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
        return null;
    }
    // If going to Upgrade then allow
    if (s.startsWith("Upgrade")) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
        return null;
    }
    // Detect mobile users and mobile formatting
    //    ClientType clientType = (ClientType) request.getSession().getAttribute(Constants.SESSION_CLIENT_TYPE);
    // @todo introduce when mobile is implemented
    //    if (clientType.getMobile()) {
    //      request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layoutMobile.jsp");
    //    }

    // URL forwarding for MVC requests (*.do, etc.)
    String requestedPath = (String) request.getAttribute("requestedURL");
    if (requestedPath == null && "GET".equals(request.getMethod())
            && request.getParameter("redirectTo") == null) {
        // Save the requestURI to be used downstream
        String contextPath = request.getContextPath();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        requestedPath = uri.substring(contextPath.length()) + (queryString == null ? "" : "?" + queryString);
        LOG.debug("Requested path: " + requestedPath);
        request.setAttribute("requestedURL", requestedPath);

        // It's important the user is using the correct URL for accessing content;
        // The portal has it's own redirect scheme, this is a general catch all
        if (!s.startsWith("Portal") && !uri.contains(".shtml") && prefs.has(ApplicationPrefs.WEB_DOMAIN_NAME)) {
            // Check to see if an old domain name is used
            PortalBean bean = new PortalBean(request);
            String expectedDomainName = prefs.get(ApplicationPrefs.WEB_DOMAIN_NAME);
            if (expectedDomainName != null && requestedPath != null && !"127.0.0.1".equals(bean.getServerName())
                    && !"127.0.0.1".equals(expectedDomainName) && !"localhost".equals(bean.getServerName())
                    && !"localhost".equals(expectedDomainName)
                    && !bean.getServerName().equals(expectedDomainName)
                    && !bean.getServerName().startsWith("10.") && !bean.getServerName().startsWith("172.")
                    && !bean.getServerName().startsWith("192.")) {
                if (uri != null && !uri.substring(1).equals(prefs.get("PORTAL.INDEX"))) {
                    String newUrl = URLFactory.createURL(prefs.getPrefs()) + requestedPath;
                    request.setAttribute("redirectTo", newUrl);
                    LOG.debug("redirectTo: " + newUrl);
                    request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
                    return "Redirect301";
                }
            }
        }
    }

    // Version check
    if (!s.startsWith("Login") && ApplicationVersion.isOutOfDate(prefs)) {
        return "UpgradeCheck";
    }
    // Get the user object from the Session Validation...
    if (sessionValidator == null) {
        sessionValidator = SessionValidatorFactory.getInstance()
                .getSessionValidator(servlet.getServletConfig().getServletContext(), request);
        LOG.debug("Found sessionValidator? " + (sessionValidator != null));
    }
    // Check cookie for user's previous location info
    SearchBean searchBean = (SearchBean) request.getSession().getAttribute(Constants.SESSION_SEARCH_BEAN);
    if (searchBean == null) {
        String searchLocation = CookieUtils.getCookieValue(request, Constants.COOKIE_USER_SEARCH_LOCATION);
        if (searchLocation != null) {
            LOG.debug("Setting search location from cookie: " + searchLocation);
            searchBean = new SearchBean();
            searchBean.setLocation(searchLocation);
            request.getSession().setAttribute(Constants.SESSION_SEARCH_BEAN, searchBean);
        }
    }
    // Continue with session creation...
    User userSession = sessionValidator.validateSession(context, request, response);
    ConnectionElement ceSession = (ConnectionElement) request.getSession()
            .getAttribute(Constants.SESSION_CONNECTION_ELEMENT);
    // The user is going to the portal so get them guest credentials if they need them
    if ("true".equals(prefs.get("PORTAL")) || s.startsWith("Register") || s.startsWith("ResetPassword")
            || s.startsWith("LoginAccept") || s.startsWith("LoginReject") || s.startsWith("Search")
            || s.startsWith("ContactUs")) {
        if (userSession == null || ceSession == null) {
            // Allow portal mode to create a default session with guest capabilities
            userSession = UserUtils.createGuestUser();
            request.getSession().setAttribute(Constants.SESSION_USER, userSession);
            // Give them a connection element
            ceSession = new ConnectionElement();
            ceSession.setDriver(prefs.get("SITE.DRIVER"));
            ceSession.setUrl(prefs.get("SITE.URL"));
            ceSession.setUsername(prefs.get("SITE.USER"));
            ceSession.setPassword(prefs.get("SITE.PASSWORD"));
            request.getSession().setAttribute(Constants.SESSION_CONNECTION_ELEMENT, ceSession);
        }
        // Make sure SSL is being used for this connection
        if (userSession.getId() > 0 && "true".equals(prefs.get("SSL"))
                && !"https".equals(request.getScheme())) {
            LOG.info("Redirecting to..." + requestedPath);
            request.setAttribute("redirectTo",
                    "https://" + request.getServerName() + request.getContextPath() + requestedPath);
            request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
            return "Redirect301";
        }
        // Generate global items
        Connection db = null;
        try {
            db = getConnection(context, request);
            // TODO: Implement cache since every hit needs this list
            if (db != null) {
                // Load the project languages
                WebSiteLanguageList webSiteLanguageList = new WebSiteLanguageList();
                webSiteLanguageList.setEnabled(Constants.TRUE);
                webSiteLanguageList.buildList(db);
                // If an admin of a language, enable it...
                webSiteLanguageList.add(userSession.getWebSiteLanguageList());
                request.setAttribute("webSiteLanguageList", webSiteLanguageList);

                // Load the menu list
                ProjectList menu = new ProjectList();
                PagedListInfo menuListInfo = new PagedListInfo();
                menuListInfo.setColumnToSortBy("p.portal_default desc, p.level asc, p.title asc");
                menuListInfo.setItemsPerPage(-1);
                menu.setPagedListInfo(menuListInfo);
                menu.setIncludeGuestProjects(false);
                menu.setPortalState(Constants.TRUE);
                menu.setOpenProjectsOnly(true);
                menu.setApprovedOnly(true);
                menu.setBuildLink(true);
                menu.setLanguageId(webSiteLanguageList.getLanguageId(request));
                menu.buildList(db);
                request.setAttribute("menuList", menu);

                // Load the main profile to use throughout
                Project mainProfile = ProjectUtils.loadProject(prefs.get("MAIN_PROFILE"));
                request.setAttribute(Constants.REQUEST_MAIN_PROFILE, mainProfile);

                // Load the project categories for search and tab menus
                ProjectCategoryList categoryList = new ProjectCategoryList();
                categoryList.setEnabled(Constants.TRUE);
                categoryList.setTopLevelOnly(true);
                categoryList.buildList(db);
                request.setAttribute(Constants.REQUEST_TAB_CATEGORY_LIST, categoryList);

                // Determine the tab that needs to be highlighted
                int chosenTabId = -1;
                if (requestedPath != null) {
                    String chosenCategory = null;
                    String chosenTab = null;
                    if (requestedPath.length() > 0) {
                        chosenTab = requestedPath.substring(1);
                    }
                    LOG.debug("chosenTab? " + chosenTab);
                    if (chosenTab == null || "".equals(chosenTab)) {
                        LOG.debug("Setting tab to Home");
                        chosenTab = "home.shtml";
                    } else {
                        boolean foundChosenTab = false;
                        for (ProjectCategory projectCategory : categoryList) {
                            String categoryName = projectCategory.getDescription();
                            String normalizedCategoryTab = projectCategory.getNormalizedCategoryName()
                                    .concat(".shtml");
                            if (chosenTab.startsWith(normalizedCategoryTab)) {
                                foundChosenTab = true;
                                chosenCategory = categoryName;
                                chosenTabId = projectCategory.getId();
                                LOG.debug("found: " + chosenCategory);
                            }
                        }
                        if (!foundChosenTab) {
                            LOG.debug("No tab to highlight");
                            chosenTab = "none";
                        }
                    }
                    request.setAttribute("chosenTab", chosenTab);
                    request.setAttribute("chosenCategory", chosenCategory);
                }

                // Go through the tabs and remove the ones the user shouldn't see, also check permission
                if (!userSession.isLoggedIn()) {
                    boolean allowed = true;
                    Iterator i = categoryList.iterator();
                    while (i.hasNext()) {
                        ProjectCategory projectCategory = (ProjectCategory) i.next();
                        if (projectCategory.getSensitive()) {
                            if (chosenTabId == projectCategory.getId()) {
                                allowed = false;
                            }
                            i.remove();
                        }
                    }
                    if (!allowed) {
                        // Redirect to the login, perhaps the page would exist then
                        String newUrl = URLFactory.createURL(prefs.getPrefs()) + "/login?redirectTo="
                                + requestedPath;
                        request.setAttribute("redirectTo", newUrl);
                        LOG.debug("redirectTo: " + newUrl);
                        request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
                        return "Redirect301";
                    }
                }

                // Category drop-down for search
                HtmlSelect thisSelect = categoryList.getHtmlSelect();
                thisSelect.addItem(-1, prefs.get("TITLE"), 0);
                request.setAttribute(Constants.REQUEST_MENU_CATEGORY_LIST, thisSelect);
            }
        } catch (Exception e) {
            LOG.error("Global items error", e);
        } finally {
            this.freeConnection(context, db);
        }
    }

    // The user is not going to login, so verify login
    if (!s.startsWith("Login")) {
        if (userSession == null || ceSession == null) {
            // boot them off now
            LOG.debug("Security failed.");
            LoginBean failedSession = new LoginBean();
            failedSession.addError("actionError", "* Please login, your session has expired");
            failedSession.checkURL(request);
            request.setAttribute("LoginBean", failedSession);
            request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
            return "SecurityCheck";
        } else {
            // The user should have a valid login now, so let them proceed
            LOG.debug("Security passed: " + userSession.getId() + " (" + userSession.getUsername() + ")");
        }
    }
    // Generate user's global items
    if (userSession != null && userSession.getId() > 0) {
        Connection db = null;
        try {
            db = getConnection(context, request);
            // TODO: Implement cache since every hit needs this list
            if (db != null) {
                // A map for global alerts
                ArrayList<String> alerts = new ArrayList<String>();
                request.setAttribute(Constants.REQUEST_GLOBAL_ALERTS, alerts);

                // Check to see if the application is configured...
                if (userSession.getAccessAdmin()) {
                    String url = URLFactory.createURL(prefs.getPrefs());
                    if (url == null) {
                        alerts.add(
                                "The application configuration requires that the URL properties are updated.  Store <strong>"
                                        + RequestUtils.getAbsoluteServerUrl(request) + "</strong>? <a href=\""
                                        + RequestUtils.getAbsoluteServerUrl(request)
                                        + "/AdminUsage.do?command=StoreURL\">Save Changes</a>");
                    } else if (!url.equals(RequestUtils.getAbsoluteServerUrl(request))) {
                        alerts.add("There is a configuration mismatch -- expected: <strong>"
                                + RequestUtils.getAbsoluteServerUrl(request)
                                + "</strong> but the configuration has <strong><a href=\"" + url + "\">" + url
                                + "</a></strong> <a href=\"" + RequestUtils.getAbsoluteServerUrl(request)
                                + "/AdminUsage.do?command=StoreURL\">Save Changes</a>");
                    }
                }

                // Check the # of invitations
                int invitationCount = InvitationList.queryCount(db, userSession.getId(),
                        userSession.getProfileProjectId());
                request.setAttribute(Constants.REQUEST_INVITATION_COUNT, String.valueOf(invitationCount));

                // Check the # of private messages
                int newMailCount = PrivateMessageList.queryUnreadCountForUser(db, userSession.getId());
                request.setAttribute(Constants.REQUEST_PRIVATE_MESSAGE_COUNT, String.valueOf(newMailCount));

                // NOTE: removed because not currently used
                // Check the number of what's new
                //          int whatsNewCount = ProjectUtils.queryWhatsNewCount(db, userSession.getId());
                //          request.setAttribute(Constants.REQUEST_WHATS_NEW_COUNT, String.valueOf(whatsNewCount));
                // Check the number of assignments
                //          int whatsAssignedCount = ProjectUtils.queryWhatsAssignedCount(db, userSession.getId());
                //          request.setAttribute(Constants.REQUEST_WHATS_ASSIGNED_COUNT, String.valueOf(whatsAssignedCount));
                //          int projectCount = ProjectUtils.queryMyProjectCount(db, userSession.getId());
                //          request.setAttribute(Constants.REQUEST_MY_PROJECT_COUNT, String.valueOf(projectCount));
            }
        } catch (Exception e) {
            LOG.error("User's global items error", e);
        } finally {
            this.freeConnection(context, db);
        }
    }
    return null;
}

From source file:be.integrationarchitects.web.dragdrop.servlet.impl.DragDropServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    random = new SecureRandom();
    String str_cfg = servletConfig.getInitParameter("cfg");
    Class c = null;/*from   w w  w .  jav a 2s . c o  m*/
    try {
        c = Class.forName(str_cfg);
        cfg = (DragDropServletConfig) c.newInstance();
        logger = cfg.getLogger();

        //used in 500.jsp for error logging
        servletConfig.getServletContext().setAttribute("mycfg", cfg);

    } catch (Exception e) {
        System.err.println(e.getMessage());
        throw new ServletException(e);
    }
    utils = new DragDropServletUtils(cfg.getFolder(), cfg.checkHash(), logger);
    logger.logDebug(".....................................Init drag drop servlet ok:" + str_cfg + ":"
            + cfg.getHandler() + ":" + cfg.getFolder());
}

From source file:org.springframework.flex.config.FlexConfigurationManager.java

/**
 * Parses the BlazeDS config files and returns a populated MessagingConfiguration
 * //from ww  w.j  a va  2 s. c om
 * @param servletConfig the servlet config for the web application
 */
@SuppressWarnings("unchecked")
public MessagingConfiguration getMessagingConfiguration(ServletConfig servletConfig) {
    Assert.isTrue(JdkVersion.getMajorJavaVersion() >= JdkVersion.JAVA_15,
            "Spring BlazeDS Integration requires a minimum of Java 1.5");
    Assert.notNull(servletConfig, "FlexConfigurationManager requires a non-null ServletConfig - "
            + "Is it being used outside a WebApplicationContext?");

    MessagingConfiguration configuration = new MessagingConfiguration();

    configuration.getSecuritySettings().setServerInfo(servletConfig.getServletContext().getServerInfo());

    if (CollectionUtils.isEmpty(configuration.getSecuritySettings().getLoginCommands())) {
        LoginCommandSettings settings = new LoginCommandSettings();
        settings.setClassName(NoOpLoginCommand.class.getName());
        configuration.getSecuritySettings().getLoginCommands().put(LoginCommandSettings.SERVER_MATCH_OVERRIDE,
                settings);
    }

    if (this.parser == null) {
        this.parser = getDefaultConfigurationParser();
    }

    Assert.notNull(this.parser, "Unable to create a parser to load Flex messaging configuration.");

    this.parser.parse(this.configurationPath, new ResourceResolverAdapter(this.resourceLoader), configuration);

    return configuration;
}

From source file:org.eclipse.equinox.servletbridge.FrameworkLauncher.java

void init(ServletConfig servletConfig) {
    config = servletConfig;
    context = servletConfig.getServletContext();
    initResourceBase();
    init();
}

From source file:lucee.runtime.config.ConfigWebImpl.java

/**
 * constructor of the class//ww w. j ava 2  s. c  om
 * @param configServer
 * @param config
 * @param configDir
 * @param configFile
 * @param cloneServer 
 */
protected ConfigWebImpl(CFMLFactoryImpl factory, ConfigServerImpl configServer, ServletConfig config,
        Resource configDir, Resource configFile) {
    super(factory, configDir, configFile, configServer.getTLDs(), configServer.getFLDs());
    this.configServer = configServer;
    this.config = config;
    factory.setConfig(this);
    ResourceProvider frp = ResourcesImpl.getFileResourceProvider();

    this.rootDir = frp.getResource(ReqRspUtil.getRootPath(config.getServletContext()));

    // Fix for tomcat
    if (this.rootDir.getName().equals(".") || this.rootDir.getName().equals(".."))
        this.rootDir = this.rootDir.getParentResource();
}