Example usage for javax.servlet ServletContext getContext

List of usage examples for javax.servlet ServletContext getContext

Introduction

In this page you can find the example usage for javax.servlet ServletContext getContext.

Prototype

public ServletContext getContext(String uripath);

Source Link

Document

Returns a ServletContext object that corresponds to a specified URL on the server.

Usage

From source file:com.liferay.portal.struts.StrutsUtil.java

public static void include(String uri, ServletContext ctx, HttpServletRequest req, HttpServletResponse res)
        throws ServletException {

    String path = Constants.TEXT_HTML_DIR + uri;
    if (BrowserSniffer.is_wml(req)) {
        path = Constants.TEXT_WML_DIR + uri;
    }/*w  w  w . ja v a2 s.co m*/

    ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX));
    if (portalCtx == null) {
        portalCtx = ctx;
    }

    RequestDispatcher rd = portalCtx.getRequestDispatcher(path);

    try {
        rd.include(req, res);
    } catch (IOException ioe) {
    }
}

From source file:com.liferay.portal.struts.StrutsUtil.java

public static void forward(String uri, ServletContext ctx, HttpServletRequest req, HttpServletResponse res)
        throws ServletException {

    if (!res.isCommitted()) {
        String path = Constants.TEXT_HTML_DIR + uri;
        if (BrowserSniffer.is_wml(req)) {
            path = Constants.TEXT_WML_DIR + uri;
        }//w w w  .ja  va  2  s.c  om

        ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX));

        if (portalCtx == null) {
            portalCtx = ctx;
        }

        RequestDispatcher rd = portalCtx.getRequestDispatcher(path);

        try {
            rd.forward(req, res);
        } catch (IOException ioe1) {
            Logger.error(StrutsUtil.class, ioe1.getMessage(), ioe1);
        } catch (ServletException se1) {
            req.setAttribute(PageContext.EXCEPTION, se1.getRootCause());

            String errorPath = Constants.TEXT_HTML_DIR + Constants.COMMON_ERROR;
            if (BrowserSniffer.is_wml(req)) {
                path = Constants.TEXT_WML_DIR + Constants.COMMON_ERROR;
            }

            rd = portalCtx.getRequestDispatcher(errorPath);

            try {
                rd.forward(req, res);
            } catch (IOException ioe2) {
                Logger.error(StrutsUtil.class, ioe2.getMessage(), ioe2);
            } catch (ServletException se2) {
                throw se2;
            }
        }
    } else {
        _log.warn(uri + " is already committed");
    }
}

From source file:com.liferay.portal.servlet.MainServlet.java

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    if (!PortalInstances.matches()) {
        String html = ContentUtil.get("messages/en_US/init.html");

        res.getOutputStream().print(html);

        return;// w w w .  j  a  va2s .c o m
    }

    if (ShutdownUtil.isShutdown()) {
        String html = ContentUtil.get("messages/en_US/shutdown.html");

        res.getOutputStream().print(html);

        return;
    }
    req.setAttribute("dotcache", "no");
    // Shared session

    HttpSession ses = req.getSession();

    if (!GetterUtil.getBoolean(PropsUtil.get(PropsUtil.TCK_URL))) {
        String sharedSessionId = CookieUtil.get(req.getCookies(), CookieKeys.SHARED_SESSION_ID);

        _log.debug("Shared session id is " + sharedSessionId);

        if (sharedSessionId == null) {
            sharedSessionId = PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2, 12);

            Cookie sharedSessionIdCookie = new Cookie(CookieKeys.SHARED_SESSION_ID, sharedSessionId);
            sharedSessionIdCookie.setPath("/");
            sharedSessionIdCookie.setMaxAge(86400);

            res.addCookie(sharedSessionIdCookie);

            _log.debug("Shared session id is " + sharedSessionId);
        }

        // if (ses.getAttribute(WebKeys.SHARED_SESSION_ID) == null) {
        ses.setAttribute(WebKeys.SHARED_SESSION_ID, sharedSessionId);
        // }

        HttpSession portalSes = (HttpSession) SharedSessionPool.get(sharedSessionId);

        if ((portalSes == null) || (ses != portalSes)) {
            if (portalSes == null) {
                _log.debug("No session exists in pool");
            } else {
                _log.debug("Session " + portalSes.getId() + " in pool is old");
            }

            _log.debug("Inserting current session " + ses.getId() + " in pool");

            SharedSessionPool.put(sharedSessionId, ses);
        }
    }

    // Test CAS auto login

    /*
     * ses.setAttribute(
     * com.liferay.portal.auth.CASAutoLogin.CAS_FILTER_USER,
     * "liferay.com.1");
     */

    // CTX

    ServletContext ctx = getServletContext();
    ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX));
    if (portalCtx == null) {
        portalCtx = ctx;
    }

    req.setAttribute(WebKeys.CTX, portalCtx);

    // CTX_PATH variable

    String ctxPath = (String) ctx.getAttribute(WebKeys.CTX_PATH);

    if (portalCtx.getAttribute(WebKeys.CTX_PATH) == null) {
        portalCtx.setAttribute(WebKeys.CTX_PATH, ctxPath);
    }

    if (ses.getAttribute(WebKeys.CTX_PATH) == null) {
        ses.setAttribute(WebKeys.CTX_PATH, ctxPath);
    }

    req.setAttribute(WebKeys.CTX_PATH, ctxPath);

    // CAPTCHA_PATH variable

    String captchaPath = (String) ctx.getAttribute(WebKeys.CAPTCHA_PATH);

    if (portalCtx.getAttribute(WebKeys.CAPTCHA_PATH) == null) {
        portalCtx.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);
    }

    if (ses.getAttribute(WebKeys.CAPTCHA_PATH) == null) {
        ses.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);
    }

    req.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);

    // IMAGE_PATH variable

    String imagePath = (String) ctx.getAttribute(WebKeys.IMAGE_PATH);

    if (portalCtx.getAttribute(WebKeys.IMAGE_PATH) == null) {
        portalCtx.setAttribute(WebKeys.IMAGE_PATH, imagePath);
    }

    if (ses.getAttribute(WebKeys.IMAGE_PATH) == null) {
        ses.setAttribute(WebKeys.IMAGE_PATH, imagePath);
    }

    req.setAttribute(WebKeys.IMAGE_PATH, imagePath);

    // WebKeys.COMPANY_ID variable

    String companyId = (String) ctx.getAttribute(WebKeys.COMPANY_ID);

    if (portalCtx.getAttribute(WebKeys.COMPANY_ID) == null) {
        portalCtx.setAttribute(WebKeys.COMPANY_ID, companyId);
    }

    if (ses.getAttribute(WebKeys.COMPANY_ID) == null) {
        ses.setAttribute(WebKeys.COMPANY_ID, companyId);
    }

    req.setAttribute(WebKeys.COMPANY_ID, companyId);

    // Portlet Request Processor

    PortletRequestProcessor portletReqProcessor = (PortletRequestProcessor) portalCtx
            .getAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR);

    if (portletReqProcessor == null) {
        portletReqProcessor = new PortletRequestProcessor(this, getModuleConfig(req));

        portalCtx.setAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor);
    }

    // Tiles definitions factory

    if (portalCtx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY) == null) {
        portalCtx.setAttribute(TilesUtilImpl.DEFINITIONS_FACTORY,
                ctx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY));
    }

    // Set character encoding

    String strutsCharEncoding = PropsUtil.get(PropsUtil.STRUTS_CHAR_ENCODING);

    req.setCharacterEncoding(strutsCharEncoding);

    /*
     * if (!BrowserSniffer.is_wml(req)) { res.setContentType(
     * Constants.TEXT_HTML + "; charset=" + strutsCharEncoding); }
     */

    // Determine content type

    String contentType = req.getHeader("Content-Type");

    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))) {

        req = new UploadServletRequest(req);
    } else if (ParamUtil.get(req, WebKeys.ENCRYPT, false)) {
        try {
            Company company = CompanyLocalManagerUtil.getCompany(companyId);

            req = new EncryptedServletRequest(req, company.getKeyObj());
        } catch (Exception e) {
        }
    }

    // Current URL

    String completeURL = Http.getCompleteURL(req);
    if (completeURL.indexOf("j_security_check") != -1) {
        completeURL = ctxPath;
    } else {
        completeURL = completeURL.substring(completeURL.indexOf("://") + 3, completeURL.length());

        completeURL = completeURL.substring(completeURL.indexOf("/"), completeURL.length());
    }

    req.setAttribute(WebKeys.CURRENT_URL, completeURL);

    // Chat server

    // Login

    String userId = PortalUtil.getUserId(req);

    if ((userId != null)) {
        PrincipalThreadLocal.setName(userId);
    }

    if (userId == null) {
        try {
            User user = UserManagerUtil.getDefaultUser(companyId);
            if (ses.getAttribute(Globals.LOCALE_KEY) == null)
                ses.setAttribute(Globals.LOCALE_KEY, user.getLocale());

        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }
    }

    // Process pre service events

    try {
        EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_PRE), req, res);
    } catch (Exception e) {
        Logger.error(this, e.getMessage(), e);

        req.setAttribute(PageContext.EXCEPTION, e);

        StrutsUtil.forward(PropsUtil.get(PropsUtil.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE), portalCtx, req, res);
    }

    // Struts service

    callParentService(req, res);

    // Process post service events

    try {
        EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_POST), req, res);
    } catch (Exception e) {
        Logger.error(this, e.getMessage(), e);
    }

    // Clear the principal associated with this thread

    PrincipalThreadLocal.setName(null);
}

From source file:net.community.chest.gitcloud.facade.frontend.git.GitController.java

private void serveRequest(RequestMethod method, HttpServletRequest req, HttpServletResponse rsp)
        throws IOException, ServletException {
    if (logger.isDebugEnabled()) {
        logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]");
    }//from  w w w.j  a  v a  2s .  com

    if ((loopRetryTimeout > 0L) && (!loopDetected)) {
        long now = System.currentTimeMillis(), diff = now - initTimestamp;
        if ((diff > 0L) && (diff < loopRetryTimeout)) {
            try {
                MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(new ObjectName(
                        "net.community.chest.gitcloud.facade.backend.git:name=BackendRepositoryResolver"));
                if (mbeanInfo != null) {
                    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " detected loop: " + mbeanInfo.getClassName() + "["
                            + mbeanInfo.getDescription() + "]");
                    loopDetected = true;
                }
            } catch (JMException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " failed " + e.getClass().getSimpleName()
                            + " to detect loop: " + e.getMessage());
                }
            }
        }
    }

    ResolvedRepositoryData repoData = resolveTargetRepository(method, req);
    if (repoData == null) {
        throw ExtendedLogUtils.thrownLogging(logger, Level.WARNING,
                "serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]",
                new NoSuchElementException("Failed to resolve repository"));
    }

    String username = authenticate(req);
    // TODO check if the user is allowed to access the repository via the resolve operation (push/pull) if at all (e.g., private repo)
    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "] user="
            + username);

    /*
     * NOTE: this feature requires enabling cross-context forwarding.
     * In Tomcat, the 'crossContext' attribute in 'Context' element of
     * 'TOMCAT_HOME\conf\context.xml' must be set to true, to enable cross-context 
     */
    if (loopDetected) {
        // TODO see if can find a more efficient way than splitting and re-constructing
        URI uri = repoData.getRepoLocation();
        ServletContext curContext = req.getServletContext();
        String urlPath = uri.getPath(), urlQuery = uri.getQuery();
        String[] comps = StringUtils.split(urlPath, '/');
        String appName = comps[0];
        ServletContext loopContext = Validate.notNull(curContext.getContext("/" + appName),
                "No cross-context for %s", appName);
        // build the relative path in the re-directed context
        StringBuilder sb = new StringBuilder(
                urlPath.length() + 1 + (StringUtils.isEmpty(urlQuery) ? 0 : urlQuery.length()));
        for (int index = 1; index < comps.length; index++) {
            sb.append('/').append(comps[index]);
        }
        if (!StringUtils.isEmpty(urlQuery)) {
            sb.append('?').append(urlQuery);
        }

        String redirectPath = sb.toString();
        RequestDispatcher dispatcher = Validate.notNull(loopContext.getRequestDispatcher(redirectPath),
                "No dispatcher for %s", redirectPath);
        dispatcher.forward(req, rsp);
        if (logger.isDebugEnabled()) {
            logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString()
                    + "]" + " forwarded to " + loopContext.getContextPath() + "/" + redirectPath);
        }
    } else {
        executeRemoteRequest(method, repoData.getRepoLocation(), req, rsp);
    }
}

From source file:org.apache.hadoop.hdfsproxy.ProxyForwardServlet.java

/** {@inheritDoc} */
@Override/*  w ww .  j  av a  2 s.c  o m*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String hostname = request.getServerName();

    String version = configuration.get(hostname);
    if (version == null) {
        // extract from hostname directly
        String[] strs = hostname.split("[-\\.]");
        version = "/" + strs[0];
    }

    ServletContext curContext = getServletContext();
    ServletContext dstContext = curContext.getContext(version);

    // avoid infinite forwarding.
    if (dstContext == null || "HDFS Proxy Forward".equals(dstContext.getServletContextName())) {
        LOG.error("Context (" + version + ".war) non-exist or restricted from access");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    LOG.debug("Request to " + hostname + " is forwarded to version " + version);
    forwardRequest(request, response, dstContext, request.getServletPath());

}

From source file:org.apache.nifi.web.ContentViewerController.java

/**
 * Gets the content and defers to registered viewers to generate the markup.
 *
 * @param request servlet request// w w  w  .  jav  a2  s  .c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // specify the charset in a response header
    response.addHeader("Content-Type", "text/html; charset=UTF-8");

    // get the content
    final ServletContext servletContext = request.getServletContext();
    final ContentAccess contentAccess = (ContentAccess) servletContext.getAttribute("nifi-content-access");

    final ContentRequestContext contentRequest;
    try {
        contentRequest = getContentRequest(request);
    } catch (final Exception e) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Unable to interpret content request.");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    if (contentRequest.getDataUri() == null) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "The data reference must be specified.");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // get the content
    final DownloadableContent downloadableContent;
    try {
        downloadableContent = contentAccess.getContent(contentRequest);
    } catch (final ResourceNotFoundException rnfe) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Unable to find the specified content");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    } catch (final AccessDeniedException ade) {
        request.setAttribute("title", "Access Denied");
        request.setAttribute("messages",
                "Unable to approve access to the specified content: " + ade.getMessage());

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    } catch (final Exception e) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "An unexpected error has occurred: " + e.getMessage());

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // determine how we want to view the data
    String mode = request.getParameter("mode");

    // if the name isn't set, use original
    if (mode == null) {
        mode = DisplayMode.Original.name();
    }

    // determine the display mode
    final DisplayMode displayMode;
    try {
        displayMode = DisplayMode.valueOf(mode);
    } catch (final IllegalArgumentException iae) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Invalid display mode: " + mode);

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // buffer the content to support resetting in case we need to detect the content type or char encoding
    try (final BufferedInputStream bis = new BufferedInputStream(downloadableContent.getContent());) {
        final String mimeType;
        final String normalizedMimeType;

        // when standalone and we don't know the type is null as we were able to directly access the content bypassing the rest endpoint,
        // when clustered and we don't know the type set to octet stream since the content was retrieved from the node's rest endpoint
        if (downloadableContent.getType() == null || StringUtils
                .startsWithIgnoreCase(downloadableContent.getType(), MediaType.OCTET_STREAM.toString())) {
            // attempt to detect the content stream if we don't know what it is ()
            final DefaultDetector detector = new DefaultDetector();

            // create the stream for tika to process, buffered to support reseting
            final TikaInputStream tikaStream = TikaInputStream.get(bis);

            // provide a hint based on the filename
            final Metadata metadata = new Metadata();
            metadata.set(Metadata.RESOURCE_NAME_KEY, downloadableContent.getFilename());

            // Get mime type
            final MediaType mediatype = detector.detect(tikaStream, metadata);
            mimeType = mediatype.toString();
        } else {
            mimeType = downloadableContent.getType();
        }

        // Extract only mime type and subtype from content type (anything after the first ; are parameters)
        // Lowercase so subsequent code does not need to implement case insensitivity
        normalizedMimeType = mimeType.split(";", 2)[0].toLowerCase();

        // add attributes needed for the header
        request.setAttribute("filename", downloadableContent.getFilename());
        request.setAttribute("contentType", mimeType);

        // generate the header
        request.getRequestDispatcher("/WEB-INF/jsp/header.jsp").include(request, response);

        // remove the attributes needed for the header
        request.removeAttribute("filename");
        request.removeAttribute("contentType");

        // generate the markup for the content based on the display mode
        if (DisplayMode.Hex.equals(displayMode)) {
            final byte[] buffer = new byte[BUFFER_LENGTH];
            final int read = StreamUtils.fillBuffer(bis, buffer, false);

            // trim the byte array if necessary
            byte[] bytes = buffer;
            if (read != buffer.length) {
                bytes = new byte[read];
                System.arraycopy(buffer, 0, bytes, 0, read);
            }

            // convert bytes into the base 64 bytes
            final String base64 = Base64.encodeBase64String(bytes);

            // defer to the jsp
            request.setAttribute("content", base64);
            request.getRequestDispatcher("/WEB-INF/jsp/hexview.jsp").include(request, response);
        } else {
            // lookup a viewer for the content
            final String contentViewerUri = servletContext.getInitParameter(normalizedMimeType);

            // handle no viewer for content type
            if (contentViewerUri == null) {
                request.getRequestDispatcher("/WEB-INF/jsp/no-viewer.jsp").include(request, response);
            } else {
                // create a request attribute for accessing the content
                request.setAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE, new ViewableContent() {
                    @Override
                    public InputStream getContentStream() {
                        return bis;
                    }

                    @Override
                    public String getContent() throws IOException {
                        // detect the charset
                        final CharsetDetector detector = new CharsetDetector();
                        detector.setText(bis);
                        detector.enableInputFilter(true);
                        final CharsetMatch match = detector.detect();

                        // ensure we were able to detect the charset
                        if (match == null) {
                            throw new IOException("Unable to detect character encoding.");
                        }

                        // convert the stream using the detected charset
                        return IOUtils.toString(bis, match.getName());
                    }

                    @Override
                    public ViewableContent.DisplayMode getDisplayMode() {
                        return displayMode;
                    }

                    @Override
                    public String getFileName() {
                        return downloadableContent.getFilename();
                    }

                    @Override
                    public String getContentType() {
                        return normalizedMimeType;
                    }

                    @Override
                    public String getRawContentType() {
                        return mimeType;
                    }
                });

                try {
                    // generate the content
                    final ServletContext viewerContext = servletContext.getContext(contentViewerUri);
                    viewerContext.getRequestDispatcher("/view-content").include(request, response);
                } catch (final Exception e) {
                    String message = e.getMessage() != null ? e.getMessage() : e.toString();
                    message = "Unable to generate view of data: " + message;

                    // log the error
                    logger.error(message);
                    if (logger.isDebugEnabled()) {
                        logger.error(StringUtils.EMPTY, e);
                    }

                    // populate the request attributes
                    request.setAttribute("title", "Error");
                    request.setAttribute("messages", message);

                    // forward to the error page
                    final ServletContext viewerContext = servletContext.getContext("/nifi");
                    viewerContext.getRequestDispatcher("/message").forward(request, response);
                    return;
                }

                // remove the request attribute
                request.removeAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE);
            }
        }

        // generate footer
        request.getRequestDispatcher("/WEB-INF/jsp/footer.jsp").include(request, response);
    }
}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.java

@Override
protected DecoratorSelector initDecoratorSelector(SiteMeshWebAppContext webAppContext) {
    // TODO: Remove heavy coupling on horrible SM2 Factory
    final Factory factory = Factory.getInstance(new Config(filterConfig));
    factory.refresh();/*from   w w  w  .  ja  v a  2  s . com*/
    return new DecoratorMapper2DecoratorSelector(factory.getDecoratorMapper()) {
        @Override
        public Decorator selectDecorator(Content content, SiteMeshContext context) {
            SiteMeshWebAppContext webAppContext = (SiteMeshWebAppContext) context;
            final com.opensymphony.module.sitemesh.Decorator decorator = factory.getDecoratorMapper()
                    .getDecorator(webAppContext.getRequest(), content2htmlPage(content));
            if (decorator == null || decorator.getPage() == null) {
                return new GrailsNoDecorator();
            } else {
                return new OldDecorator2NewDecorator(decorator) {
                    @Override
                    protected void render(Content content, HttpServletRequest request,
                            HttpServletResponse response, ServletContext servletContext,
                            SiteMeshWebAppContext webAppContext) throws IOException, ServletException {

                        HTMLPage htmlPage = content2htmlPage(content);
                        request.setAttribute(PAGE, htmlPage);

                        // see if the URI path (webapp) is set
                        if (decorator.getURIPath() != null) {
                            // in a security conscious environment, the servlet container
                            // may return null for a given URL
                            if (servletContext.getContext(decorator.getURIPath()) != null) {
                                servletContext = servletContext.getContext(decorator.getURIPath());
                            }
                        }
                        // get the dispatcher for the decorator
                        RequestDispatcher dispatcher = servletContext.getRequestDispatcher(decorator.getPage());
                        if (response.isCommitted()) {
                            dispatcher.include(request, response);
                        } else {
                            dispatcher.forward(request, response);
                        }

                        request.removeAttribute(PAGE);
                    }

                };
            }
        }
    };
}

From source file:org.echocat.nodoodle.server.BaseUrlsDiscovery.java

public boolean isAvailable(URL url) {
    if (url == null) {
        throw new NullPointerException("The url is not defined.");
    }/*from w  w  w  .j  av  a 2s.c  o m*/
    final ServletContext servletContext = _servletContext;
    if (servletContext == null) {
        throw new IllegalStateException("The init() method was not yet called.");
    }
    if (CollectionUtils.isEmpty(_baseUrls)) {
        throw new IllegalArgumentException("No baseUrls property set.");
    }
    boolean baseUrlFound = false;
    final Iterator<URL> i = _baseUrls.iterator();
    while (i.hasNext() && !baseUrlFound) {
        final URL baseUrl = i.next();
        baseUrlFound = url.toExternalForm().startsWith(baseUrl.toExternalForm());
    }
    final boolean result;
    if (baseUrlFound) {
        final String uriPath = url.getPath();
        final ServletContext servletContextForUrl = servletContext.getContext(uriPath);
        result = servletContext.equals(servletContextForUrl);
    } else {
        result = false;
    }
    return result;
}

From source file:org.iterx.miru.support.servlet.dispatcher.context.BootstrapServletContextListener.java

private static String resolveContextPath(ServletContext servletContext) {
    String path;/*from www .  ja  v a  2 s  . com*/
    int next;

    path = ((URI.create(servletContext.getRealPath("/"))).getPath()).toLowerCase();
    next = path.length() - 1;
    while (servletContext.getContext(path.substring(next)) != servletContext) {
        next = path.lastIndexOf('/', next - 1);
    }
    return path.substring(next);
}

From source file:org.orbeon.oxf.servlet.ServletExternalContext.java

public RequestDispatcher getRequestDispatcher(String path, boolean isContextRelative) {

    final ServletContext servletContext = (ServletContext) webAppContext.getNativeContext();

    if (isContextRelative) {
        // Path is relative to the current context root
        final ServletContext slashServletContext = servletContext.getContext("/");
        return new ServletToExternalContextRequestDispatcherWrapper(servletContext.getRequestDispatcher(path),
                slashServletContext == servletContext);
    } else {//from w w w  .j a  va2 s  .  c  om
        // Path is relative to the server document root

        final ServletContext otherServletContext = servletContext.getContext(path);
        if (otherServletContext == null)
            return null;

        final ServletContext slashServletContext = servletContext.getContext("/");

        final String modifiedPath;
        final boolean isDefaultContext;
        if (slashServletContext != otherServletContext) {
            // Remove first path element
            modifiedPath = NetUtils.removeFirstPathElement(path);
            if (modifiedPath == null)
                return null;
            isDefaultContext = false;
        } else {
            // No need to remove first path element because the servlet context is ""
            modifiedPath = path;
            isDefaultContext = true;
        }

        return new ServletToExternalContextRequestDispatcherWrapper(
                otherServletContext.getRequestDispatcher(modifiedPath), isDefaultContext);
    }
}