/// <summary> /// Called by the server (via the Service method) /// to allow a servlet to handle a TRACE request. /// /// A TRACE returns the headers sent with the TRACE /// request to the client, so that they can be used in /// debugging. There's no need to override this method. /// </summary> /// <param name="req"> /// the IHttpServletRequest object that /// contains the request the client made of /// the servlet /// </param> /// <param name="resp"> /// the IHttpServletResponse object that /// contains the response the servlet returns /// to the client /// </param> /// <exception cref="IOException"> /// if an input or output error occurs /// while the servlet is handling the /// TRACE request /// </exception> /// <exception cref="ServletException"> /// if the request for the /// TRACE cannot be handled /// </exception> protected void DoTrace(IHttpServletRequest req, IHttpServletResponse resp) { int responseLength; string CRLF = "\r\n"; string responseString = "TRACE " + req.RequestURI + " " + req.Protocol; foreach (object elem in req.HeaderNames) { string headerName = (string)elem; responseString += CRLF + headerName + ": " + req.GetHeader(headerName); } responseString += CRLF; responseLength = responseString.Length; resp.ContentType = "message/http"; resp.ContentLength = responseLength; ServletOutputStream output = resp.OutputStream; output.Print(responseString); output.Close(); return; }
/// <summary> /// Receives an HTTP HEAD request from the protected /// Service method and handles the /// request. /// The client sends a HEAD request when it wants /// to see only the headers of a response, such as /// Content-Type or Content-Length. The HTTP HEAD /// method counts the output bytes in the response /// to set the Content-Length header accurately. /// /// If you override this method, you can avoid computing /// the response body and just set the response headers /// directly to improve performance. Make sure that the /// DoHead method you write is both safe /// and idempotent (that is, protects itself from being /// called multiple times for one HTTP HEAD request). /// /// If the HTTP HEAD request is incorrectly formatted, /// DoHead returns an HTTP "Bad Request" /// message. /// </summary> /// <param name="req">the request object that is passed to the servlet</param> /// <param name="resp">the response object that the servlet uses to return the headers to the clien</param> /// <exception cref="IOException">if an input or output error occurs</exception> /// <exception cref="ServletException">if the request for the HEAD could not be handled</exception> protected void DoHead(IHttpServletRequest req, IHttpServletResponse resp) { NoBodyResponse response = new NoBodyResponse(resp); DoGet(req, (IHttpServletResponse)response); response.SetContentLength(); }
/// <summary> /// Reconstructs the URL the client used to make the request, /// using information in the HttpServletRequest object. /// The returned URL contains a protocol, server name, port /// number, and server path, but it does not include query /// string parameters. /// /// Because this method returns a StringBuilder, /// not a string, you can modify the URL easily, for example, /// to Append query parameters. /// /// This method is useful for creating redirect messages /// and for reporting errors. /// </summary> /// <param name="req">a HttpServletRequest object containing the client's request</param> /// <returns>a StringBuilder object containing the reconstructed URL</returns> public static StringBuilder GetRequestURL(IHttpServletRequest req) { StringBuilder url = new StringBuilder(); string scheme = req.Scheme; int port = req.ServerPort; string urlPath = req.RequestURI; //string servletPath = req.getServletPath (); //string pathInfo = req.getPathInfo (); url.Append(scheme); // http, https url.Append("://"); url.Append(req.ServerName); if ((scheme.Equals("http") && port != 80) || (scheme.Equals("https") && port != 443)) { url.Append(':'); url.Append(req.ServerPort); } //if (servletPath != null) // url.Append (servletPath); //if (pathInfo != null) // url.Append (pathInfo); url.Append(urlPath); return(url); }
/// <summary> /// Reconstructs the URL the client used to make the request, /// using information in the HttpServletRequest object. /// The returned URL contains a protocol, server name, port /// number, and server path, but it does not include query /// string parameters. /// /// Because this method returns a StringBuilder, /// not a string, you can modify the URL easily, for example, /// to Append query parameters. /// /// This method is useful for creating redirect messages /// and for reporting errors. /// </summary> /// <param name="req">a HttpServletRequest object containing the client's request</param> /// <returns>a StringBuilder object containing the reconstructed URL</returns> public static StringBuilder GetRequestURL(IHttpServletRequest req) { StringBuilder url = new StringBuilder(); string scheme = req.Scheme; int port = req.ServerPort; string urlPath = req.RequestURI; //string servletPath = req.getServletPath (); //string pathInfo = req.getPathInfo (); url.Append(scheme); // http, https url.Append("://"); url.Append(req.ServerName); if ((scheme.Equals("http") && port != 80) || (scheme.Equals("https") && port != 443)) { url.Append(':'); url.Append(req.ServerPort); } //if (servletPath != null) // url.Append (servletPath); //if (pathInfo != null) // url.Append (pathInfo); url.Append(urlPath); return url; }
/// <summary><inheritDoc/></summary> /// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(IHttpServletRequest request, IHttpServletResponse response) { logger.Info("GET SPIED query from " + request.GetRemoteAddr()); if (request.GetCharacterEncoding() == null) { request.SetCharacterEncoding("utf-8"); } response.SetContentType("text/json; charset=UTF-8"); PrintWriter @out = response.GetWriter(); try { string raw = request.GetParameter("q"); string seedwords = request.GetParameter("seedwords"); string model = request.GetParameter("model"); if (raw == null || string.Empty.Equals(raw)) { @out.Print("{\"okay\":false,\"reason\":\"No data provided\"}"); } else { Run(@out, raw, seedwords, model); } } catch (Exception t) { WriteError(t, @out, request.ToString()); } @out.Close(); }
// --------------------------------------------------------------- Handlers /// <summary> /// Handles a CORS request of type /// <see cref="CORSRequestType"/> /// .SIMPLE. /// </summary> /// <param name="request"> /// The /// <see cref="Javax.Servlet.Http.IHttpServletRequest"/> /// object. /// </param> /// <param name="response"> /// The /// <see cref="Javax.Servlet.Http.IHttpServletResponse"/> /// object. /// </param> /// <param name="filterChain"> /// The /// <see cref="Javax.Servlet.IFilterChain"/> /// object. /// </param> /// <exception cref="System.IO.IOException"/> /// <exception cref="Javax.Servlet.ServletException"/> /// <seealso><a href="http://www.w3.org/TR/cors/#resource-requests">Simple /// * Cross-Origin Request, Actual Request, and Redirects</a></seealso> public void HandleSimpleCORS(IHttpServletRequest request, IHttpServletResponse response, IFilterChain filterChain) { CORSFilter.CORSRequestType requestType = CheckRequestType(request); if (!(requestType == CORSFilter.CORSRequestType.Simple || requestType == CORSFilter.CORSRequestType.Actual)) { string message = "Expects a HttpServletRequest object of type " + CORSFilter.CORSRequestType.Simple + " or " + CORSFilter.CORSRequestType.Actual; throw new ArgumentException(message); } string origin = request.GetHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.RequestHeaderOrigin); string method = request.GetMethod(); // Section 6.1.2 if (!IsOriginAllowed(origin)) { HandleInvalidCORS(request, response, filterChain); return; } if (!allowedHttpMethods.Contains(method)) { HandleInvalidCORS(request, response, filterChain); return; } // Section 6.1.3 // Add a single Access-Control-Allow-Origin header. if (anyOriginAllowed && !supportsCredentials) { // If resource doesn't support credentials and if any origin is // allowed // to make CORS request, return header with '*'. response.AddHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.ResponseHeaderAccessControlAllowOrigin, "*"); } else { // If the resource supports credentials add a single // Access-Control-Allow-Origin header, with the value of the Origin // header as value. response.AddHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.ResponseHeaderAccessControlAllowOrigin, origin); } // Section 6.1.3 // If the resource supports credentials, add a single // Access-Control-Allow-Credentials header with the case-sensitive // string "true" as value. if (supportsCredentials) { response.AddHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.ResponseHeaderAccessControlAllowCredentials, "true"); } // Section 6.1.4 // If the list of exposed headers is not empty add one or more // Access-Control-Expose-Headers headers, with as values the header // field names given in the list of exposed headers. if ((exposedHeaders != null) && (exposedHeaders.Count > 0)) { string exposedHeadersString = Join(exposedHeaders, ","); response.AddHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.ResponseHeaderAccessControlExposeHeaders, exposedHeadersString); } // Forward the request down the filter chain. filterChain.DoFilter(request, response); }
// --------------------------------------------------------- Public methods /// <exception cref="System.IO.IOException"/> /// <exception cref="Javax.Servlet.ServletException"/> public void DoFilter(IServletRequest servletRequest, IServletResponse servletResponse, IFilterChain filterChain) { if (!(servletRequest is IHttpServletRequest) || !(servletResponse is IHttpServletResponse)) { string message = "CORS doesn't support non-HTTP request or response."; throw new ServletException(message); } // Safe to downcast at this point. IHttpServletRequest request = (IHttpServletRequest)servletRequest; IHttpServletResponse response = (IHttpServletResponse)servletResponse; // Determines the CORS request type. CORSFilter.CORSRequestType requestType = CheckRequestType(request); // Adds CORS specific attributes to request. if (decorateRequest) { Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.DecorateCORSProperties(request, requestType); } switch (requestType) { case CORSFilter.CORSRequestType.Simple: { // Handles a Simple CORS request. this.HandleSimpleCORS(request, response, filterChain); break; } case CORSFilter.CORSRequestType.Actual: { // Handles an Actual CORS request. this.HandleSimpleCORS(request, response, filterChain); break; } case CORSFilter.CORSRequestType.PreFlight: { // Handles a Pre-flight CORS request. this.HandlePreflightCORS(request, response, filterChain); break; } case CORSFilter.CORSRequestType.NotCors: { // Handles a Normal request that is not a cross-origin request. this.HandleNonCORS(request, response, filterChain); break; } default: { // Handles a CORS request that violates specification. this.HandleInvalidCORS(request, response, filterChain); break; } } }
/// <exception cref="System.IO.IOException"/> private void AddResults(IHttpServletRequest request, IHttpServletResponse response) { string input = request.GetParameter("input"); if (input == null) { return; } input = input.Trim(); if (input.IsEmpty()) { return; } PrintWriter @out = response.GetWriter(); if (input.Length > MaximumQueryLength) { @out.Print("This query is too long. If you want to run very long queries, please download and use our <a href=\"http://nlp.stanford.edu/software/CRF-NER.html\">publicly released distribution</a>."); return; } string outputFormat = request.GetParameter("outputFormat"); if (outputFormat == null || outputFormat.Trim().IsEmpty()) { outputFormat = this.format; } bool preserveSpacing; string preserveSpacingStr = request.GetParameter("preserveSpacing"); if (preserveSpacingStr == null || preserveSpacingStr.Trim().IsEmpty()) { preserveSpacing = this.spacing; } else { preserveSpacingStr = preserveSpacingStr.Trim(); preserveSpacing = bool.ValueOf(preserveSpacingStr); } string classifier = request.GetParameter("classifier"); if (classifier == null || classifier.Trim().IsEmpty()) { classifier = this.defaultClassifier; } response.AddHeader("classifier", classifier); response.AddHeader("outputFormat", outputFormat); response.AddHeader("preserveSpacing", preserveSpacing.ToString()); if (outputFormat.Equals("highlighted")) { OutputHighlighting(@out, ners[classifier], input); } else { @out.Print(StringEscapeUtils.EscapeHtml4(ners[classifier].ClassifyToString(input, outputFormat, preserveSpacing))); } }
// NOOP // -------------------------------------------------------- Utility methods /// <summary> /// Decorates the /// <see cref="Javax.Servlet.Http.IHttpServletRequest"/> /// , with CORS attributes. /// <ul> /// <li><b>cors.isCorsRequest:</b> Flag to determine if request is a CORS /// request. Set to <code>true</code> if CORS request; <code>false</code> /// otherwise.</li> /// <li><b>cors.request.origin:</b> The Origin URL.</li> /// <li><b>cors.request.type:</b> Type of request. Values: /// <code>simple</code> or <code>preflight</code> or <code>not_cors</code> or /// <code>invalid_cors</code></li> /// <li><b>cors.request.headers:</b> Request headers sent as /// 'Access-Control-Request-Headers' header, for pre-flight request.</li> /// </ul> /// </summary> /// <param name="request"> /// The /// <see cref="Javax.Servlet.Http.IHttpServletRequest"/> /// object. /// </param> /// <param name="corsRequestType"> /// The /// <see cref="CORSRequestType"/> /// object. /// </param> public static void DecorateCORSProperties(IHttpServletRequest request, CORSFilter.CORSRequestType corsRequestType) { if (request == null) { throw new ArgumentException("HttpServletRequest object is null"); } if (corsRequestType == null) { throw new ArgumentException("CORSRequestType object is null"); } switch (corsRequestType) { case CORSFilter.CORSRequestType.Simple: { request.SetAttribute(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.HttpRequestAttributeIsCorsRequest, true); request.SetAttribute(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.HttpRequestAttributeOrigin, request.GetHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.RequestHeaderOrigin)); request.SetAttribute(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.HttpRequestAttributeRequestType, corsRequestType.ToString().ToLower()); break; } case CORSFilter.CORSRequestType.Actual: { request.SetAttribute(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.HttpRequestAttributeIsCorsRequest, true); request.SetAttribute(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.HttpRequestAttributeOrigin, request.GetHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.RequestHeaderOrigin)); request.SetAttribute(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.HttpRequestAttributeRequestType, corsRequestType.ToString().ToLower()); break; } case CORSFilter.CORSRequestType.PreFlight: { request.SetAttribute(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.HttpRequestAttributeIsCorsRequest, true); request.SetAttribute(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.HttpRequestAttributeOrigin, request.GetHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.RequestHeaderOrigin)); request.SetAttribute(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.HttpRequestAttributeRequestType, corsRequestType.ToString().ToLower()); string headers = request.GetHeader(RequestHeaderAccessControlRequestHeaders); if (headers == null) { headers = string.Empty; } request.SetAttribute(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.HttpRequestAttributeRequestHeaders, headers); break; } case CORSFilter.CORSRequestType.NotCors: { request.SetAttribute(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.HttpRequestAttributeIsCorsRequest, false); break; } default: { // Don't set any attributes break; } } }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(IHttpServletRequest request, IHttpServletResponse response) { if (request.GetCharacterEncoding() == null) { request.SetCharacterEncoding("utf-8"); } response.SetContentType("text/html; charset=UTF-8"); this.GetServletContext().GetRequestDispatcher("/header.jsp").Include(request, response); AddResults(request, response); this.GetServletContext().GetRequestDispatcher("/footer.jsp").Include(request, response); }
private Properties GetTimeAnnotatorProperties(IHttpServletRequest request) { // Parses request and set up properties for time annotators bool markTimeRanges = ParseBoolean(request.GetParameter("markTimeRanges")); bool includeNested = ParseBoolean(request.GetParameter("includeNested")); bool includeRange = ParseBoolean(request.GetParameter("includeRange")); bool readRules = true; string heuristicLevel = request.GetParameter("relativeHeuristicLevel"); Options.RelativeHeuristicLevel relativeHeuristicLevel = Options.RelativeHeuristicLevel.None; if (!StringUtils.IsNullOrEmpty(heuristicLevel)) { relativeHeuristicLevel = Options.RelativeHeuristicLevel.ValueOf(heuristicLevel); } string ruleFile = null; if (readRules) { string rules = request.GetParameter("rules"); if (Sharpen.Runtime.EqualsIgnoreCase("English", rules)) { ruleFile = GetRuleFilepaths("defs.sutime.txt", "english.sutime.txt", "english.holidays.sutime.txt"); } } // Create properties Properties props = new Properties(); if (markTimeRanges) { props.SetProperty("sutime.markTimeRanges", "true"); } if (includeNested) { props.SetProperty("sutime.includeNested", "true"); } if (includeRange) { props.SetProperty("sutime.includeRange", "true"); } if (ruleFile != null) { props.SetProperty("sutime.rules", ruleFile); props.SetProperty("sutime.binders", "1"); props.SetProperty("sutime.binder.1", "edu.stanford.nlp.time.JollyDayHolidays"); props.SetProperty("sutime.binder.1.xml", GetServletContext().GetRealPath("/WEB-INF/data/holidays/Holidays_sutime.xml")); props.SetProperty("sutime.binder.1.pathtype", "file"); } props.SetProperty("sutime.teRelHeurLevel", relativeHeuristicLevel.ToString()); // props.setProperty("sutime.verbose", "true"); // props.setProperty("heideltime.path", getServletContext().getRealPath("/packages/heideltime")); // props.setProperty("gutime.path", getServletContext().getRealPath("/packages/gutime")); return(props); }
/// <summary> /// Called by the server (via the Service method) /// to allow a servlet to handle a PUT request. /// /// The PUT operation allows a client to /// place a file on the server and is similar to /// sending a file by FTP. /// /// When overriding this method, leave intact /// any content headers sent with the request (including /// Content-Length, Content-Type, Content-Transfer-Encoding, /// Content-Encoding, Content-Base, Content-Language, Content-Location, /// Content-MD5, and Content-Range). If your method cannot /// handle a content header, it must issue an error message /// (HTTP 501 - Not Implemented) and discard the request. /// For more information on HTTP 1.1, see RFC 2616 /// <a href="http://www.ietf.org/rfc/rfc2616.txt"></a>. /// /// This method does not need to be either safe or idempotent. /// Operations that <code>doPut</code> performs can have side /// effects for which the user can be held accountable. When using /// this method, it may be useful to save a copy of the /// affected URL in temporary storage. /// /// If the HTTP PUT request is incorrectly formatted, /// DoPut returns an HTTP "Bad Request" message. /// </summary> /// <param name="req"> /// the IHttpServletRequest object that /// contains the request the client made of /// the servlet /// </param> /// <param name="resp"> /// the IHttpServletResponse object that /// contains the response the servlet returns /// to the client /// </param> /// <exception cref="IOException"> /// if an input or output error occurs /// while the servlet is handling the /// PUT request /// </exception> /// <exception cref="ServletException">if the request for the PUT cannot be handled</exception> protected void DoPut(IHttpServletRequest req, IHttpServletResponse resp) { string protocol = req.Protocol; //TODO: string msg = lStrings.getString("http.method_put_not_supported"); string msg = "HTTP method PUT is not supported by this URL"; if (protocol.EndsWith("1.1")) { resp.SendError((int)HttpServletResponseStatusCode.SC_METHOD_NOT_ALLOWED, msg); } else { resp.SendError((int)HttpServletResponseStatusCode.SC_BAD_REQUEST, msg); } }
/// <summary>Handles a CORS request that violates specification.</summary> /// <param name="request"> /// The /// <see cref="Javax.Servlet.Http.IHttpServletRequest"/> /// object. /// </param> /// <param name="response"> /// The /// <see cref="Javax.Servlet.Http.IHttpServletResponse"/> /// object. /// </param> /// <param name="filterChain"> /// The /// <see cref="Javax.Servlet.IFilterChain"/> /// object. /// </param> /// <exception cref="System.IO.IOException"/> /// <exception cref="Javax.Servlet.ServletException"/> public void HandleInvalidCORS(IHttpServletRequest request, IHttpServletResponse response, IFilterChain filterChain) { string origin = request.GetHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.RequestHeaderOrigin); string method = request.GetMethod(); string accessControlRequestHeaders = request.GetHeader(RequestHeaderAccessControlRequestHeaders); string message = "Invalid CORS request; Origin=" + origin + ";Method=" + method; if (accessControlRequestHeaders != null) { message = message + ";Access-Control-Request-Headers=" + accessControlRequestHeaders; } response.SetContentType("text/plain"); response.SetStatus(HttpServletResponseConstants.ScForbidden); response.ResetBuffer(); Log(message); }
/// <summary><inheritDoc/></summary> /// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(IHttpServletRequest request, IHttpServletResponse response) { if (request.GetCharacterEncoding() == null) { request.SetCharacterEncoding("utf-8"); } response.SetContentType("text/json; charset=UTF-8"); PrintWriter @out = response.GetWriter(); string raw = request.GetParameter("q"); if (raw == null || string.Empty.Equals(raw)) { @out.Println("{ok:false, entailments:[], triples=[], msg=\"\"}"); } else { DoGet(@out, raw); } @out.Close(); }
/// <exception cref="System.IO.IOException"/> private void AddResults(IHttpServletRequest request, IHttpServletResponse response) { // if we can't handle UTF-8, need to do something like this... //String originalQuery = request.getParameter("q"); //String query = WebappUtil.convertString(originalQuery); string query = request.GetParameter("q"); string dateString = request.GetParameter("d"); // TODO: this always returns true... bool dateError = !pipeline.IsDateOkay(dateString); bool includeOffsets = ParseBoolean(request.GetParameter("includeOffsets")); PrintWriter @out = response.GetWriter(); if (dateError) { @out.Println("<br><br>Warning: unparseable date " + StringEscapeUtils.EscapeHtml4(dateString)); } if (!StringUtils.IsNullOrEmpty(query)) { Properties props = GetTimeAnnotatorProperties(request); string annotatorType = request.GetParameter("annotator"); if (annotatorType == null) { annotatorType = "sutime"; } IAnnotator timeAnnotator = pipeline.GetTimeAnnotator(annotatorType, props); if (timeAnnotator != null) { Annotation anno = pipeline.Process(query, dateString, timeAnnotator); @out.Println("<h3>Annotated Text</h3> <em>(tagged using " + annotatorType + "</em>)"); DisplayAnnotation(@out, query, anno, includeOffsets); } else { @out.Println("<br><br>Error creating annotator for " + StringEscapeUtils.EscapeHtml4(annotatorType)); } } }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> public virtual void AddResults(IHttpServletRequest request, IHttpServletResponse response) { string input = request.GetParameter("input"); if (input == null) { return; } input = input.Trim(); if (input.IsEmpty()) { return; } PrintWriter @out = response.GetWriter(); if (input.Length > MaximumQueryLength) { @out.Print("<div>This query is too long. If you want to run very long queries, please download and use our <a href=\"http://nlp.stanford.edu/software/corenlp.html\">publicly released distribution</a>.</div>"); return; } Annotation annotation = new Annotation(input); pipeline.Annotate(annotation); string outputFormat = request.GetParameter("outputFormat"); if (outputFormat == null || outputFormat.Trim().IsEmpty()) { outputFormat = this.defaultFormat; } switch (outputFormat) { case "xml": { OutputXml(@out, annotation); break; } case "json": { OutputJson(@out, annotation); break; } case "conll": { OutputCoNLL(@out, annotation); break; } case "pretty": { OutputPretty(@out, annotation); break; } default: { OutputVisualise(@out, annotation); break; } } }
/// <summary> /// Returns the time the IHttpServletRequest /// object was last modified, /// in milliseconds since midnight January 1, 1970 GMT. /// If the time is unknown, this method returns a negative /// number (the default). /// /// Servlets that support HTTP GET requests and can quickly determine /// their last modification time should override this method. /// This makes browser and proxy caches work more effectively, /// reducing the load on server and network resources. /// </summary> /// <param name="req">the object that is sent to the servlet</param> /// <returns> /// a long integer specifying /// the time the IHttpServletRequest /// object was last modified, in milliseconds /// since midnight, January 1, 1970 GMT, or /// -1 if the time is not known /// </returns> protected long GetLastModified(IHttpServletRequest req) { return(-1); }
//throws ServletException, IOException /// <summary> /// Receives standard HTTP requests from the public /// Service method and dispatches /// them to the <code>Do</code><i>XXX</i> methods defined in /// this class. This method is an HTTP-specific version of the /// {@link javax.servlet.Servlet#Service} method. There's no /// need to override this method. /// </summary> /// <param name="req"> /// the IHttpServletRequest object that /// contains the request the client made of /// the servlet /// </param> /// <param name="resp"> /// the IHttpServletResponse object that /// contains the response the servlet returns /// to the client /// </param> /// <exception cref="IOException"> /// if an input or output error occurs /// while the servlet is handling the /// HTTP request /// </exception> /// <exception cref="ServletException"> /// if the HTTP request cannot be handled /// </exception> protected void Service(IHttpServletRequest req, IHttpServletResponse resp) { string method = req.Method; if (method.Equals(METHOD_GET)) { long lastModified = GetLastModified(req); if (lastModified == -1) { // servlet doesn't support if-modified-since, no reason // to go through further expensive logic DoGet(req, resp); } else { long ifModifiedSince = req.GetDateHeader(HEADER_IFMODSINCE); if (ifModifiedSince < (lastModified / 1000 * 1000)) { // If the servlet mod time is later, call doGet() // Round down to the nearest second for a proper compare // A ifModifiedSince of -1 will always be less MaybeSetLastModified(resp, lastModified); DoGet(req, resp); } else { resp.Status = (int)HttpServletResponseStatusCode.SC_NOT_MODIFIED; } } } else if (method.Equals(METHOD_HEAD)) { long lastModified = GetLastModified(req); MaybeSetLastModified(resp, lastModified); DoHead(req, resp); } else if (method.Equals(METHOD_POST)) { DoPost(req, resp); } else if (method.Equals(METHOD_PUT)) { DoPut(req, resp); } else if (method.Equals(METHOD_DELETE)) { DoDelete(req, resp); } else if (method.Equals(METHOD_OPTIONS)) { DoOptions(req, resp); } else if (method.Equals(METHOD_TRACE)) { DoTrace(req, resp); } else { // // Note that this means NO servlet supports whatever // method was requested, anywhere on this server. // //TODO: string errMsg = lStrings.getString("http.method_not_implemented"); string errMsg = "Method {0} is not defined in RFC 2068 and is not supported by the Servlet API"; object[] errArgs = new object[1]; errArgs[0] = method; errMsg = string.Format(errMsg, errArgs); resp.SendError((int)HttpServletResponseStatusCode.SC_NOT_IMPLEMENTED, errMsg); } }
// Do not forward the request down the filter chain. /// <summary>Handles a request, that's not a CORS request, but is a valid request i.e.</summary> /// <remarks> /// Handles a request, that's not a CORS request, but is a valid request i.e. /// it is not a cross-origin request. This implementation, just forwards the /// request down the filter chain. /// </remarks> /// <param name="request"> /// The /// <see cref="Javax.Servlet.Http.IHttpServletRequest"/> /// object. /// </param> /// <param name="response"> /// The /// <see cref="Javax.Servlet.Http.IHttpServletResponse"/> /// object. /// </param> /// <param name="filterChain"> /// The /// <see cref="Javax.Servlet.IFilterChain"/> /// object. /// </param> /// <exception cref="System.IO.IOException"/> /// <exception cref="Javax.Servlet.ServletException"/> public void HandleNonCORS(IHttpServletRequest request, IHttpServletResponse response, IFilterChain filterChain) { // Let request pass. filterChain.DoFilter(request, response); }
/// <summary> /// Called by the server (via the Service method) /// to allow a servlet to handle a OPTIONS request. /// /// The OPTIONS request determines which HTTP methods /// the server supports and /// returns an appropriate header. For example, if a servlet /// overrides DoGet, this method returns the /// following header: /// /// <code>Allow: GET, HEAD, TRACE, OPTIONS</code> /// /// There's no need to override this method unless the /// servlet implements new HTTP methods, beyond those /// implemented by HTTP 1.1. /// </summary> /// <param name="req"> /// the IHttpServletRequest object that /// contains the request the client made of /// the servlet</param> /// <param name="resp"> /// the IHttpServletResponse object that /// contains the response the servlet returns /// to the client /// </param> /// <exception cref="IOException"> /// if an input or output error occurs /// while the servlet is handling the /// OPTIONS request /// </exception> /// <exception cref="ServletException"> /// if the request for the /// OPTIONS cannot be handled /// </exception> protected void DoOptions(IHttpServletRequest req, IHttpServletResponse resp) { MethodInfo[] methods = GetAllDeclaredMethods(this.GetType()); bool ALLOW_GET = false; bool ALLOW_HEAD = false; bool ALLOW_POST = false; bool ALLOW_PUT = false; bool ALLOW_DELETE = false; bool ALLOW_TRACE = true; bool ALLOW_OPTIONS = true; for (int i = 0; i < methods.Length; i++) { MethodInfo m = methods[i]; if (m.Name.Equals("DoGet")) { ALLOW_GET = true; ALLOW_HEAD = true; } if (m.Name.Equals("DoPost")) ALLOW_POST = true; if (m.Name.Equals("DoPut")) ALLOW_PUT = true; if (m.Name.Equals("DoDelete")) ALLOW_DELETE = true; } string allow = null; if (ALLOW_GET) if (allow == null) allow = METHOD_GET; if (ALLOW_HEAD) if (allow == null) allow = METHOD_HEAD; else allow += ", " + METHOD_HEAD; if (ALLOW_POST) if (allow == null) allow = METHOD_POST; else allow += ", " + METHOD_POST; if (ALLOW_PUT) if (allow == null) allow = METHOD_PUT; else allow += ", " + METHOD_PUT; if (ALLOW_DELETE) if (allow == null) allow = METHOD_DELETE; else allow += ", " + METHOD_DELETE; if (ALLOW_TRACE) if (allow == null) allow = METHOD_TRACE; else allow += ", " + METHOD_TRACE; if (ALLOW_OPTIONS) if (allow == null) allow = METHOD_OPTIONS; else allow += ", " + METHOD_OPTIONS; resp.SetHeader("Allow", allow); }
/// <summary> /// Called by the server (via the Service method) /// to allow a servlet to handle a OPTIONS request. /// /// The OPTIONS request determines which HTTP methods /// the server supports and /// returns an appropriate header. For example, if a servlet /// overrides DoGet, this method returns the /// following header: /// /// <code>Allow: GET, HEAD, TRACE, OPTIONS</code> /// /// There's no need to override this method unless the /// servlet implements new HTTP methods, beyond those /// implemented by HTTP 1.1. /// </summary> /// <param name="req"> /// the IHttpServletRequest object that /// contains the request the client made of /// the servlet</param> /// <param name="resp"> /// the IHttpServletResponse object that /// contains the response the servlet returns /// to the client /// </param> /// <exception cref="IOException"> /// if an input or output error occurs /// while the servlet is handling the /// OPTIONS request /// </exception> /// <exception cref="ServletException"> /// if the request for the /// OPTIONS cannot be handled /// </exception> protected void DoOptions(IHttpServletRequest req, IHttpServletResponse resp) { MethodInfo[] methods = GetAllDeclaredMethods(this.GetType()); bool ALLOW_GET = false; bool ALLOW_HEAD = false; bool ALLOW_POST = false; bool ALLOW_PUT = false; bool ALLOW_DELETE = false; bool ALLOW_TRACE = true; bool ALLOW_OPTIONS = true; for (int i = 0; i < methods.Length; i++) { MethodInfo m = methods[i]; if (m.Name.Equals("DoGet")) { ALLOW_GET = true; ALLOW_HEAD = true; } if (m.Name.Equals("DoPost")) { ALLOW_POST = true; } if (m.Name.Equals("DoPut")) { ALLOW_PUT = true; } if (m.Name.Equals("DoDelete")) { ALLOW_DELETE = true; } } string allow = null; if (ALLOW_GET) { if (allow == null) { allow = METHOD_GET; } } if (ALLOW_HEAD) { if (allow == null) { allow = METHOD_HEAD; } else { allow += ", " + METHOD_HEAD; } } if (ALLOW_POST) { if (allow == null) { allow = METHOD_POST; } else { allow += ", " + METHOD_POST; } } if (ALLOW_PUT) { if (allow == null) { allow = METHOD_PUT; } else { allow += ", " + METHOD_PUT; } } if (ALLOW_DELETE) { if (allow == null) { allow = METHOD_DELETE; } else { allow += ", " + METHOD_DELETE; } } if (ALLOW_TRACE) { if (allow == null) { allow = METHOD_TRACE; } else { allow += ", " + METHOD_TRACE; } } if (ALLOW_OPTIONS) { if (allow == null) { allow = METHOD_OPTIONS; } else { allow += ", " + METHOD_OPTIONS; } } resp.SetHeader("Allow", allow); }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoPost(IHttpServletRequest request, IHttpServletResponse response) { DoGet(request, response); }
/// <summary> /// Receives standard HTTP requests from the public /// Service method and dispatches /// them to the <code>Do</code><i>XXX</i> methods defined in /// this class. This method is an HTTP-specific version of the /// {@link javax.servlet.Servlet#Service} method. There's no /// need to override this method. /// </summary> /// <param name="req"> /// the IHttpServletRequest object that /// contains the request the client made of /// the servlet /// </param> /// <param name="resp"> /// the IHttpServletResponse object that /// contains the response the servlet returns /// to the client /// </param> /// <exception cref="IOException"> /// if an input or output error occurs /// while the servlet is handling the /// HTTP request /// </exception> /// <exception cref="ServletException"> /// if the HTTP request cannot be handled /// </exception> protected void Service(IHttpServletRequest req, IHttpServletResponse resp) //throws ServletException, IOException { string method = req.Method; if (method.Equals(METHOD_GET)) { long lastModified = GetLastModified(req); if (lastModified == -1) { // servlet doesn't support if-modified-since, no reason // to go through further expensive logic DoGet(req, resp); } else { long ifModifiedSince = req.GetDateHeader(HEADER_IFMODSINCE); if (ifModifiedSince < (lastModified / 1000 * 1000)) { // If the servlet mod time is later, call doGet() // Round down to the nearest second for a proper compare // A ifModifiedSince of -1 will always be less MaybeSetLastModified(resp, lastModified); DoGet(req, resp); } else { resp.Status = (int)HttpServletResponseStatusCode.SC_NOT_MODIFIED; } } } else if (method.Equals(METHOD_HEAD)) { long lastModified = GetLastModified(req); MaybeSetLastModified(resp, lastModified); DoHead(req, resp); } else if (method.Equals(METHOD_POST)) { DoPost(req, resp); } else if (method.Equals(METHOD_PUT)) { DoPut(req, resp); } else if (method.Equals(METHOD_DELETE)) { DoDelete(req, resp); } else if (method.Equals(METHOD_OPTIONS)) { DoOptions(req, resp); } else if (method.Equals(METHOD_TRACE)) { DoTrace(req, resp); } else { // // Note that this means NO servlet supports whatever // method was requested, anywhere on this server. // //TODO: string errMsg = lStrings.getString("http.method_not_implemented"); string errMsg = "Method {0} is not defined in RFC 2068 and is not supported by the Servlet API"; object[] errArgs = new object[1]; errArgs[0] = method; errMsg = string.Format(errMsg, errArgs); resp.SendError((int)HttpServletResponseStatusCode.SC_NOT_IMPLEMENTED, errMsg); } }
/// <summary> /// Constructs a request object wrapping the given request. /// </summary> /// <param name="request"></param> /// <exception cref="ArgumentException">if the request is null</exception> public HttpServletRequestWrapper(IHttpServletRequest request) : base(request) { }
/// <summary><inheritDoc/></summary> /// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoPost(IHttpServletRequest request, IHttpServletResponse response) { logger.Info("Responding to the request for SPIED"); GetServletContext().Log("Responding through SPIED through servlet context!!"); DoGet(request, response); }
/// <summary> /// Returns the time the IHttpServletRequest /// object was last modified, /// in milliseconds since midnight January 1, 1970 GMT. /// If the time is unknown, this method returns a negative /// number (the default). /// /// Servlets that support HTTP GET requests and can quickly determine /// their last modification time should override this method. /// This makes browser and proxy caches work more effectively, /// reducing the load on server and network resources. /// </summary> /// <param name="req">the object that is sent to the servlet</param> /// <returns> /// a long integer specifying /// the time the IHttpServletRequest /// object was last modified, in milliseconds /// since midnight, January 1, 1970 GMT, or /// -1 if the time is not known /// </returns> protected long GetLastModified(IHttpServletRequest req) { return -1; }
/// <summary>Determines the request type.</summary> /// <param name="request"/> /// <returns/> public CORSFilter.CORSRequestType CheckRequestType(IHttpServletRequest request) { CORSFilter.CORSRequestType requestType = CORSFilter.CORSRequestType.InvalidCors; if (request == null) { throw new ArgumentException("HttpServletRequest object is null"); } string originHeader = request.GetHeader(RequestHeaderOrigin); // Section 6.1.1 and Section 6.2.1 if (originHeader != null) { if (originHeader.IsEmpty()) { requestType = CORSFilter.CORSRequestType.InvalidCors; } else { if (!IsValidOrigin(originHeader)) { requestType = CORSFilter.CORSRequestType.InvalidCors; } else { string method = request.GetMethod(); if (method != null && HttpMethods.Contains(method)) { if ("OPTIONS".Equals(method)) { string accessControlRequestMethodHeader = request.GetHeader(RequestHeaderAccessControlRequestMethod); if (accessControlRequestMethodHeader != null && !accessControlRequestMethodHeader.IsEmpty()) { requestType = CORSFilter.CORSRequestType.PreFlight; } else { if (accessControlRequestMethodHeader != null && accessControlRequestMethodHeader.IsEmpty()) { requestType = CORSFilter.CORSRequestType.InvalidCors; } else { requestType = CORSFilter.CORSRequestType.Actual; } } } else { if ("GET".Equals(method) || "HEAD".Equals(method)) { requestType = CORSFilter.CORSRequestType.Simple; } else { if ("POST".Equals(method)) { string contentType = request.GetContentType(); if (contentType != null) { contentType = contentType.ToLower().Trim(); if (SimpleHttpRequestContentTypeValues.Contains(contentType)) { requestType = CORSFilter.CORSRequestType.Simple; } else { requestType = CORSFilter.CORSRequestType.Actual; } } } else { if (ComplexHttpMethods.Contains(method)) { requestType = CORSFilter.CORSRequestType.Actual; } } } } } } } } else { requestType = CORSFilter.CORSRequestType.NotCors; } return(requestType); }
/// <summary>Handles CORS pre-flight request.</summary> /// <param name="request"> /// The /// <see cref="Javax.Servlet.Http.IHttpServletRequest"/> /// object. /// </param> /// <param name="response"> /// The /// <see cref="Javax.Servlet.Http.IHttpServletResponse"/> /// object. /// </param> /// <param name="filterChain"> /// The /// <see cref="Javax.Servlet.IFilterChain"/> /// object. /// </param> /// <exception cref="System.IO.IOException"/> /// <exception cref="Javax.Servlet.ServletException"/> public void HandlePreflightCORS(IHttpServletRequest request, IHttpServletResponse response, IFilterChain filterChain) { CORSFilter.CORSRequestType requestType = CheckRequestType(request); if (requestType != CORSFilter.CORSRequestType.PreFlight) { throw new ArgumentException("Expects a HttpServletRequest object of type " + CORSFilter.CORSRequestType.PreFlight.ToString().ToLower()); } string origin = request.GetHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.RequestHeaderOrigin); // Section 6.2.2 if (!IsOriginAllowed(origin)) { HandleInvalidCORS(request, response, filterChain); return; } // Section 6.2.3 string accessControlRequestMethod = request.GetHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.RequestHeaderAccessControlRequestMethod); if (accessControlRequestMethod == null || (!HttpMethods.Contains(accessControlRequestMethod.Trim()))) { HandleInvalidCORS(request, response, filterChain); return; } else { accessControlRequestMethod = accessControlRequestMethod.Trim(); } // Section 6.2.4 string accessControlRequestHeadersHeader = request.GetHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.RequestHeaderAccessControlRequestHeaders); IList <string> accessControlRequestHeaders = new LinkedList <string>(); if (accessControlRequestHeadersHeader != null && !accessControlRequestHeadersHeader.Trim().IsEmpty()) { string[] headers = accessControlRequestHeadersHeader.Trim().Split(","); foreach (string header in headers) { accessControlRequestHeaders.Add(header.Trim().ToLower()); } } // Section 6.2.5 if (!allowedHttpMethods.Contains(accessControlRequestMethod)) { HandleInvalidCORS(request, response, filterChain); return; } // Section 6.2.6 if (!accessControlRequestHeaders.IsEmpty()) { foreach (string header in accessControlRequestHeaders) { if (!allowedHttpHeaders.Contains(header)) { HandleInvalidCORS(request, response, filterChain); return; } } } // Section 6.2.7 if (supportsCredentials) { response.AddHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.ResponseHeaderAccessControlAllowOrigin, origin); response.AddHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.ResponseHeaderAccessControlAllowCredentials, "true"); } else { if (anyOriginAllowed) { response.AddHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.ResponseHeaderAccessControlAllowOrigin, "*"); } else { response.AddHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.ResponseHeaderAccessControlAllowOrigin, origin); } } // Section 6.2.8 if (preflightMaxAge > 0) { response.AddHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.ResponseHeaderAccessControlMaxAge, preflightMaxAge.ToString()); } // Section 6.2.9 response.AddHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.ResponseHeaderAccessControlAllowMethods, accessControlRequestMethod); // Section 6.2.10 if ((allowedHttpHeaders != null) && (!allowedHttpHeaders.IsEmpty())) { response.AddHeader(Edu.Stanford.Nlp.Naturalli.Demo.CORSFilter.ResponseHeaderAccessControlAllowHeaders, Join(allowedHttpHeaders, ",")); } }