// http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control // http://board.flashkit.com/board/showthread.php?t=782484 // http://www.adobe.com/devnet/flashplayer/articles/fplayer9_security_02.html protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.setContentType("text/x-cross-domain-policy"); Console.WriteLine(UrlPattern); resp.getWriter().print(@" <?xml version=""1.0""?> <!DOCTYPE cross-domain-policy SYSTEM ""http://www.adobe.com/xml/dtds/cross-domain-policy.dtd""> <cross-domain-policy> <site-control permitted-cross-domain-policies=""all""/> <allow-access-from domain=""*"" secure=""false""/> <allow-http-request-headers-from domain=""*"" headers=""*"" secure=""false""/> </cross-domain-policy> ".Trim()); resp.getWriter().flush(); } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object)ex).printStackTrace(); } }
protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { var PathAndQuery = req.GetPathAndQuery().Substring(UrlPattern.Length); // not allowed to do so: // http://groups.google.com/group/google-appengine/browse_thread/thread/68a480cb7bec869e // http://www.ozelwebtasarim.com/index.php/google/10004-google-app-engine-java-utf-8-character-encoding-problem //resp.setHeader("Content-Encoding", "utf-8"); if (PathAndQuery.Length > 1) { resp.setContentType("text/html; charset=utf-8"); resp.getWriter().println(Launch(PathAndQuery.Substring(1))); } else { resp.setContentType("text/html; charset=utf-8"); resp.getWriter().println(Launch(null)); } } catch { // either swallow of throw a runtime exception } }
// http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control // http://board.flashkit.com/board/showthread.php?t=782484 protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { var p = req.GetPathAndQuery(); if (p.Length > UrlPattern.Length + 1) p = p.Substring(UrlPattern.Length + 1); else p = ""; if ("zip" == p) { resp.setContentType(ZIPFile.ContentType); resp.getOutputStream().write((sbyte[])(object)GetContent()); resp.getOutputStream().flush(); } else { resp.setContentType("text/html"); resp.getWriter().println(Launch(p)); resp.getWriter().flush(); } } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object)ex).printStackTrace(); } }
protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { var Path = req.getServletPath(); var Query = req.getQueryString(); var PathAndQuery = Path; if (Query != null) PathAndQuery += "?" + Query; if (PathAndQuery != "/") { //resp.setContentType("text/html"); //resp.getWriter().println( resp.sendRedirect( GetTinEyeVersion(GetPosterLink(PathAndQuery)) //.ToImage() ); } else { resp.setContentType("text/html"); resp.getWriter().println(Launch(PathAndQuery)); } } catch { // either swallow of throw a runtime exception } }
override protected void service(HttpServletRequest req, HttpServletResponse resp) { string servletPath = ServletIncludeUtils.getServletPath(req); TextWriter writer = (TextWriter)ServletIncludeUtils.getTextWriter(req); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(servletPath); HttpServletResponseWrapper wrapper = new AspxResponseWrapper(resp, writer); dispatcher.include(req, wrapper); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void afterCompletion(javax.servlet.http.HttpServletRequest arg0, javax.servlet.http.HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception public override void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, object arg2, Exception arg3) { // 删除 MDC.remove(SESSION_KEY); ThreadContext.removeSessionId(); ThreadContext.clean(); }
public ServletWorkerRequest (HttpServlet servlet, HttpServletRequest req, HttpServletResponse resp) : base (req.getContextPath(), req.getServletPath (), req.getRequestURI ()) { _HttpServlet = servlet; _HttpServletRequest = req; _HttpServletResponse = resp; }
override protected void service(HttpServletRequest req, HttpServletResponse resp) { resp.setHeader("X-Powered-By", "ASP.NET"); resp.setHeader("X-AspNet-Version", "1.1.4322"); String filename = getServletContext().getRealPath(req.getServletPath()); ServletOutputStream hos; try { hos = resp.getOutputStream(); } catch (java.lang.IllegalStateException e) { string mimeType = getServletContext().getMimeType(filename); if (mimeType == null || mimeType.StartsWith("text")) { sendFileUsingWriter(resp, filename); return; } else throw e; } try { string mimeType = this.getServletContext().getMimeType(filename); if (mimeType == null) mimeType = "text/plain"; resp.setContentType(mimeType); FileStream fis = null; try { fis = new FileStream(filename,FileMode.Open,FileAccess.Read); byte[] buf = new byte[4 * 1024]; // 4K buffer int bytesRead; while ((bytesRead = fis.Read(buf,0,buf.Length)) != -1 && bytesRead != 0) { hos.write(TypeUtils.ToSByteArray(buf), 0, bytesRead); } } finally { if (fis != null) fis.Close(); } } catch (System.IO.FileNotFoundException e) { resp.setStatus(404,"Object Not Found."); HttpException myExp = new HttpException (404, "File '" + filename + "' not found."); hos.print(((HttpException) myExp).GetHtmlErrorMessage ()); hos.flush(); } catch(Exception e) { Trace.WriteLine (String.Format ("ERROR in Static File Reading {0},{1}", e.GetType (), e.Message)); resp.setStatus(500); HttpException myExp = new HttpException ("Exception in Reading static file", e); hos.print(((HttpException) myExp).GetHtmlErrorMessage ()); hos.flush(); } }
/// <summary> /// 自定义的全局错误 /// </summary> /// <param name="request"> </param> /// <param name="response"> </param> /// <param name="message"> </param> /// <param name="errorCode"> /// </param> /// <exception cref="IOException"> </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: protected void returnJsonSystemError(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, String message, com.baidu.dsp.common.constant.ErrorCode errorCode) throws java.io.IOException protected internal virtual void returnJsonSystemError(HttpServletRequest request, HttpServletResponse response, string message, ErrorCode errorCode) { JsonObjectBase jsonObjectBase = JsonObjectUtils.buildGlobalError(message, errorCode); response.setHeader("Cache-Control", "no-cache"); response.ContentType = "application/json;charset=UTF-8"; response.CharacterEncoding = "UTF-8"; response.Writer.write(JsonUtils.toJson(jsonObjectBase)); }
private void AddAllowedMethodIfValid(string methodName, HttpServletResponse response) { HttpMethod method = HttpMethod.valueOfOrNull(methodName); if (method != null) { response.addHeader(ACCESS_CONTROL_ALLOW_METHODS, methodName); } else { _log.warn("Unknown HTTP method specified in " + ACCESS_CONTROL_REQUEST_METHOD + " '" + methodName + "'. " + "It will be ignored and not attached to the " + ACCESS_CONTROL_ALLOW_METHODS + " response header"); } }
public override HttpServletResponse Response() { HttpServletResponse result = Org.Mockito.Mockito.Mock <HttpServletResponse>(); try { Org.Mockito.Mockito.When(result.GetWriter()).ThenReturn(new PrintWriter(data)); } catch (IOException) { } return(result); }
/// <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="System.Exception"/> public virtual void TestRequestWithInvalidAuthorization() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetHeader(KerberosAuthenticator.Authorization)). ThenReturn("invalid"); NUnit.Framework.Assert.IsNull(handler.Authenticate(request, response)); Org.Mockito.Mockito.Verify(response).SetHeader(KerberosAuthenticator.WwwAuthenticate , KerberosAuthenticator.Negotiate); Org.Mockito.Mockito.Verify(response).SetStatus(HttpServletResponse.ScUnauthorized ); }
/// <exception cref="System.IO.IOException"/> /// <exception cref="Javax.Servlet.ServletException"/> public virtual void DoFilter(ServletRequest req, ServletResponse res, FilterChain chain) { HttpServletResponse httpRes = (HttpServletResponse)res; httpRes.SetHeader("Cache-Control", "no-cache"); long now = Runtime.CurrentTimeMillis(); httpRes.AddDateHeader("Expires", now); httpRes.AddDateHeader("Date", now); httpRes.AddHeader("Pragma", "no-cache"); chain.DoFilter(req, res); }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest req, HttpServletResponse resp) { lock (this) { try { Sharpen.Runtime.Wait(this, 5000); } catch (Exception) { } } }
// http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control // http://board.flashkit.com/board/showthread.php?t=782484 protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.sendRedirect(ToLocation(req.GetPathAndQuery())); } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object) ex).printStackTrace(); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception public override bool preHandle(HttpServletRequest request, HttpServletResponse response, object handler) { // 初始化会话 ThreadContext.init(); // 放SessionId string token = TokenUtil.generateToken(); MDC.put(SESSION_KEY, token); ThreadContext.putSessionId(token); return true; }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override protected void doPost(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) throws javax.servlet.ServletException, java.io.IOException protected internal override void doPost(HttpServletRequest req, HttpServletResponse resp) { LOG.debug("Resource POST REQUEST ========= " + req.ToString()); echoHeader(req, resp); string uri = sanitise(req.RequestURI); string type = getType(uri); try { string contentType = req.ContentType; if (contentType.Equals("application/octet-stream")) { LOG.debug("Resource POST REQUEST is a file upload"); processFileUpload(req, resp); } else if (contentType.StartsWith("multipart", StringComparison.Ordinal)) { LOG.debug("Resource POST REQUEST is a multipart file upload"); processMultiPart(req, resp); } else { string content = getContent(req.InputStream); if (contentType.Contains("application/x-www-form-urlencoded")) { try { generateResponse(resp, type, noddyKvpToXml(content, "UTF-8")); } catch (Exception) { LOG.warn("the content passed in isn't encoded as application/x-www-form-urlencoded: " + content); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); } } else if (content.Trim().StartsWith("<", StringComparison.Ordinal) || content.Trim().EndsWith("}", StringComparison.Ordinal)) { generateResponse(resp, type, content); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); } } } catch (Exception) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } LOG.debug("Resource POST RESPONSE ========= " + req.ToString()); }
/// <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"); } }
// level editor // - save locally // -- as cookie // -- to google gears // -- to file // - save to the bulldog system // -- description // -- preview // - upload new assets for custom levels (pay extra for storage to avoid spam) protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.sendRedirect(Link); } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object)ex).printStackTrace(); } }
/// <exception cref="System.IO.IOException"/> /// <exception cref="Javax.Servlet.ServletException"/> protected override void DoFilter(FilterChain filterChain, HttpServletRequest request , HttpServletResponse response) { bool requestCompleted = false; UserGroupInformation ugi = null; AuthenticationToken authToken = (AuthenticationToken)request.GetUserPrincipal(); if (authToken != null && authToken != AuthenticationToken.Anonymous) { // if the request was authenticated because of a delegation token, // then we ignore proxyuser (this is the same as the RPC behavior). ugi = (UserGroupInformation)request.GetAttribute(DelegationTokenAuthenticationHandler .DelegationTokenUgiAttribute); if (ugi == null) { string realUser = request.GetUserPrincipal().GetName(); ugi = UserGroupInformation.CreateRemoteUser(realUser, handlerAuthMethod); string doAsUser = GetDoAs(request); if (doAsUser != null) { ugi = UserGroupInformation.CreateProxyUser(doAsUser, ugi); try { ProxyUsers.Authorize(ugi, request.GetRemoteHost()); } catch (AuthorizationException ex) { HttpExceptionUtils.CreateServletExceptionResponse(response, HttpServletResponse.ScForbidden , ex); requestCompleted = true; } } } UgiTl.Set(ugi); } if (!requestCompleted) { UserGroupInformation ugiF = ugi; try { request = new _HttpServletRequestWrapper_269(this, ugiF, request); base.DoFilter(filterChain, request, response); } finally { UgiTl.Remove(); } } }
/// <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); }
// http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control // http://board.flashkit.com/board/showthread.php?t=782484 protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.setContentType("text/html"); resp.getWriter().println(Launch(req.GetPathAndQuery())); resp.getWriter().flush(); } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object) ex).printStackTrace(); } }
/// <exception cref="System.Exception"/> public virtual void TestAlternateAuthenticationAsBrowser() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); // By default, a User-Agent without "java", "curl", "wget", or "perl" in it // is considered a browser Org.Mockito.Mockito.When(request.GetHeader("User-Agent")).ThenReturn("Some Browser" ); AuthenticationToken token = handler.Authenticate(request, response); Assert.Equal("A", token.GetUserName()); Assert.Equal("B", token.GetName()); Assert.Equal(GetExpectedType(), token.GetType()); }
/// <exception cref="System.Exception"/> private void TestInvalidDelegationTokenHeader() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetHeader(Org.Mockito.Mockito.Eq(DelegationTokenAuthenticator .DelegationTokenHeader))).ThenReturn("invalid"); StringWriter writer = new StringWriter(); Org.Mockito.Mockito.When(response.GetWriter()).ThenReturn(new PrintWriter(writer) ); NUnit.Framework.Assert.IsNull(handler.Authenticate(request, response)); Assert.True(writer.ToString().Contains("AuthenticationException" )); }
/// <summary> /// It enforces the the Kerberos SPNEGO authentication sequence returning an /// <see cref="AuthenticationToken"/> /// only after the Kerberos SPNEGO sequence has /// completed successfully (in the case of Java access) and only after the /// custom authentication implemented by the subclass in alternateAuthenticate /// has completed successfully (in the case of browser access). /// </summary> /// <param name="request">the HTTP client request.</param> /// <param name="response">the HTTP client response.</param> /// <returns>an authentication token if the request is authorized or null</returns> /// <exception cref="System.IO.IOException">thrown if an IO error occurred</exception> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// ">thrown if an authentication error occurred</exception> public override AuthenticationToken Authenticate(HttpServletRequest request, HttpServletResponse response) { AuthenticationToken token; if (IsBrowser(request.GetHeader("User-Agent"))) { token = AlternateAuthenticate(request, response); } else { token = base.Authenticate(request, response); } return(token); }
/// <exception cref="System.Exception"/> private void TestInvalidDelegationTokenQueryString() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetQueryString()).ThenReturn(DelegationTokenAuthenticator .DelegationParam + "=invalid"); StringWriter writer = new StringWriter(); Org.Mockito.Mockito.When(response.GetWriter()).ThenReturn(new PrintWriter(writer) ); NUnit.Framework.Assert.IsNull(handler.Authenticate(request, response)); Org.Mockito.Mockito.Verify(response).SetStatus(HttpServletResponse.ScForbidden); Assert.True(writer.ToString().Contains("AuthenticationException" )); }
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); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public void doFilter(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse, javax.servlet.FilterChain filterChain) throws java.io.IOException, javax.servlet.ServletException public override void DoFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) { HttpServletRequest request = ( HttpServletRequest )servletRequest; HttpServletResponse response = ( HttpServletResponse )servletResponse; if (request.ServletPath != null && request.ServletPath.EndsWith(".html")) { response.addHeader("Cache-Control", "private, no-cache, no-store, proxy-revalidate, no-transform"); response.addHeader("Pragma", "no-cache"); response.addHeader("Content-Security-Policy", "frame-ancestors 'none'"); response.addHeader("X-Frame-Options", "DENY"); response.addHeader("X-Content-Type-Options", "nosniff"); response.addHeader("X-XSS-Protection", "1; mode=block"); } filterChain.doFilter(servletRequest, servletResponse); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldPassThroughRequestsWithNullServletPath() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldPassThroughRequestsWithNullServletPath() { // given HttpServletRequest request = mock(typeof(HttpServletRequest)); when(request.ServletPath).thenReturn(null); HttpServletResponse response = mock(typeof(HttpServletResponse)); FilterChain filterChain = mock(typeof(FilterChain)); // when (new StaticContentFilter()).DoFilter(request, response, filterChain); // then verifyZeroInteractions(response); verify(filterChain).doFilter(request, response); }
// http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control // http://board.flashkit.com/board/showthread.php?t=782484 protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.setContentType("text/html"); resp.getWriter().println(Launch(req.GetPathAndQuery())); resp.getWriter().flush(); } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object)ex).printStackTrace(); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws java.io.IOException, ServletException public virtual void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) req; HttpServletRequest request = (HttpServletRequest)req; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) resp; HttpServletResponse response = (HttpServletResponse)resp; if ("GET".Equals(request.Method) && !request.RequestURI.EndsWith("xml")) { response.setHeader("Cache-Control", "no-cache"); } chain.doFilter(req, resp); }
/// <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); }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest req, HttpServletResponse resp) { UserGroupInformation ugi; ServletContext context = GetServletContext(); Configuration conf = NameNodeHttpServer.GetConfFromContext(context); try { ugi = GetUGI(req, conf); } catch (IOException ioe) { Log.Info("Request for token received with no authentication from " + req.GetRemoteAddr (), ioe); resp.SendError(HttpServletResponse.ScForbidden, "Unable to identify or authenticate user" ); return; } NameNode nn = NameNodeHttpServer.GetNameNodeFromContext(context); string tokenString = req.GetParameter(Token); if (tokenString == null) { resp.SendError(HttpServletResponse.ScMultipleChoices, "Token to renew not specified" ); } Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier> token = new Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier>(); token.DecodeFromUrlString(tokenString); try { long result = ugi.DoAs(new _PrivilegedExceptionAction_73(nn, token)); PrintWriter os = new PrintWriter(new OutputStreamWriter(resp.GetOutputStream(), Charsets .Utf8)); os.WriteLine(result); os.Close(); } catch (Exception e) { // transfer exception over the http string exceptionClass = e.GetType().FullName; string exceptionMsg = e.GetLocalizedMessage(); string strException = exceptionClass + ";" + exceptionMsg; Log.Info("Exception while renewing token. Re-throwing. s=" + strException, e); resp.SendError(HttpServletResponse.ScInternalServerError, strException); } }
//Empty /// <exception cref="System.IO.IOException"/> /// <exception cref="Javax.Servlet.ServletException"/> public virtual void DoFilter(ServletRequest req, ServletResponse resp, FilterChain chain) { ProxyUtils.RejectNonHttpRequests(req); HttpServletRequest httpReq = (HttpServletRequest)req; HttpServletResponse httpResp = (HttpServletResponse)resp; if (Log.IsDebugEnabled()) { Log.Debug("Remote address for request is: {}", httpReq.GetRemoteAddr()); } if (!GetProxyAddresses().Contains(httpReq.GetRemoteAddr())) { string redirectUrl = FindRedirectUrl(); string target = redirectUrl + httpReq.GetRequestURI(); ProxyUtils.SendRedirect(httpReq, httpResp, target); return; } string user = null; if (httpReq.GetCookies() != null) { foreach (Cookie c in httpReq.GetCookies()) { if (WebAppProxyServlet.ProxyUserCookieName.Equals(c.GetName())) { user = c.GetValue(); break; } } } if (user == null) { if (Log.IsDebugEnabled()) { Log.Debug("Could not find " + WebAppProxyServlet.ProxyUserCookieName + " cookie, so user will not be set" ); } chain.DoFilter(req, resp); } else { AmIpPrincipal principal = new AmIpPrincipal(user); ServletRequest requestWrapper = new AmIpServletRequestWrapper(httpReq, principal); chain.DoFilter(requestWrapper, resp); } }
// http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control // http://board.flashkit.com/board/showthread.php?t=782484 protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.setContentType(YAMLDocument.ContentType); resp.getWriter().print(GameReferenceExtensions.Default.ToYAML()); resp.getWriter().flush(); } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object) ex).printStackTrace(); } }
public virtual void TestInstances() { Injector injector = WebAppTests.CreateMockInjector(this); HttpServletRequest req = injector.GetInstance <HttpServletRequest>(); HttpServletResponse res = injector.GetInstance <HttpServletResponse>(); string val = req.GetParameter("foo"); PrintWriter @out = res.GetWriter(); @out.WriteLine("Hello world!"); LogInstances(req, res, @out); NUnit.Framework.Assert.AreSame(req, injector.GetInstance <HttpServletRequest>()); NUnit.Framework.Assert.AreSame(res, injector.GetInstance <HttpServletResponse>()); NUnit.Framework.Assert.AreSame(this, injector.GetInstance <TestWebAppTests>()); Org.Mockito.Mockito.Verify(req).GetParameter("foo"); Org.Mockito.Mockito.Verify(res).GetWriter(); Org.Mockito.Mockito.Verify(@out).WriteLine("Hello world!"); }
// http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control // http://board.flashkit.com/board/showthread.php?t=782484 protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.setContentType(ZIPFile.ContentType); resp.getOutputStream().write((sbyte[])(object)GetContent()); resp.getOutputStream().flush(); } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object) ex).printStackTrace(); } }
// http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control // http://board.flashkit.com/board/showthread.php?t=782484 protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.setContentType("application/rss+xml"); resp.getWriter().print(GetContent()); resp.getWriter().flush(); } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object) ex).printStackTrace(); } }
// Servlet that delays requests for a long time /// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest request, HttpServletResponse response ) { bool timedOut = false; calledTimes++; try { // Sleep for a long time Sharpen.Thread.Sleep(1000000); } catch (Exception) { timedOut = true; } NUnit.Framework.Assert.IsTrue("DelayServlet should be interrupted", timedOut); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void processMultiPart(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) throws java.io.IOException private void processMultiPart(HttpServletRequest req, HttpServletResponse resp) { PrintWriter @out = resp.Writer; resp.ContentType = "text/plain"; MultipartParser mp = new MultipartParser(req, 2048); Part part = null; while ((part = mp.readNextPart()) != null) { string name = part.Name.Trim(); if (part.Param) { // it's a parameter part ParamPart paramPart = (ParamPart)part; string value = paramPart.StringValue.Trim(); LOG.info("param; name=" + name + ", value=" + value); @out.print("param; name=" + name + ", value=" + value); } else if (part.File) { // it's a file part FilePart filePart = (FilePart)part; string fileName = filePart.FileName; if (!string.ReferenceEquals(fileName, null)) { // the part actually contained a file // StringWriter sw = new StringWriter(); // long size = filePart.writeTo(new File(System // .getProperty("java.io.tmpdir"))); System.IO.MemoryStream baos = new System.IO.MemoryStream(); long size = filePart.writeTo(baos); LOG.info("file; name=" + name + "; filename=" + fileName + ", filePath=" + filePart.FilePath + ", content type=" + filePart.ContentType + ", size=" + size); @out.print(string.Format("{0}: {1}", name, (StringHelperClass.NewString(baos.toByteArray())).Trim())); } else { // the field did not contain a file LOG.info("file; name=" + name + "; EMPTY"); } @out.flush(); } } resp.Status = HttpServletResponse.SC_OK; }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest req, HttpServletResponse resp) { UserGroupInformation ugi; ServletContext context = GetServletContext(); Configuration conf = NameNodeHttpServer.GetConfFromContext(context); try { ugi = GetUGI(req, conf); } catch (IOException ioe) { Log.Info("Request for token received with no authentication from " + req.GetRemoteAddr (), ioe); resp.SendError(HttpServletResponse.ScForbidden, "Unable to identify or authenticate user" ); return; } Log.Info("Sending token: {" + ugi.GetUserName() + "," + req.GetRemoteAddr() + "}" ); NameNode nn = NameNodeHttpServer.GetNameNodeFromContext(context); string renewer = req.GetParameter(Renewer); string renewerFinal = (renewer == null) ? req.GetUserPrincipal().GetName() : renewer; DataOutputStream dos = null; try { dos = new DataOutputStream(resp.GetOutputStream()); DataOutputStream dosFinal = dos; // for doAs block ugi.DoAs(new _PrivilegedExceptionAction_69(nn, ugi, renewerFinal, dosFinal)); } catch (Exception e) { Log.Info("Exception while sending token. Re-throwing ", e); resp.SendError(HttpServletResponse.ScInternalServerError); } finally { if (dos != null) { dos.Close(); } } }
// http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control // http://board.flashkit.com/board/showthread.php?t=782484 protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.setContentType("application/rss+xml"); resp.getWriter().print(GetContent()); resp.getWriter().flush(); } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object)ex).printStackTrace(); } }
// http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control // http://board.flashkit.com/board/showthread.php?t=782484 protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.setContentType(ZIPFile.ContentType); resp.getOutputStream().write((sbyte[])(object)GetContent()); resp.getOutputStream().flush(); } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object)ex).printStackTrace(); } }
// http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control // http://board.flashkit.com/board/showthread.php?t=782484 protected override void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.setContentType(YAMLDocument.ContentType); resp.getWriter().print(GameReferenceExtensions.Default.ToYAML()); resp.getWriter().flush(); } catch (csharp.ThrowableException ex) { // either swallow of throw a runtime exception ((java.lang.Throwable)(object)ex).printStackTrace(); } }
/// <summary> /// Receives standard HTTP requests from the public /// <code>service</code> method and dispatches /// them to the <code>do</code><i>XXX</i> methods defined in /// this class. /// </summary> protected void service(HttpServletRequest @req, HttpServletResponse @resp) { }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void afterCompletion(javax.servlet.http.HttpServletRequest arg0, javax.servlet.http.HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception public override void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, object arg2, Exception arg3) { }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception public override bool preHandle(HttpServletRequest request, HttpServletResponse response, object handler) { return false; }
void sendFileUsingWriter(HttpServletResponse resp, string filename) { java.io.PrintWriter writer = resp.getWriter(); try { resp.setContentType(this.getServletContext().getMimeType(filename)); StreamReader fis = null; char[] buf = new char[4 * 1024]; // 4K buffer try { fis = new StreamReader(filename); int charsRead; while ((charsRead = fis.Read(buf,0,buf.Length)) != -1 && charsRead != 0) { writer.write(buf, 0, charsRead); } } finally { if (fis != null) fis.Close(); } } catch (System.IO.FileNotFoundException e) { resp.setStatus(404,"Object Not Found."); HttpException myExp = new HttpException (404, "File '" + filename + "' not found."); writer.print(((HttpException) myExp).GetHtmlErrorMessage ()); writer.flush(); } catch(Exception e) { Trace.WriteLine (String.Format ("ERROR in Static File Reading {0},{1}", e.GetType (), e.Message)); resp.setStatus(500); HttpException myExp = new HttpException ("Exception in Reading static file", e); writer.print(((HttpException) myExp).GetHtmlErrorMessage ()); writer.flush(); } }
/// <summary> /// Called by the server (via the <code>service</code> method) /// to allow a servlet to handle a POST request. /// </summary> protected virtual void doPost(HttpServletRequest @req, HttpServletResponse @resp) { }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void postHandle(javax.servlet.http.HttpServletRequest arg0, javax.servlet.http.HttpServletResponse arg1, Object arg2, org.springframework.web.servlet.ModelAndView arg3) throws Exception public override void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, object arg2, ModelAndView arg3) { }
/// <summary> /// Called by the server (via the <code>service</code> method) /// to allow a servlet to handle a OPTIONS request. /// </summary> protected void doOptions(HttpServletRequest @req, HttpServletResponse @resp) { }
override protected void service (HttpServletRequest req, HttpServletResponse resp) { string pathInfo = req.getRequestURI (); string contextPath = req.getContextPath (); if (pathInfo.Equals (contextPath) || ((pathInfo.Length - contextPath.Length) == 1) && pathInfo [pathInfo.Length - 1] == '/' && pathInfo.StartsWith (contextPath)) pathInfo = contextPath + req.getServletPath (); if (pathInfo.EndsWith (".aspx") || pathInfo.EndsWith (".asmx") || pathInfo.EndsWith (".invoke")) { base.service (req, resp); } else { staticServlet.service (req, resp); } }
protected override void service (HttpServletRequest req, HttpServletResponse resp) { const string assemblies = "/assemblies"; const string getping = "getping"; const string setping = "setping"; const string version = "2.2"; string servletPath = req.getServletPath (); if (String.CompareOrdinal (assemblies, 0, servletPath, 0, assemblies.Length) == 0) { if (servletPath.Length == assemblies.Length || servletPath [assemblies.Length] == '/') { string requestURI = req.getRequestURI (); bool getp = requestURI.EndsWith (getping, StringComparison.Ordinal); if (!getp && requestURI.EndsWith (setping, StringComparison.Ordinal)) { getServletContext().setAttribute(getping, version); getp = true; } if (getp) { string ping = (string) getServletContext ().getAttribute (getping); if (ping == null) ping = "0"; resp.getOutputStream ().print (ping); return; } } } resp.setContentType ("text/html"); try { // Very important - to update Virtual Path!!! AppDomain servletDomain = (AppDomain)this.getServletContext().getAttribute(J2EEConsts.APP_DOMAIN); if (!_appVirDirInited) { string appVPath = req.getContextPath (); if (appVPath == null || appVPath.Length == 0) appVPath = "/"; servletDomain.SetData (IAppDomainConfig.APP_VIRT_DIR, appVPath); servletDomain.SetData (".hostingVirtualPath", req.getContextPath ()); _appVirDirInited = true; } // Put to the TLS current AppDomain of the servlet, so anyone can use it. [email protected](servletDomain); // put request to the TLS //Thread.SetData(_servletRequestSlot, req); //// put response to the TLS //Thread.SetData(_servletResponseSlot, resp); //// put the servlet object to the TLS //Thread.SetData(_servletSlot, this); resp.setHeader("X-Powered-By", "ASP.NET"); resp.setHeader("X-AspNet-Version", "1.1.4322"); HttpWorkerRequest gwr = new ServletWorkerRequest (this, req, resp); CultureInfo culture = (CultureInfo) [email protected] (req.getLocale ()); Thread currentTread = Thread.CurrentThread; currentTread.CurrentCulture = culture; currentTread.CurrentUICulture = culture; HttpRuntime.ProcessRequest(gwr); } finally { HttpContext.Current = null; //Thread.SetData(_servletRequestSlot, null); //Thread.SetData(_servletResponseSlot, null); //Thread.SetData(_servletSlot, null); [email protected](); } }
public override ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, object o, Exception e) { LOG.warn(request.RequestURI + " ExceptionHandler FOUND. " + e.ToString() + "\t" + e.InnerException); // PathVariable 出错 if (e is TypeMismatchException) { return getParamErrors((TypeMismatchException) e); // Bean 参数无法映射错误 } else if (e is InvalidPropertyException) { return getParamErrors((InvalidPropertyException) e); // @Valid 出错 } else if (e is BindException) { return ParamValidateUtils.getParamErrors((BindException) e); // 业务校验处理 } else if (e is FieldException) { return getParamErrors((FieldException) e); } else if (e is DocumentNotFoundException) { response.Status = HttpServletResponse.SC_NOT_FOUND; try { FileUtils.closeWriter(response.Writer); } catch (IOException e1) { Console.WriteLine(e1.ToString()); Console.Write(e1.StackTrace); } return null; // 用户没有请求方法的访问权限 } else if (e is AccessDeniedException) { LOG.warn("details: " + ((AccessDeniedException) e).ErrorMessage); return buildError("auth.access.denied", ErrorCode.ACCESS_NOAUTH_ERROR); } else if (e is HttpRequestMethodNotSupportedException) { return buildError("syserror.httpmethod", ErrorCode.HttpRequestMethodNotSupportedException); } else if (e is MissingServletRequestParameterException) { return buildError("syserror.param.miss", ErrorCode.MissingServletRequestParameterException); } else if (e is GlobalExceptionAware) { LOG.error("details: ", e); GlobalExceptionAware g = (GlobalExceptionAware) e; return buildError(g.ErrorMessage, g.ErrorCode); } else { LOG.warn("details: ", e); return buildError("syserror.inner", ErrorCode.GLOBAL_ERROR); } }
/// <summary> /// Called by the server (via the <code>service</code> method) /// to allow a servlet to handle a TRACE request. /// </summary> protected void doTrace(HttpServletRequest @req, HttpServletResponse @resp) { }
/// /// <param name="resp"></param> /// <param name="req"></param> public override void _jspService(HttpServletResponse resp, HttpServletRequest req) { }
public AspxResponseWrapper(HttpServletResponse resp, TextWriter writer) : base (resp) { jwriter = new PrintWriter(new JavaWriterFromTextWriter(writer)); }
/// <summary> /// 采用两级缓存。先访问session,<br/> /// 如果存在,则直接使用,并更新 threadlocal <br/> /// 如果不存在,则访问 redis,<br/> /// 如果redis存在,则更新session和threadlocal<br/> /// 如果redis也不存在,则认为没有登录 /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception public override bool preHandle(HttpServletRequest request, HttpServletResponse response, object handler) { // // 去掉不需拦截的path // string requestPath = request.RequestURI; // 显示所有用户的请求 LOG.info(request.RequestURI); if (notInterceptPathList != null) { // 更精确的定位 foreach (string path in notInterceptPathList) { if (requestPath.Contains(path)) { return true; } } } /// <summary> /// 种植Cookie /// </summary> plantCookie(request, response); /// <summary> /// 登录与否判断 /// </summary> // // 判断session中是否有visitor // HttpSession session = request.Session; Visitor visitor = (Visitor) session.getAttribute(UserConstant.USER_KEY); // // session中没有该信息,则从 redis上获取,并更新session的数据 // if (visitor == null) { Visitor redisVisitor = redisLogin.isLogin(request); // // 有登录信息 // if (redisVisitor != null) { // 更新session中的登录信息 redisLogin.updateSessionVisitor(session, redisVisitor); } else { // 还是没有登录 returnJsonSystemError(request, response, "login.error", ErrorCode.LOGIN_ERROR); return false; } } else { // 每次都更新session中的登录信息 redisLogin.updateSessionVisitor(session, visitor); } return true; }
public JettyWebConnection(IWebServer webServer, String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) : base(webServer, CallingFrom.Web) { Response = response; BaseRequest = baseRequest; Request = request; _RequestedFile = target; org.eclipse.jetty.io.EndPoint jettyEndpoint = baseRequest.getConnection().getEndPoint(); string remoteAddress = jettyEndpoint.getRemoteAddr(); int remotePort = jettyEndpoint.getRemotePort(); _RemoteEndPoint = new IPEndPoint(IPAddress.Parse(remoteAddress), remotePort); }