/// <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).(); }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest request, HttpServletResponse response ) { response.SetContentType("text/html"); PrintWriter @out = response.GetWriter(); @out.Write("hello world"); @out.Close(); }
/// <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 )); }
/// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest req, HttpServletResponse resp) { resp.SetContentType("application/json; charset=UTF-8"); StartupProgress prog = NameNodeHttpServer.GetStartupProgressFromContext(GetServletContext ()); StartupProgressView view = prog.CreateView(); JsonGenerator json = new JsonFactory().CreateJsonGenerator(resp.GetWriter()); try { json.WriteStartObject(); json.WriteNumberField(ElapsedTime, view.GetElapsedTime()); json.WriteNumberField(PercentComplete, view.GetPercentComplete()); json.WriteArrayFieldStart(Phases); foreach (Phase phase in view.GetPhases()) { json.WriteStartObject(); json.WriteStringField(Name, phase.GetName()); json.WriteStringField(Desc, phase.GetDescription()); json.WriteStringField(Status, view.GetStatus(phase).ToString()); json.WriteNumberField(PercentComplete, view.GetPercentComplete(phase)); json.WriteNumberField(ElapsedTime, view.GetElapsedTime(phase)); WriteStringFieldIfNotNull(json, File, view.GetFile(phase)); WriteNumberFieldIfDefined(json, Size, view.GetSize(phase)); json.WriteArrayFieldStart(Steps); foreach (Step step in view.GetSteps(phase)) { json.WriteStartObject(); StepType type = step.GetType(); if (type != null) { json.WriteStringField(Name, type.GetName()); json.WriteStringField(Desc, type.GetDescription()); } json.WriteNumberField(Count, view.GetCount(phase, step)); WriteStringFieldIfNotNull(json, File, step.GetFile()); WriteNumberFieldIfDefined(json, Size, step.GetSize()); json.WriteNumberField(Total, view.GetTotal(phase, step)); json.WriteNumberField(PercentComplete, view.GetPercentComplete(phase, step)); json.WriteNumberField(ElapsedTime, view.GetElapsedTime(phase, step)); json.WriteEndObject(); } json.WriteEndArray(); json.WriteEndObject(); } json.WriteEndArray(); json.WriteEndObject(); } finally { IOUtils.Cleanup(Log, json); } }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest req, HttpServletResponse resp) { Log.Info("GET"); resp.SetContentType("text/html"); PrintWriter @out = resp.GetWriter(); Reconfigurable reconf = GetReconfigurable(req); string nodeName = reconf.GetType().GetCanonicalName(); PrintHeader(@out, nodeName); PrintConf(@out, reconf); PrintFooter(@out); }
/// <summary>Warn the user that the link may not be safe!</summary> /// <param name="resp">the http response</param> /// <param name="link">the link to point to</param> /// <param name="user">the user that owns the link.</param> /// <exception cref="System.IO.IOException">on any error.</exception> private static void WarnUserPage(HttpServletResponse resp, string link, string user , ApplicationId id) { //Set the cookie when we warn which overrides the query parameter //This is so that if a user passes in the approved query parameter without //having first visited this page then this page will still be displayed resp.AddCookie(MakeCheckCookie(id, false)); resp.SetContentType(MimeType.Html); WebAppProxyServlet.Page p = new WebAppProxyServlet.Page(resp.GetWriter()); p.Html().H1("WARNING: The following page may not be safe!").H3().("click ").A(link , "here").(" to continue to an Application Master web interface owned by ", user ).().(); }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest request, HttpServletResponse response ) { if (!HttpServer2.IsInstrumentationAccessAllowed(GetServletContext(), request, response )) { return; } string format = request.GetParameter(FormatParam); if (null == format) { format = FormatXml; } if (FormatXml.Equals(format)) { response.SetContentType("text/xml; charset=utf-8"); } else { if (FormatJson.Equals(format)) { response.SetContentType("application/json; charset=utf-8"); } } TextWriter @out = response.GetWriter(); try { WriteResponse(GetConfFromContext(), @out, format); } catch (ConfServlet.BadFormatException bfe) { response.SendError(HttpServletResponse.ScBadRequest, bfe.Message); } @out.Close(); }
/// <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(); }
/// <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(); }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoPost(HttpServletRequest req, HttpServletResponse resp) { Log.Info("POST"); resp.SetContentType("text/html"); PrintWriter @out = resp.GetWriter(); Reconfigurable reconf = GetReconfigurable(req); string nodeName = reconf.GetType().GetCanonicalName(); PrintHeader(@out, nodeName); try { ApplyChanges(@out, reconf, req); } catch (ReconfigurationException e) { resp.SendError(HttpServletResponse.ScInternalServerError, StringUtils.StringifyException (e)); return; } @out.WriteLine("<p><a href=\"" + req.GetServletPath() + "\">back</a></p>"); PrintFooter(@out); }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest request, HttpServletResponse response ) { if (!HttpServer2.IsInstrumentationAccessAllowed(GetServletContext(), request, response )) { return; } string format = request.GetParameter("format"); ICollection <MetricsContext> allContexts = ContextFactory.GetFactory().GetAllContexts (); if ("json".Equals(format)) { response.SetContentType("application/json; charset=utf-8"); PrintWriter @out = response.GetWriter(); try { // Uses Jetty's built-in JSON support to convert the map into JSON. @out.Write(new JSON().ToJSON(MakeMap(allContexts))); } finally { @out.Close(); } } else { PrintWriter @out = response.GetWriter(); try { PrintMap(@out, MakeMap(allContexts)); } finally { @out.Close(); } } }
/// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest request, HttpServletResponse response ) { response.SetContentType("text/plain"); DataNode datanode = (DataNode)GetServletContext().GetAttribute("datanode"); BlockScanner blockScanner = datanode.GetBlockScanner(); StringBuilder buffer = new StringBuilder(8 * 1024); if (!blockScanner.IsEnabled()) { Log.Warn("Periodic block scanner is not running"); buffer.Append("Periodic block scanner is not running. " + "Please check the datanode log if this is unexpected." ); } else { buffer.Append("Block Scanner Statistics\n\n"); blockScanner.PrintStats(buffer); } string resp = buffer.ToString(); Log.Trace("Returned Servlet info {}", resp); response.GetWriter().Write(resp); }
/// <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); }
private void Init() { //clear content type response.SetContentType(null); }
public virtual Response ToResponse(Exception e) { if (Log.IsTraceEnabled()) { Log.Trace("GOT EXCEPITION", e); } // Don't catch this as filter forward on 404 // (ServletContainer.FEATURE_FILTER_FORWARD_ON_404) // won't work and the web UI won't work! if (e is NotFoundException) { return(((NotFoundException)e).GetResponse()); } // clear content type response.SetContentType(null); // Convert exception if (e is RemoteException) { e = ((RemoteException)e).UnwrapRemoteException(); } // Map response status Response.Status s; if (e is SecurityException) { s = Response.Status.Unauthorized; } else { if (e is AuthorizationException) { s = Response.Status.Unauthorized; } else { if (e is FileNotFoundException) { s = Response.Status.NotFound; } else { if (e is NotFoundException) { s = Response.Status.NotFound; } else { if (e is IOException) { s = Response.Status.NotFound; } else { if (e is ForbiddenException) { s = Response.Status.Forbidden; } else { if (e is NotSupportedException) { s = Response.Status.BadRequest; } else { if (e is ArgumentException) { s = Response.Status.BadRequest; } else { if (e is FormatException) { s = Response.Status.BadRequest; } else { if (e is BadRequestException) { s = Response.Status.BadRequest; } else { if (e is WebApplicationException && e.InnerException is UnmarshalException) { s = Response.Status.BadRequest; } else { Log.Warn("INTERNAL_SERVER_ERROR", e); s = Response.Status.InternalServerError; } } } } } } } } } } } // let jaxb handle marshalling data out in the same format requested RemoteExceptionData exception = new RemoteExceptionData(e.GetType().Name, e.Message , e.GetType().FullName); return(Response.Status(s).Entity(exception).Build()); }
protected internal virtual void Init(HttpServletResponse response) { // clear content type response.SetContentType(null); }
private void Init(HttpServletResponse response) { response.SetContentType(null); }
public virtual Response ToResponse(Exception e) { if (Log.IsTraceEnabled()) { Log.Trace("GOT EXCEPITION", e); } //clear content type response.SetContentType(null); //Convert exception if (e is ParamException) { ParamException paramexception = (ParamException)e; e = new ArgumentException("Invalid value for webhdfs parameter \"" + paramexception .GetParameterName() + "\": " + e.InnerException.Message, e); } if (e is ContainerException) { e = ToCause(e); } if (e is RemoteException) { e = ((RemoteException)e).UnwrapRemoteException(); } if (e is SecurityException) { e = ToCause(e); } //Map response status Response.Status s; if (e is SecurityException) { s = Response.Status.Forbidden; } else { if (e is AuthorizationException) { s = Response.Status.Forbidden; } else { if (e is FileNotFoundException) { s = Response.Status.NotFound; } else { if (e is IOException) { s = Response.Status.Forbidden; } else { if (e is NotSupportedException) { s = Response.Status.BadRequest; } else { if (e is ArgumentException) { s = Response.Status.BadRequest; } else { Log.Warn("INTERNAL_SERVER_ERROR", e); s = Response.Status.InternalServerError; } } } } } } string js = JsonUtil.ToJsonString(e); return(Response.Status(s).Type(MediaType.ApplicationJson).Entity(js).Build()); }
/// <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(); } } }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest request, HttpServletResponse response ) { string path = ServletUtil.GetDecodedPath(request, "/streamFile"); string rawPath = ServletUtil.GetRawPath(request, "/streamFile"); string filename = JspHelper.ValidatePath(path); string rawFilename = JspHelper.ValidatePath(rawPath); if (filename == null) { response.SetContentType("text/plain"); PrintWriter @out = response.GetWriter(); @out.Write("Invalid input"); return; } Enumeration <string> reqRanges = request.GetHeaders("Range"); if (reqRanges != null && !reqRanges.MoveNext()) { reqRanges = null; } DFSClient dfs; try { dfs = GetDFSClient(request); } catch (Exception e) { response.SendError(400, e.Message); return; } HdfsDataInputStream @in = null; OutputStream out_1 = null; try { @in = dfs.CreateWrappedInputStream(dfs.Open(filename)); out_1 = response.GetOutputStream(); long fileLen = @in.GetVisibleLength(); if (reqRanges != null) { IList <InclusiveByteRange> ranges = InclusiveByteRange.SatisfiableRanges(reqRanges , fileLen); StreamFile.SendPartialData(@in, out_1, response, fileLen, ranges); } else { // No ranges, so send entire file response.SetHeader("Content-Disposition", "attachment; filename=\"" + rawFilename + "\""); response.SetContentType("application/octet-stream"); response.SetHeader(ContentLength, string.Empty + fileLen); StreamFile.CopyFromOffset(@in, out_1, 0L, fileLen); } @in.Close(); @in = null; out_1.Close(); out_1 = null; dfs.Close(); dfs = null; } catch (IOException ioe) { if (Log.IsDebugEnabled()) { Log.Debug("response.isCommitted()=" + response.IsCommitted(), ioe); } throw; } finally { IOUtils.Cleanup(Log, @in); IOUtils.Cleanup(Log, out_1); IOUtils.Cleanup(Log, dfs); } }