示例#1
0
 /// <exception cref="System.IO.IOException"/>
 /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException
 ///     "/>
 public override AuthenticationToken Authenticate(HttpServletRequest request, HttpServletResponse
                                                  response)
 {
     response.SetStatus(HttpServletResponse.ScUnauthorized);
     response.SetHeader(KerberosAuthenticator.WwwAuthenticate, "mock");
     return(null);
 }
示例#2
0
        /// <summary>Authenticates an HTTP client request.</summary>
        /// <remarks>
        /// Authenticates an HTTP client request.
        /// <p>
        /// It extracts the
        /// <see cref="Org.Apache.Hadoop.Security.Authentication.Client.PseudoAuthenticator.UserName
        ///     "/>
        /// parameter from the query string and creates
        /// an
        /// <see cref="AuthenticationToken"/>
        /// with it.
        /// <p>
        /// If the HTTP client request does not contain the
        /// <see cref="Org.Apache.Hadoop.Security.Authentication.Client.PseudoAuthenticator.UserName
        ///     "/>
        /// parameter and
        /// the handler is configured to allow anonymous users it returns the
        /// <see cref="AuthenticationToken.Anonymous"/>
        /// token.
        /// <p>
        /// If the HTTP client request does not contain the
        /// <see cref="Org.Apache.Hadoop.Security.Authentication.Client.PseudoAuthenticator.UserName
        ///     "/>
        /// parameter and
        /// the handler is configured to disallow anonymous users it throws an
        /// <see cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException
        ///     "/>
        /// .
        /// </remarks>
        /// <param name="request">the HTTP client request.</param>
        /// <param name="response">the HTTP client response.</param>
        /// <returns>an authentication token if the HTTP client request is accepted and credentials are valid.
        ///     </returns>
        /// <exception cref="System.IO.IOException">thrown if an IO error occurred.</exception>
        /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException
        ///     ">thrown if HTTP client request was not accepted as an authentication request.</exception>
        public override AuthenticationToken Authenticate(HttpServletRequest request, HttpServletResponse
                                                         response)
        {
            AuthenticationToken token;
            string userName = GetUserName(request);

            if (userName == null)
            {
                if (GetAcceptAnonymous())
                {
                    token = AuthenticationToken.Anonymous;
                }
                else
                {
                    response.SetStatus(HttpServletResponse.ScForbidden);
                    response.SetHeader(WwwAuthenticate, PseudoAuth);
                    token = null;
                }
            }
            else
            {
                token = new AuthenticationToken(userName, userName, GetType());
            }
            return(token);
        }
 /// <exception cref="Javax.Servlet.ServletException"/>
 /// <exception cref="System.IO.IOException"/>
 protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                               )
 {
     Assert.Equal(63 * 1024, request.GetHeader("longheader").Length
                  );
     response.SetStatus(HttpServletResponse.ScOk);
 }
示例#4
0
 /// <summary>Output 404 with appropriate message.</summary>
 /// <param name="resp">the http response.</param>
 /// <param name="message">the message to include on the page.</param>
 /// <exception cref="System.IO.IOException">on any error.</exception>
 public static void NotFound(HttpServletResponse resp, string message)
 {
     resp.SetStatus(HttpServletResponse.ScNotFound);
     resp.SetContentType(MimeType.Html);
     ProxyUtils.Page p = new ProxyUtils.Page(resp.GetWriter());
     p.Html().H1(message).();
 }
示例#5
0
            /// <exception cref="Javax.Servlet.ServletException"/>
            /// <exception cref="System.IO.IOException"/>
            protected override void DoGet(HttpServletRequest req, HttpServletResponse res)
            {
                string queryString = req.GetQueryString();

                switch (counter)
                {
                case 0:
                {
                    VerifyQuery(queryString, "SUCCEEDED");
                    break;
                }

                case 2:
                {
                    VerifyQuery(queryString, "KILLED");
                    break;
                }

                case 4:
                {
                    VerifyQuery(queryString, "FAILED");
                    break;
                }
                }
                if (counter % 2 == 0)
                {
                    res.SendError(HttpServletResponse.ScBadRequest, "forcing error");
                }
                else
                {
                    res.SetStatus(HttpServletResponse.ScOk);
                }
                counter++;
            }
示例#6
0
            /// <exception cref="Javax.Servlet.ServletException"/>
            /// <exception cref="System.IO.IOException"/>
            protected override void DoPost(HttpServletRequest req, HttpServletResponse resp)
            {
                TextWriter writer = resp.GetWriter();

                writer.Write("ping: ");
                IOUtils.Copy(req.GetReader(), writer);
                resp.SetStatus(HttpServletResponse.ScOk);
            }
示例#7
0
            /// <exception cref="Javax.Servlet.ServletException"/>
            /// <exception cref="System.IO.IOException"/>
            protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
            {
                UserGroupInformation ugi = HttpUserGroupInformation.Get();

                if (ugi != null)
                {
                    string ret = "remoteuser="******":ugi=" + ugi.GetShortUserName
                                     ();
                    if (ugi.GetAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.Proxy)
                    {
                        ret = "realugi=" + ugi.GetRealUser().GetShortUserName() + ":" + ret;
                    }
                    resp.SetStatus(HttpServletResponse.ScOk);
                    resp.GetWriter().Write(ret);
                }
                else
                {
                    resp.SetStatus(HttpServletResponse.ScInternalServerError);
                }
            }
示例#8
0
 /// <summary>Send a partial content response with the given range.</summary>
 /// <remarks>
 /// Send a partial content response with the given range. If there are
 /// no satisfiable ranges, or if multiple ranges are requested, which
 /// is unsupported, respond with range not satisfiable.
 /// </remarks>
 /// <param name="in">stream to read from</param>
 /// <param name="out">stream to write to</param>
 /// <param name="response">http response to use</param>
 /// <param name="contentLength">for the response header</param>
 /// <param name="ranges">to write to respond with</param>
 /// <exception cref="System.IO.IOException">on error sending the response</exception>
 internal static void SendPartialData(FSDataInputStream @in, OutputStream @out, HttpServletResponse
                                      response, long contentLength, IList <InclusiveByteRange> ranges)
 {
     if (ranges == null || ranges.Count != 1)
     {
         response.SetContentLength(0);
         response.SetStatus(HttpServletResponse.ScRequestedRangeNotSatisfiable);
         response.SetHeader("Content-Range", InclusiveByteRange.To416HeaderRangeString(contentLength
                                                                                       ));
     }
     else
     {
         InclusiveByteRange singleSatisfiableRange = ranges[0];
         long singleLength = singleSatisfiableRange.GetSize(contentLength);
         response.SetStatus(HttpServletResponse.ScPartialContent);
         response.SetHeader("Content-Range", singleSatisfiableRange.ToHeaderRangeString(contentLength
                                                                                        ));
         CopyFromOffset(@in, @out, singleSatisfiableRange.GetFirst(contentLength), singleLength
                        );
     }
 }
示例#9
0
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
        {
            resp.SetContentType("text/plain");
            resp.SetStatus(HttpServletResponse.ScOk);
            string user      = req.GetRemoteUser();
            string principal = (req.GetUserPrincipal() != null) ? req.GetUserPrincipal().GetName
                                   () : null;
            TextWriter writer = resp.GetWriter();

            writer.Write(MessageFormat.Format("You are: user[{0}] principal[{1}]\n", user, principal
                                              ));
        }
示例#10
0
 /// <exception cref="Javax.Servlet.ServletException"/>
 /// <exception cref="System.IO.IOException"/>
 protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
 {
     resp.SetStatus(HttpServletResponse.ScOk);
     resp.GetWriter().Write("ping");
     if (req.GetHeader(DelegationTokenAuthenticator.DelegationTokenHeader) != null)
     {
         resp.SetHeader("UsingHeader", "true");
     }
     if (req.GetQueryString() != null && req.GetQueryString().Contains(DelegationTokenAuthenticator
                                                                       .DelegationParam + "="))
     {
         resp.SetHeader("UsingQueryString", "true");
     }
 }
示例#11
0
            /// <exception cref="Javax.Servlet.ServletException"/>
            /// <exception cref="System.IO.IOException"/>
            protected override void DoPost(HttpServletRequest req, HttpServletResponse resp)
            {
                InputStream  @is = req.GetInputStream();
                OutputStream os  = resp.GetOutputStream();
                int          c   = @is.Read();

                while (c > -1)
                {
                    os.Write(c);
                    c = @is.Read();
                }
                @is.Close();
                os.Close();
                resp.SetStatus(HttpServletResponse.ScOk);
            }
示例#12
0
        public static void RedirectToErrorPage(HttpServletResponse res, Exception e, string
                                               path, bool devMode)
        {
            string st = devMode ? ErrorPage.ToStackTrace(e, 1024 * 3) : "See logs for stack trace";

            // spec: min 4KB
            res.SetStatus(res.ScFound);
            Cookie cookie = new Cookie(StatusCookie, 500.ToString());

            cookie.SetPath(path);
            res.AddCookie(cookie);
            cookie = new Cookie(ErrorCookie, st);
            cookie.SetPath(path);
            res.AddCookie(cookie);
            res.SetHeader("Location", path);
        }
        /// <summary>
        /// It enforces the the Kerberos SPNEGO authentication sequence returning an
        /// <see cref="AuthenticationToken"/>
        /// only
        /// after the Kerberos SPNEGO sequence has completed successfully.
        /// </summary>
        /// <param name="request">the HTTP client request.</param>
        /// <param name="response">the HTTP client response.</param>
        /// <returns>
        /// an authentication token if the Kerberos SPNEGO sequence is complete and valid,
        /// <code>null</code> if it is in progress (in this case the handler handles the response to the client).
        /// </returns>
        /// <exception cref="System.IO.IOException">thrown if an IO error occurred.</exception>
        /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException
        ///     ">thrown if Kerberos SPNEGO sequence failed.</exception>
        public override AuthenticationToken Authenticate(HttpServletRequest request, HttpServletResponse
                                                         response)
        {
            AuthenticationToken token = null;
            string authorization      = request.GetHeader(KerberosAuthenticator.Authorization);

            if (authorization == null || !authorization.StartsWith(KerberosAuthenticator.Negotiate
                                                                   ))
            {
                response.SetHeader(WwwAuthenticate, KerberosAuthenticator.Negotiate);
                response.SetStatus(HttpServletResponse.ScUnauthorized);
                if (authorization == null)
                {
                    Log.Trace("SPNEGO starting");
                }
                else
                {
                    Log.Warn("'" + KerberosAuthenticator.Authorization + "' does not start with '" +
                             KerberosAuthenticator.Negotiate + "' :  {}", authorization);
                }
            }
            else
            {
                authorization = Runtime.Substring(authorization, KerberosAuthenticator.Negotiate
                                                  .Length).Trim();
                Base64 base64      = new Base64(0);
                byte[] clientToken = base64.Decode(authorization);
                string serverName  = request.GetServerName();
                try
                {
                    token = Subject.DoAs(serverSubject, new _PrivilegedExceptionAction_347(this, serverName
                                                                                           , clientToken, base64, response));
                }
                catch (PrivilegedActionException ex)
                {
                    if (ex.GetException() is IOException)
                    {
                        throw (IOException)ex.GetException();
                    }
                    else
                    {
                        throw new AuthenticationException(ex.GetException());
                    }
                }
            }
            return(token);
        }
示例#14
0
            /// <exception cref="System.IO.IOException"/>
            /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException
            ///     "/>
            public override AuthenticationToken Authenticate(HttpServletRequest request, HttpServletResponse
                                                             response)
            {
                AuthenticationToken token = null;

                if (request.GetParameter("authenticated") != null)
                {
                    token = new AuthenticationToken(request.GetParameter("authenticated"), "U", "test"
                                                    );
                }
                else
                {
                    response.SetStatus(HttpServletResponse.ScUnauthorized);
                    response.SetHeader(KerberosAuthenticator.WwwAuthenticate, "dummy");
                }
                return(token);
            }
示例#15
0
        /// <summary>Creates a HTTP servlet response serializing the exception in it as JSON.
        ///     </summary>
        /// <param name="response">the servlet response</param>
        /// <param name="status">the error code to set in the response</param>
        /// <param name="ex">the exception to serialize in the response</param>
        /// <exception cref="System.IO.IOException">
        /// thrown if there was an error while creating the
        /// response
        /// </exception>
        public static void CreateServletExceptionResponse(HttpServletResponse response, int
                                                          status, Exception ex)
        {
            response.SetStatus(status);
            response.SetContentType(ApplicationJsonMime);
            IDictionary <string, object> json = new LinkedHashMap <string, object>();

            json[ErrorMessageJson]   = GetOneLineMessage(ex);
            json[ErrorExceptionJson] = ex.GetType().Name;
            json[ErrorClassnameJson] = ex.GetType().FullName;
            IDictionary <string, object> jsonResponse = new LinkedHashMap <string, object>();

            jsonResponse[ErrorJson] = json;
            ObjectMapper jsonMapper = new ObjectMapper();
            TextWriter   writer     = response.GetWriter();

            jsonMapper.WriterWithDefaultPrettyPrinter().WriteValue(writer, jsonResponse);
            writer.Flush();
        }
示例#16
0
        /// <summary>
        /// Handle redirects with a status code that can in future support verbs other
        /// than GET, thus supporting full REST functionality.
        /// </summary>
        /// <remarks>
        /// Handle redirects with a status code that can in future support verbs other
        /// than GET, thus supporting full REST functionality.
        /// <p>
        /// The target URL is included in the redirect text returned
        /// <p>
        /// At the end of this method, the output stream is closed.
        /// </remarks>
        /// <param name="request">
        /// request (hence: the verb and any other information
        /// relevant to a redirect)
        /// </param>
        /// <param name="response">the response</param>
        /// <param name="target">the target URL -unencoded</param>
        /// <exception cref="System.IO.IOException"/>
        public static void SendRedirect(HttpServletRequest request, HttpServletResponse response
                                        , string target)
        {
            if (Log.IsDebugEnabled())
            {
                Log.Debug("Redirecting {} {} to {}", request.GetMethod(), request.GetRequestURI()
                          , target);
            }
            string location = response.EncodeRedirectURL(target);

            response.SetStatus(HttpServletResponse.ScFound);
            response.SetHeader(Location, location);
            response.SetContentType(MimeType.Html);
            PrintWriter writer = response.GetWriter();

            ProxyUtils.Page p = new ProxyUtils.Page(writer);
            p.Html().Head().Title("Moved").().Body().H1("Moved").Div().("Content has moved ")
            .A(location, "here").().().();
            writer.Close();
        }
示例#17
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException
        ///     "/>
        public override bool ManagementOperation(AuthenticationToken token, HttpServletRequest
                                                 request, HttpServletResponse response)
        {
            bool   requestContinues = true;
            string op = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator
                                                  .OpParam);

            op = (op != null) ? StringUtils.ToUpperCase(op) : null;
            if (DelegationTokenOps.Contains(op) && !request.GetMethod().Equals("OPTIONS"))
            {
                DelegationTokenAuthenticator.DelegationTokenOperation dtOp = DelegationTokenAuthenticator.DelegationTokenOperation
                                                                             .ValueOf(op);
                if (dtOp.GetHttpMethod().Equals(request.GetMethod()))
                {
                    bool doManagement;
                    if (dtOp.RequiresKerberosCredentials() && token == null)
                    {
                        token = Authenticate(request, response);
                        if (token == null)
                        {
                            requestContinues = false;
                            doManagement     = false;
                        }
                        else
                        {
                            doManagement = true;
                        }
                    }
                    else
                    {
                        doManagement = true;
                    }
                    if (doManagement)
                    {
                        UserGroupInformation requestUgi = (token != null) ? UserGroupInformation.CreateRemoteUser
                                                              (token.GetUserName()) : null;
                        // Create the proxy user if doAsUser exists
                        string doAsUser = DelegationTokenAuthenticationFilter.GetDoAs(request);
                        if (requestUgi != null && doAsUser != null)
                        {
                            requestUgi = UserGroupInformation.CreateProxyUser(doAsUser, requestUgi);
                            try
                            {
                                ProxyUsers.Authorize(requestUgi, request.GetRemoteHost());
                            }
                            catch (AuthorizationException ex)
                            {
                                HttpExceptionUtils.CreateServletExceptionResponse(response, HttpServletResponse.ScForbidden
                                                                                  , ex);
                                return(false);
                            }
                        }
                        IDictionary map = null;
                        switch (dtOp)
                        {
                        case DelegationTokenAuthenticator.DelegationTokenOperation.Getdelegationtoken:
                        {
                            if (requestUgi == null)
                            {
                                throw new InvalidOperationException("request UGI cannot be NULL");
                            }
                            string renewer = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator
                                                                       .RenewerParam);
                            try
                            {
                                Org.Apache.Hadoop.Security.Token.Token <object> dToken = tokenManager.CreateToken(
                                    requestUgi, renewer);
                                map = DelegationTokenToJSON(dToken);
                            }
                            catch (IOException ex)
                            {
                                throw new AuthenticationException(ex.ToString(), ex);
                            }
                            break;
                        }

                        case DelegationTokenAuthenticator.DelegationTokenOperation.Renewdelegationtoken:
                        {
                            if (requestUgi == null)
                            {
                                throw new InvalidOperationException("request UGI cannot be NULL");
                            }
                            string tokenToRenew = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator
                                                                            .TokenParam);
                            if (tokenToRenew == null)
                            {
                                response.SendError(HttpServletResponse.ScBadRequest, MessageFormat.Format("Operation [{0}] requires the parameter [{1}]"
                                                                                                          , dtOp, KerberosDelegationTokenAuthenticator.TokenParam));
                                requestContinues = false;
                            }
                            else
                            {
                                Org.Apache.Hadoop.Security.Token.Token <AbstractDelegationTokenIdentifier> dt = new
                                                                                                                Org.Apache.Hadoop.Security.Token.Token();
                                try
                                {
                                    dt.DecodeFromUrlString(tokenToRenew);
                                    long expirationTime = tokenManager.RenewToken(dt, requestUgi.GetShortUserName());
                                    map         = new Hashtable();
                                    map["long"] = expirationTime;
                                }
                                catch (IOException ex)
                                {
                                    throw new AuthenticationException(ex.ToString(), ex);
                                }
                            }
                            break;
                        }

                        case DelegationTokenAuthenticator.DelegationTokenOperation.Canceldelegationtoken:
                        {
                            string tokenToCancel = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator
                                                                             .TokenParam);
                            if (tokenToCancel == null)
                            {
                                response.SendError(HttpServletResponse.ScBadRequest, MessageFormat.Format("Operation [{0}] requires the parameter [{1}]"
                                                                                                          , dtOp, KerberosDelegationTokenAuthenticator.TokenParam));
                                requestContinues = false;
                            }
                            else
                            {
                                Org.Apache.Hadoop.Security.Token.Token <AbstractDelegationTokenIdentifier> dt = new
                                                                                                                Org.Apache.Hadoop.Security.Token.Token();
                                try
                                {
                                    dt.DecodeFromUrlString(tokenToCancel);
                                    tokenManager.CancelToken(dt, (requestUgi != null) ? requestUgi.GetShortUserName()
                                                                                         : null);
                                }
                                catch (IOException)
                                {
                                    response.SendError(HttpServletResponse.ScNotFound, "Invalid delegation token, cannot cancel"
                                                       );
                                    requestContinues = false;
                                }
                            }
                            break;
                        }
                        }
                        if (requestContinues)
                        {
                            response.SetStatus(HttpServletResponse.ScOk);
                            if (map != null)
                            {
                                response.SetContentType(MediaType.ApplicationJson);
                                TextWriter   writer     = response.GetWriter();
                                ObjectMapper jsonMapper = new ObjectMapper();
                                jsonMapper.WriteValue(writer, map);
                                writer.Write(Enter);
                                writer.Flush();
                            }
                            requestContinues = false;
                        }
                    }
                }
                else
                {
                    response.SendError(HttpServletResponse.ScBadRequest, MessageFormat.Format("Wrong HTTP method [{0}] for operation [{1}], it should be "
                                                                                              + "[{2}]", request.GetMethod(), dtOp, dtOp.GetHttpMethod()));
                    requestContinues = false;
                }
            }
            return(requestContinues);
        }
示例#18
0
        // --------------------------------------------------------- Private Methods
        /// <exception cref="System.IO.IOException"/>
        private void ListBeans(JsonGenerator jg, ObjectName qry, string attribute, HttpServletResponse
                               response)
        {
            Log.Debug("Listing beans for " + qry);
            ICollection <ObjectName> names = null;

            names = mBeanServer.QueryNames(qry, null);
            jg.WriteArrayFieldStart("beans");
            IEnumerator <ObjectName> it = names.GetEnumerator();

            while (it.HasNext())
            {
                ObjectName oname = it.Next();
                MBeanInfo  minfo;
                string     code          = string.Empty;
                object     attributeinfo = null;
                try
                {
                    minfo = mBeanServer.GetMBeanInfo(oname);
                    code  = minfo.GetClassName();
                    string prs = string.Empty;
                    try
                    {
                        if ("org.apache.commons.modeler.BaseModelMBean".Equals(code))
                        {
                            prs  = "modelerType";
                            code = (string)mBeanServer.GetAttribute(oname, prs);
                        }
                        if (attribute != null)
                        {
                            prs           = attribute;
                            attributeinfo = mBeanServer.GetAttribute(oname, prs);
                        }
                    }
                    catch (AttributeNotFoundException e)
                    {
                        // If the modelerType attribute was not found, the class name is used
                        // instead.
                        Log.Error("getting attribute " + prs + " of " + oname + " threw an exception", e);
                    }
                    catch (MBeanException e)
                    {
                        // The code inside the attribute getter threw an exception so log it,
                        // and fall back on the class name
                        Log.Error("getting attribute " + prs + " of " + oname + " threw an exception", e);
                    }
                    catch (RuntimeException e)
                    {
                        // For some reason even with an MBeanException available to them
                        // Runtime exceptionscan still find their way through, so treat them
                        // the same as MBeanException
                        Log.Error("getting attribute " + prs + " of " + oname + " threw an exception", e);
                    }
                    catch (ReflectionException e)
                    {
                        // This happens when the code inside the JMX bean (setter?? from the
                        // java docs) threw an exception, so log it and fall back on the
                        // class name
                        Log.Error("getting attribute " + prs + " of " + oname + " threw an exception", e);
                    }
                }
                catch (InstanceNotFoundException)
                {
                    //Ignored for some reason the bean was not found so don't output it
                    continue;
                }
                catch (IntrospectionException e)
                {
                    // This is an internal error, something odd happened with reflection so
                    // log it and don't output the bean.
                    Log.Error("Problem while trying to process JMX query: " + qry + " with MBean " +
                              oname, e);
                    continue;
                }
                catch (ReflectionException e)
                {
                    // This happens when the code inside the JMX bean threw an exception, so
                    // log it and don't output the bean.
                    Log.Error("Problem while trying to process JMX query: " + qry + " with MBean " +
                              oname, e);
                    continue;
                }
                jg.WriteStartObject();
                jg.WriteStringField("name", oname.ToString());
                jg.WriteStringField("modelerType", code);
                if ((attribute != null) && (attributeinfo == null))
                {
                    jg.WriteStringField("result", "ERROR");
                    jg.WriteStringField("message", "No attribute with name " + attribute + " was found."
                                        );
                    jg.WriteEndObject();
                    jg.WriteEndArray();
                    jg.Close();
                    response.SetStatus(HttpServletResponse.ScNotFound);
                    return;
                }
                if (attribute != null)
                {
                    WriteAttribute(jg, attribute, attributeinfo);
                }
                else
                {
                    MBeanAttributeInfo[] attrs = minfo.GetAttributes();
                    for (int i = 0; i < attrs.Length; i++)
                    {
                        WriteAttribute(jg, oname, attrs[i]);
                    }
                }
                jg.WriteEndObject();
            }
            jg.WriteEndArray();
        }
示例#19
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);
            }
        }
示例#20
0
 /// <exception cref="Javax.Servlet.ServletException"/>
 /// <exception cref="System.IO.IOException"/>
 protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
 {
     resp.SetStatus(HttpServletResponse.ScOk);
 }
示例#21
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Javax.Servlet.ServletException"/>
        public override void DoFilter(HttpServletRequest request, HttpServletResponse response
                                      , FilterChain chain)
        {
            response.SetCharacterEncoding("UTF-8");
            string uri = HtmlQuoting.QuoteHtmlChars(request.GetRequestURI());

            if (uri == null)
            {
                uri = "/";
            }
            RMWebApp rmWebApp = injector.GetInstance <RMWebApp>();

            rmWebApp.CheckIfStandbyRM();
            if (rmWebApp.IsStandby() && ShouldRedirect(rmWebApp, uri))
            {
                string redirectPath = rmWebApp.GetRedirectPath();
                if (redirectPath != null && !redirectPath.IsEmpty())
                {
                    redirectPath += uri;
                    string      redirectMsg = "This is standby RM. The redirect url is: " + redirectPath;
                    PrintWriter @out        = response.GetWriter();
                    @out.WriteLine(redirectMsg);
                    response.SetHeader("Location", redirectPath);
                    response.SetStatus(HttpServletResponse.ScTemporaryRedirect);
                    return;
                }
                else
                {
                    bool   doRetry          = true;
                    string retryIntervalStr = request.GetParameter(YarnWebParams.NextRefreshInterval);
                    int    retryInterval    = 0;
                    if (retryIntervalStr != null)
                    {
                        try
                        {
                            retryInterval = System.Convert.ToInt32(retryIntervalStr.Trim());
                        }
                        catch (FormatException)
                        {
                            doRetry = false;
                        }
                    }
                    int    next        = CalculateExponentialTime(retryInterval);
                    string redirectUrl = AppendOrReplaceParamter(path + uri, YarnWebParams.NextRefreshInterval
                                                                 + "=" + (retryInterval + 1));
                    if (redirectUrl == null || next > MaxSleepTime)
                    {
                        doRetry = false;
                    }
                    string redirectMsg = doRetry ? "Can not find any active RM. Will retry in next "
                                         + next + " seconds." : "There is no active RM right now.";
                    redirectMsg += "\nHA Zookeeper Connection State: " + rmWebApp.GetHAZookeeperConnectionState
                                       ();
                    PrintWriter @out = response.GetWriter();
                    @out.WriteLine(redirectMsg);
                    if (doRetry)
                    {
                        response.SetHeader("Refresh", next + ";url=" + redirectUrl);
                        response.SetStatus(HttpServletResponse.ScTemporaryRedirect);
                    }
                }
                return;
            }
            base.DoFilter(request, response, chain);
        }
示例#22
0
 /// <summary>
 /// The default behavior of this method is to call SetStatus(int sc, string sm)
 /// on the wrapped response object.
 /// </summary>
 /// <param name="sc"></param>
 /// <param name="sm"></param>
 public void SetStatus(int sc, string sm)
 {
     HttpServletResponse.SetStatus(sc, sm);
 }
示例#23
0
        /// <summary>Download link and have it be the response.</summary>
        /// <param name="req">the http request</param>
        /// <param name="resp">the http response</param>
        /// <param name="link">the link to download</param>
        /// <param name="c">the cookie to set if any</param>
        /// <exception cref="System.IO.IOException">on any error.</exception>
        private static void ProxyLink(HttpServletRequest req, HttpServletResponse resp, URI
                                      link, Cookie c, string proxyHost)
        {
            DefaultHttpClient client = new DefaultHttpClient();

            client.GetParams().SetParameter(ClientPNames.CookiePolicy, CookiePolicy.BrowserCompatibility
                                            ).SetBooleanParameter(ClientPNames.AllowCircularRedirects, true);
            // Make sure we send the request from the proxy address in the config
            // since that is what the AM filter checks against. IP aliasing or
            // similar could cause issues otherwise.
            IPAddress localAddress = Sharpen.Extensions.GetAddressByName(proxyHost);

            if (Log.IsDebugEnabled())
            {
                Log.Debug("local InetAddress for proxy host: {}", localAddress);
            }
            client.GetParams().SetParameter(ConnRoutePNames.LocalAddress, localAddress);
            HttpGet httpGet            = new HttpGet(link);
            Enumeration <string> names = req.GetHeaderNames();

            while (names.MoveNext())
            {
                string name = names.Current;
                if (passThroughHeaders.Contains(name))
                {
                    string value = req.GetHeader(name);
                    if (Log.IsDebugEnabled())
                    {
                        Log.Debug("REQ HEADER: {} : {}", name, value);
                    }
                    httpGet.SetHeader(name, value);
                }
            }
            string user = req.GetRemoteUser();

            if (user != null && !user.IsEmpty())
            {
                httpGet.SetHeader("Cookie", ProxyUserCookieName + "=" + URLEncoder.Encode(user, "ASCII"
                                                                                          ));
            }
            OutputStream @out = resp.GetOutputStream();

            try
            {
                HttpResponse httpResp = client.Execute(httpGet);
                resp.SetStatus(httpResp.GetStatusLine().GetStatusCode());
                foreach (Header header in httpResp.GetAllHeaders())
                {
                    resp.SetHeader(header.GetName(), header.GetValue());
                }
                if (c != null)
                {
                    resp.AddCookie(c);
                }
                InputStream @in = httpResp.GetEntity().GetContent();
                if (@in != null)
                {
                    IOUtils.CopyBytes(@in, @out, 4096, true);
                }
            }
            finally
            {
                httpGet.ReleaseConnection();
            }
        }
示例#24
0
 /// <exception cref="Javax.Servlet.ServletException"/>
 /// <exception cref="System.IO.IOException"/>
 protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
 {
     resp.SetStatus(HttpServletResponse.ScOk);
     resp.GetWriter().Write(req.GetUserPrincipal().GetName());
 }
示例#25
0
        /// <summary>Process a GET request for the specified resource.</summary>
        /// <param name="request">The servlet request we are processing</param>
        /// <param name="response">The servlet response we are creating</param>
        protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                                      )
        {
            string      jsonpcb = null;
            PrintWriter writer  = null;

            try
            {
                if (!IsInstrumentationAccessAllowed(request, response))
                {
                    return;
                }
                JsonGenerator jg = null;
                try
                {
                    writer = response.GetWriter();
                    response.SetContentType("application/json; charset=utf8");
                    response.SetHeader(AccessControlAllowMethods, "GET");
                    response.SetHeader(AccessControlAllowOrigin, "*");
                    JsonFactory jsonFactory = new JsonFactory();
                    jg = jsonFactory.CreateJsonGenerator(writer);
                    jg.Disable(JsonGenerator.Feature.AutoCloseTarget);
                    jg.UseDefaultPrettyPrinter();
                    jg.WriteStartObject();
                    if (mBeanServer == null)
                    {
                        jg.WriteStringField("result", "ERROR");
                        jg.WriteStringField("message", "No MBeanServer could be found");
                        jg.Close();
                        Log.Error("No MBeanServer could be found.");
                        response.SetStatus(HttpServletResponse.ScNotFound);
                        return;
                    }
                    // query per mbean attribute
                    string getmethod = request.GetParameter("get");
                    if (getmethod != null)
                    {
                        string[] splitStrings = getmethod.Split("\\:\\:");
                        if (splitStrings.Length != 2)
                        {
                            jg.WriteStringField("result", "ERROR");
                            jg.WriteStringField("message", "query format is not as expected.");
                            jg.Close();
                            response.SetStatus(HttpServletResponse.ScBadRequest);
                            return;
                        }
                        ListBeans(jg, new ObjectName(splitStrings[0]), splitStrings[1], response);
                        jg.Close();
                        return;
                    }
                    // query per mbean
                    string qry = request.GetParameter("qry");
                    if (qry == null)
                    {
                        qry = "*:*";
                    }
                    ListBeans(jg, new ObjectName(qry), null, response);
                }
                finally
                {
                    if (jg != null)
                    {
                        jg.Close();
                    }
                    if (writer != null)
                    {
                        writer.Close();
                    }
                }
            }
            catch (IOException e)
            {
                Log.Error("Caught an exception while processing JMX request", e);
                response.SetStatus(HttpServletResponse.ScInternalServerError);
            }
            catch (MalformedObjectNameException e)
            {
                Log.Error("Caught an exception while processing JMX request", e);
                response.SetStatus(HttpServletResponse.ScBadRequest);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
示例#26
0
 public virtual void SetStatus(int status)
 {
     this.status = status;
     response.SetStatus(status);
 }