コード例 #1
0
        public virtual void Mdc()
        {
            HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>();

            Org.Mockito.Mockito.When(request.GetUserPrincipal()).ThenReturn(null);
            Org.Mockito.Mockito.When(request.GetMethod()).ThenReturn("METHOD");
            Org.Mockito.Mockito.When(request.GetPathInfo()).ThenReturn("/pathinfo");
            ServletResponse response = Org.Mockito.Mockito.Mock <ServletResponse>();
            AtomicBoolean   invoked  = new AtomicBoolean();
            FilterChain     chain    = new _FilterChain_55(invoked);

            MDC.Clear();
            Filter filter = new MDCFilter();

            filter.Init(null);
            filter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.IsTrue(invoked.Get());
            NUnit.Framework.Assert.IsNull(MDC.Get("hostname"));
            NUnit.Framework.Assert.IsNull(MDC.Get("user"));
            NUnit.Framework.Assert.IsNull(MDC.Get("method"));
            NUnit.Framework.Assert.IsNull(MDC.Get("path"));
            Org.Mockito.Mockito.When(request.GetUserPrincipal()).ThenReturn(new _Principal_78
                                                                                ());
            invoked.Set(false);
            chain = new _FilterChain_86(invoked);
            filter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.IsTrue(invoked.Get());
            HostnameFilter.HostnameTl.Set("HOST");
            invoked.Set(false);
            chain = new _FilterChain_103(invoked);
            filter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.IsTrue(invoked.Get());
            HostnameFilter.HostnameTl.Remove();
            filter.Destroy();
        }
コード例 #2
0
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void Service(HttpServletRequest req, HttpServletResponse res)
        {
            res.SetCharacterEncoding("UTF-8");
            string uri = HtmlQuoting.QuoteHtmlChars(req.GetRequestURI());

            if (uri == null)
            {
                uri = "/";
            }
            if (devMode && uri.Equals("/__stop"))
            {
                // quick hack to restart servers in dev mode without OS commands
                res.SetStatus(res.ScNoContent);
                Log.Info("dev mode restart requested");
                PrepareToExit();
                return;
            }
            // if they provide a redirectPath go there instead of going to
            // "/" so that filters can differentiate the webapps.
            if (uri.Equals("/"))
            {
                string redirectPath = webApp.GetRedirectPath();
                if (redirectPath != null && !redirectPath.IsEmpty())
                {
                    res.SendRedirect(redirectPath);
                    return;
                }
            }
            string method = req.GetMethod();

            if (method.Equals("OPTIONS"))
            {
                DoOptions(req, res);
                return;
            }
            if (method.Equals("TRACE"))
            {
                DoTrace(req, res);
                return;
            }
            if (method.Equals("HEAD"))
            {
                DoGet(req, res);
                // default to bad request
                return;
            }
            string pathInfo = req.GetPathInfo();

            if (pathInfo == null)
            {
                pathInfo = "/";
            }
            Controller.RequestContext rc = injector.GetInstance <Controller.RequestContext>();
            if (SetCookieParams(rc, req) > 0)
            {
                Cookie ec = rc.Cookies()[ErrorCookie];
                if (ec != null)
                {
                    rc.SetStatus(System.Convert.ToInt32(rc.Cookies()[StatusCookie].GetValue()));
                    RemoveErrorCookies(res, uri);
                    rc.Set(Params.ErrorDetails, ec.GetValue());
                    Render(typeof(ErrorPage));
                    return;
                }
            }
            rc.prefix = webApp.Name();
            Router.Dest dest = null;
            try
            {
                dest = router.Resolve(method, pathInfo);
            }
            catch (WebAppException e)
            {
                rc.error = e;
                if (!e.Message.Contains("not found"))
                {
                    rc.SetStatus(res.ScInternalServerError);
                    Render(typeof(ErrorPage));
                    return;
                }
            }
            if (dest == null)
            {
                rc.SetStatus(res.ScNotFound);
                Render(typeof(ErrorPage));
                return;
            }
            rc.devMode = devMode;
            SetMoreParams(rc, pathInfo, dest);
            Controller controller = injector.GetInstance(dest.controllerClass);

            try
            {
                // TODO: support args converted from /path/:arg1/...
                dest.action.Invoke(controller, (object[])null);
                if (!rc.rendered)
                {
                    if (dest.defaultViewClass != null)
                    {
                        Render(dest.defaultViewClass);
                    }
                    else
                    {
                        if (rc.status == 200)
                        {
                            throw new InvalidOperationException("No view rendered for 200");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("error handling URI: " + uri, e);
                // Page could be half rendered (but still not flushed). So redirect.
                RedirectToErrorPage(res, e, uri, devMode);
            }
        }
コード例 #3
0
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                string   userApprovedParamS = req.GetParameter(ProxyUriUtils.ProxyApprovalParam);
                bool     userWasWarned      = false;
                bool     userApproved       = Sharpen.Extensions.ValueOf(userApprovedParamS);
                bool     securityEnabled    = IsSecurityEnabled();
                string   remoteUser         = req.GetRemoteUser();
                string   pathInfo           = req.GetPathInfo();
                string[] parts = pathInfo.Split("/", 3);
                if (parts.Length < 2)
                {
                    Log.Warn("{} gave an invalid proxy path {}", remoteUser, pathInfo);
                    NotFound(resp, "Your path appears to be formatted incorrectly.");
                    return;
                }
                //parts[0] is empty because path info always starts with a /
                string        appId = parts[1];
                string        rest  = parts.Length > 2 ? parts[2] : string.Empty;
                ApplicationId id    = Apps.ToAppID(appId);
                if (id == null)
                {
                    Log.Warn("{} attempting to access {} that is invalid", remoteUser, appId);
                    NotFound(resp, appId + " appears to be formatted incorrectly.");
                    return;
                }
                if (securityEnabled)
                {
                    string   cookieName = GetCheckCookieName(id);
                    Cookie[] cookies    = req.GetCookies();
                    if (cookies != null)
                    {
                        foreach (Cookie c in cookies)
                        {
                            if (cookieName.Equals(c.GetName()))
                            {
                                userWasWarned = true;
                                userApproved  = userApproved || Sharpen.Extensions.ValueOf(c.GetValue());
                                break;
                            }
                        }
                    }
                }
                bool checkUser = securityEnabled && (!userWasWarned || !userApproved);
                AppReportFetcher.FetchedAppReport fetchedAppReport = null;
                ApplicationReport applicationReport = null;
                try
                {
                    fetchedAppReport = GetApplicationReport(id);
                    if (fetchedAppReport != null)
                    {
                        if (fetchedAppReport.GetAppReportSource() != AppReportFetcher.AppReportSource.Rm &&
                            fetchedAppReport.GetAppReportSource() != AppReportFetcher.AppReportSource.Ahs)
                        {
                            throw new NotSupportedException("Application report not " + "fetched from RM or history server."
                                                            );
                        }
                        applicationReport = fetchedAppReport.GetApplicationReport();
                    }
                }
                catch (ApplicationNotFoundException)
                {
                    applicationReport = null;
                }
                if (applicationReport == null)
                {
                    Log.Warn("{} attempting to access {} that was not found", remoteUser, id);
                    URI toFetch = ProxyUriUtils.GetUriFromTrackingPlugins(id, this.trackingUriPlugins
                                                                          );
                    if (toFetch != null)
                    {
                        ProxyUtils.SendRedirect(req, resp, toFetch.ToString());
                        return;
                    }
                    NotFound(resp, "Application " + appId + " could not be found " + "in RM or history server"
                             );
                    return;
                }
                string original = applicationReport.GetOriginalTrackingUrl();
                URI    trackingUri;
                if (original == null || original.Equals("N/A") || original.Equals(string.Empty))
                {
                    if (fetchedAppReport.GetAppReportSource() == AppReportFetcher.AppReportSource.Rm)
                    {
                        // fallback to ResourceManager's app page if no tracking URI provided
                        // and Application Report was fetched from RM
                        Log.Debug("Original tracking url is '{}'. Redirecting to RM app page", original ==
                                  null ? "NULL" : original);
                        ProxyUtils.SendRedirect(req, resp, StringHelper.Pjoin(rmAppPageUrlBase, id.ToString
                                                                                  ()));
                    }
                    else
                    {
                        if (fetchedAppReport.GetAppReportSource() == AppReportFetcher.AppReportSource.Ahs)
                        {
                            // fallback to Application History Server app page if the application
                            // report was fetched from AHS
                            Log.Debug("Original tracking url is '{}'. Redirecting to AHS app page", original
                                      == null ? "NULL" : original);
                            ProxyUtils.SendRedirect(req, resp, StringHelper.Pjoin(ahsAppPageUrlBase, id.ToString
                                                                                      ()));
                        }
                    }
                    return;
                }
                else
                {
                    if (ProxyUriUtils.GetSchemeFromUrl(original).IsEmpty())
                    {
                        trackingUri = ProxyUriUtils.GetUriFromAMUrl(WebAppUtils.GetHttpSchemePrefix(conf)
                                                                    , original);
                    }
                    else
                    {
                        trackingUri = new URI(original);
                    }
                }
                string runningUser = applicationReport.GetUser();
                if (checkUser && !runningUser.Equals(remoteUser))
                {
                    Log.Info("Asking {} if they want to connect to the " + "app master GUI of {} owned by {}"
                             , remoteUser, appId, runningUser);
                    WarnUserPage(resp, ProxyUriUtils.GetPathAndQuery(id, rest, req.GetQueryString(),
                                                                     true), runningUser, id);
                    return;
                }
                // Append the user-provided path and query parameter to the original
                // tracking url.
                IList <NameValuePair> queryPairs = URLEncodedUtils.Parse(req.GetQueryString(), null
                                                                         );
                UriBuilder builder = UriBuilder.FromUri(trackingUri);
                foreach (NameValuePair pair in queryPairs)
                {
                    builder.QueryParam(pair.GetName(), pair.GetValue());
                }
                URI toFetch_1 = builder.Path(rest).Build();
                Log.Info("{} is accessing unchecked {}" + " which is the app master GUI of {} owned by {}"
                         , remoteUser, toFetch_1, appId, runningUser);
                switch (applicationReport.GetYarnApplicationState())
                {
                case YarnApplicationState.Killed:
                case YarnApplicationState.Finished:
                case YarnApplicationState.Failed:
                {
                    ProxyUtils.SendRedirect(req, resp, toFetch_1.ToString());
                    return;
                }

                default:
                {
                    break;
                }
                }
                // fall out of the switch
                Cookie c_1 = null;
                if (userWasWarned && userApproved)
                {
                    c_1 = MakeCheckCookie(id, true);
                }
                ProxyLink(req, resp, toFetch_1, c_1, GetProxyHost());
            }
            catch (Exception e)
            {
                throw new IOException(e);
            }
        }