Example usage for javax.servlet Servlet getServletConfig

List of usage examples for javax.servlet Servlet getServletConfig

Introduction

In this page you can find the example usage for javax.servlet Servlet getServletConfig.

Prototype


public ServletConfig getServletConfig();

Source Link

Document

Returns a ServletConfig object, which contains initialization and startup parameters for this servlet.

Usage

From source file:com.jsmartframework.web.manager.WebContext.java

static final void setServlet(Servlet servlet) {
    smartServlet = servlet;//from   w w w . java2 s  . co  m
    jspContext = JSP_FACTORY.getJspApplicationContext(servlet.getServletConfig().getServletContext());
}

From source file:com.liferay.httpservice.internal.servlet.BundleServletContextTest.java

protected void registerServlet(String servletName, String... urlPatterns)
        throws NamespaceException, ServletException {

    mockBundleWiring();//from   w ww.ja  va2 s  .  c  o m

    when(_servlet.getServletConfig()).thenReturn(new MockServletConfig(servletName));

    _bundleServletContext.registerServlet(servletName, Arrays.asList(urlPatterns), _servlet, null,
            _httpContext);

    Servlet servlet = _bundleServletContext.getServlet(servletName);

    Assert.assertNotNull(servlet);

    Assert.assertEquals(servletName, servlet.getServletConfig().getServletName());

    Mockito.verify(_servlet).getServletConfig();

    verifyBundleWiring();
}

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 o  m
 *
 * @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:com.zimbra.cs.service.formatter.HtmlFormatter.java

static void dispatchJspRest(Servlet servlet, UserServletContext context)
        throws ServiceException, ServletException, IOException {
    AuthToken auth = null;// ww  w  .j  av  a 2  s . co  m
    long expiration = System.currentTimeMillis() + AUTH_EXPIRATION;
    if (context.basicAuthHappened) {
        Account acc = context.getAuthAccount();
        if (acc instanceof GuestAccount) {
            auth = AuthToken.getAuthToken(acc.getId(), acc.getName(), null, ((GuestAccount) acc).getDigest(),
                    expiration);
        } else {
            auth = AuthProvider.getAuthToken(context.getAuthAccount(), expiration);
        }
    } else if (context.cookieAuthHappened) {
        auth = UserServlet.getAuthTokenFromCookie(context.req, context.resp, true);
    } else {
        auth = AuthToken.getAuthToken(GuestAccount.GUID_PUBLIC, null, null, null, expiration);
    }
    if (auth != null && context.targetAccount != null && context.targetAccount != context.getAuthAccount()) {
        auth.setProxyAuthToken(
                Provisioning.getInstance().getProxyAuthToken(context.targetAccount.getId(), null));
    }
    String authString = null;
    try {
        if (auth != null)
            authString = auth.getEncoded();
    } catch (AuthTokenException e) {
        throw new ServletException("error generating the authToken", e);
    }

    Account targetAccount = context.targetAccount;
    MailItem targetItem = context.target;
    String uri = (String) context.req.getAttribute("requestedPath");

    if (targetItem instanceof Mountpoint
            && ((Mountpoint) targetItem).getDefaultView() != MailItem.Type.APPOINTMENT) {
        Mountpoint mp = (Mountpoint) targetItem;
        Provisioning prov = Provisioning.getInstance();
        targetAccount = prov.getAccountById(mp.getOwnerId());
        Pair<Header[], HttpInputStream> remoteItem = UserServlet.getRemoteResourceAsStream(
                (auth == null) ? null : auth.toZAuthToken(), mp.getTarget(), context.extraPath);
        remoteItem.getSecond().close();
        String remoteItemId = null;
        String remoteItemType = null;
        String remoteItemName = null;
        String remoteItemPath = null;
        for (Header h : remoteItem.getFirst())
            if (h.getName().compareToIgnoreCase("X-Zimbra-ItemId") == 0)
                remoteItemId = h.getValue();
            else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemType") == 0)
                remoteItemType = h.getValue();
            else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemName") == 0)
                remoteItemName = h.getValue();
            else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemPath") == 0)
                remoteItemPath = h.getValue();

        context.req.setAttribute(ATTR_TARGET_ITEM_ID, remoteItemId);
        context.req.setAttribute(ATTR_TARGET_ITEM_TYPE, remoteItemType);
        context.req.setAttribute(ATTR_TARGET_ITEM_NAME, remoteItemName);
        context.req.setAttribute(ATTR_TARGET_ITEM_PATH, remoteItemPath);
        context.req.setAttribute(ATTR_TARGET_ITEM_COLOR, mp.getColor());
        context.req.setAttribute(ATTR_TARGET_ITEM_VIEW, mp.getDefaultView().toByte());
        targetItem = null;
    }

    context.req.setAttribute(ATTR_INTERNAL_DISPATCH, "yes");
    context.req.setAttribute(ATTR_REQUEST_URI, uri != null ? uri : context.req.getRequestURI());
    context.req.setAttribute(ATTR_AUTH_TOKEN, authString);
    context.req.setAttribute(ATTR_CSRF_ENABLED, auth.isCsrfTokenEnabled());
    if (targetAccount != null) {
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_NAME, targetAccount.getName());
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_ID, targetAccount.getId());
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_TIME_ZONE,
                targetAccount.getAttr(Provisioning.A_zimbraPrefTimeZoneId));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_SKIN,
                targetAccount.getAttr(Provisioning.A_zimbraPrefSkin));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_LOCALE,
                targetAccount.getAttr(Provisioning.A_zimbraPrefLocale));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_FIRST_DAY_OF_WEEK,
                targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarFirstDayOfWeek));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_START,
                targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarDayHourStart));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_END,
                targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarDayHourEnd));
    } else {
        // Useful when faking results - e.g. FREEBUSY html view for non-existent account
        if (context.fakeTarget != null) {
            context.req.setAttribute(ATTR_TARGET_ACCOUNT_NAME, context.fakeTarget.getAccount());
        }
        com.zimbra.cs.account.Cos defaultCos = Provisioning.getInstance()
                .get(com.zimbra.common.account.Key.CosBy.name, Provisioning.DEFAULT_COS_NAME);
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_TIME_ZONE,
                defaultCos.getAttr(Provisioning.A_zimbraPrefTimeZoneId));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_SKIN,
                defaultCos.getAttr(Provisioning.A_zimbraPrefSkin));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_LOCALE,
                defaultCos.getAttr(Provisioning.A_zimbraPrefLocale));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_FIRST_DAY_OF_WEEK,
                defaultCos.getAttr(Provisioning.A_zimbraPrefCalendarFirstDayOfWeek));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_START,
                defaultCos.getAttr(Provisioning.A_zimbraPrefCalendarDayHourStart));
        context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_END,
                defaultCos.getAttr(Provisioning.A_zimbraPrefCalendarDayHourEnd));
    }
    if (targetItem != null) {
        context.req.setAttribute(ATTR_TARGET_ITEM_ID, targetItem.getId());
        context.req.setAttribute(ATTR_TARGET_ITEM_PATH, targetItem.getPath());
        context.req.setAttribute(ATTR_TARGET_ITEM_NAME, targetItem.getName());
        context.req.setAttribute(ATTR_TARGET_ITEM_TYPE, targetItem.getType().toString());

        context.req.setAttribute(ATTR_TARGET_ITEM_COLOR, targetItem.getColor());
        if (targetItem instanceof Folder) {
            context.req.setAttribute(ATTR_TARGET_ITEM_VIEW, ((Folder) targetItem).getDefaultView().toString());
        }
    } else {
        context.req.setAttribute(ATTR_TARGET_ITEM_COLOR, Color.getMappedColor(null));
    }
    if (context.fakeTarget != null) { // Override to avoid address harvesting
        context.req.setAttribute(ATTR_TARGET_ITEM_PATH, context.fakeTarget.getPath());
        context.req.setAttribute(ATTR_TARGET_ITEM_NAME, context.fakeTarget.getName());
    }
    String mailUrl = PATH_MAIN_CONTEXT;
    if (WebSplitUtil.isZimbraServiceSplitEnabled()) {
        mailUrl = Provisioning.getInstance().getLocalServer().getWebClientURL() + PATH_JSP_REST_PAGE;
        HttpClient httpclient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().getDefaultHttpClient();
        /*
         * Retest the code with POST to check whether it works
        PostMethod postMethod = new PostMethod(mailUrl);
        Enumeration<String> attributeNames = context.req.getAttributeNames();
        List<Part> parts = new ArrayList<Part>();
        while(attributeNames.hasMoreElements())
        {
        String attrName = (String) attributeNames.nextElement();
        String attrValue = context.req.getAttribute(attrName).toString();
        Part part = new StringPart(attrName, attrValue);
        parts.add(part);
        }
        postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams()));
                
        HttpClientUtil.executeMethod(httpclient, postMethod);
        ByteUtil.copy(postMethod.getResponseBodyAsStream(), true, context.resp.getOutputStream(), true);
        */

        Enumeration<String> attributeNames = context.req.getAttributeNames();
        StringBuilder sb = new StringBuilder(mailUrl);
        sb.append("?");
        while (attributeNames.hasMoreElements()) {
            String attrName = attributeNames.nextElement();
            String attrValue = context.req.getAttribute(attrName).toString();
            sb.append(attrName).append("=").append(HttpUtil.urlEscape(attrValue)).append("&");
        }
        GetMethod postMethod = new GetMethod(sb.toString());

        HttpClientUtil.executeMethod(httpclient, postMethod);
        ByteUtil.copy(postMethod.getResponseBodyAsStream(), true, context.resp.getOutputStream(), false);
    } else {
        try {
            mailUrl = Provisioning.getInstance().getLocalServer().getMailURL();
        } catch (Exception e) {
        }
        ServletContext targetContext = servlet.getServletConfig().getServletContext().getContext(mailUrl);
        RequestDispatcher dispatcher = targetContext.getRequestDispatcher(PATH_JSP_REST_PAGE);
        dispatcher.forward(context.req, context.resp);
    }
}

From source file:org.apache.cocoon.servletservice.ServletServiceContext.java

/**
 * Get the context of a servlet service with a given name.
 */// w  w w.ja  v  a2  s.c o  m
// FIXME implement NPE handling
public ServletContext getNamedContext(String name) {
    if (this.connections == null) {
        return null;
    }

    Servlet servlet = (Servlet) this.connections.get(name);
    if (servlet == null && !name.equals(SUPER)) {
        Servlet _super = ((Servlet) this.connections.get(SUPER));
        if (_super != null) {
            ServletContext c = _super.getServletConfig().getServletContext();
            if (c instanceof ServletServiceContext)
                return ((ServletServiceContext) c).getNamedContext(name);

            return null;
        }
    }
    return servlet != null ? servlet.getServletConfig().getServletContext() : null;
}

From source file:org.apache.jasper.runtime.PageContextImpl.java

private void _initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL,
        boolean needsSession, int bufferSize, boolean autoFlush) throws IOException {

    // initialize state
    this.servlet = servlet;
    this.config = servlet.getServletConfig();
    this.context = config.getServletContext();
    this.needsSession = needsSession;
    this.errorPageURL = errorPageURL;
    this.bufferSize = bufferSize;
    this.autoFlush = autoFlush;
    this.request = request;
    this.response = response;

    // Setup session (if required)
    if (request instanceof HttpServletRequest && needsSession)
        this.session = ((HttpServletRequest) request).getSession();
    if (needsSession && session == null)
        throw new IllegalStateException("Page needs a session and none is available");

    // initialize the initial out ...
    depth = -1;/*from w  ww .  j a va  2s.co  m*/
    if (this.baseOut == null) {
        this.baseOut = new JspWriterImpl(response, bufferSize, autoFlush);
    } else {
        this.baseOut.init(response, bufferSize, autoFlush);
    }
    this.out = baseOut;

    // register names/values as per spec
    setAttribute(OUT, this.out);
    setAttribute(REQUEST, request);
    setAttribute(RESPONSE, response);

    if (session != null)
        setAttribute(SESSION, session);

    setAttribute(PAGE, servlet);
    setAttribute(CONFIG, config);
    setAttribute(PAGECONTEXT, this);
    setAttribute(APPLICATION, context);

    isIncluded = request.getAttribute("javax.servlet.include.servlet_path") != null;
}

From source file:org.apache.sling.servlets.resolver.internal.SlingServletResolver.java

private void handleError(final Servlet errorHandler, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException {

    request.setAttribute(SlingConstants.ERROR_REQUEST_URI, request.getRequestURI());

    // if there is no explicitly known error causing servlet, use
    // the name of the error handler servlet
    if (request.getAttribute(SlingConstants.ERROR_SERVLET_NAME) == null) {
        request.setAttribute(SlingConstants.ERROR_SERVLET_NAME,
                errorHandler.getServletConfig().getServletName());
    }/*from  w  ww . j  a va  2 s  .c  o  m*/

    // Let the error handler servlet process the request and
    // forward all exceptions if it fails.
    // Before SLING-4143 we only forwarded IOExceptions.
    try {
        errorHandler.service(request, response);
        // commit the response
        response.flushBuffer();
        // close the response (SLING-2724)
        response.getWriter().close();
    } catch (final Throwable t) {
        LOGGER.error("Calling the error handler resulted in an error", t);
        LOGGER.error("Original error " + request.getAttribute(SlingConstants.ERROR_EXCEPTION_TYPE),
                (Throwable) request.getAttribute(SlingConstants.ERROR_EXCEPTION));
        final IOException x = new IOException("Error handler failed: " + t.getClass().getName());
        x.initCause(t);
        throw x;
    }
}

From source file:org.apache.struts2.jasper.runtime.PageContextImpl.java

private void _initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL,
        boolean needsSession, int bufferSize, boolean autoFlush) throws IOException {

    // initialize state
    this.servlet = servlet;
    this.config = servlet.getServletConfig();
    this.context = config.getServletContext();
    this.errorPageURL = errorPageURL;
    this.request = request;
    this.response = response;

    // Setup session (if required)
    if (request instanceof HttpServletRequest && needsSession)
        this.session = ((HttpServletRequest) request).getSession();
    if (needsSession && session == null)
        throw new IllegalStateException("Page needs a session and none is available");

    // initialize the initial out ...
    depth = -1;/* w  w  w .j  a  v a2 s.c o m*/
    if (this.baseOut == null) {
        this.baseOut = new JspWriterImpl(response, bufferSize, autoFlush);
    } else {
        this.baseOut.init(response, bufferSize, autoFlush);
    }
    this.out = baseOut;

    // register names/values as per spec
    setAttribute(OUT, this.out);
    setAttribute(REQUEST, request);
    setAttribute(RESPONSE, response);

    if (session != null)
        setAttribute(SESSION, session);

    setAttribute(PAGE, servlet);
    setAttribute(CONFIG, config);
    setAttribute(PAGECONTEXT, this);
    setAttribute(APPLICATION, context);

    isIncluded = request.getAttribute("javax.servlet.include.servlet_path") != null;
}

From source file:org.codehaus.groovy.grails.web.pages.ext.jsp.GroovyPagesPageContext.java

public GroovyPagesPageContext(Servlet pagesServlet, Binding pageScope) {
    Assert.notNull(pagesServlet, "GroovyPagesPageContext class requires a reference to the GSP servlet");
    webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();

    servletContext = webRequest.getServletContext();
    request = webRequest.getCurrentRequest();
    response = webRequest.getCurrentResponse();
    servlet = pagesServlet;/*from  w w w  .  j  ava2 s. c om*/
    servletconfig = pagesServlet.getServletConfig();
    this.pageScope = pageScope;
    session = request.getSession(false);
    // setup initial writer
    pushWriter(new JspWriterDelegate(webRequest.getOut()));
    // Register page attributes as per JSP spec
    setAttribute(REQUEST, request);
    setAttribute(RESPONSE, response);
    if (session != null) {
        setAttribute(SESSION, session);
    }
    setAttribute(PAGE, servlet);
    setAttribute(CONFIG, servlet.getServletConfig());
    setAttribute(PAGECONTEXT, this);
    setAttribute(APPLICATION, servletContext);
}

From source file:org.massyframework.assembly.servlet.jasper.JasparResourceProessor.java

@Override
public void process(HttpServletRequest req, HttpServletResponse resp, HttpResource resource)
        throws ServletException, IOException {

    Servlet servlet = this.getOrCreateJspServelt(resource);
    String path = resource.getName() + req.getPathInfo();
    req.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, path);

    ClassLoader loader = ClassLoaderUtils
            .setThreadContextClassLoader(servlet.getServletConfig().getServletContext().getClassLoader());
    try {//ww  w .ja v a  2  s  .c  o  m
        servlet.service(req, resp);
    } finally {
        ClassLoaderUtils.setThreadContextClassLoader(loader);
    }
}