Example #1
0
        /// <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();
        }
Example #2
0
        /// <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><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;
            }
            }
        }
Example #6
0
        /// <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)));
            }
        }
 /// <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);
 }
Example #8
0
 /// <summary>
 /// Sets the Last-Modified entity header field, if it has not
 /// already been set and if the value is meaningful.  Called before
 /// doGet, to ensure that headers are set before response data is
 /// written.  A subclass might have set this header already, so we
 /// check.
 /// </summary>
 /// <param name="resp"></param>
 /// <param name="lastModified"></param>
 private void MaybeSetLastModified(IHttpServletResponse resp,
                                   long lastModified)
 {
     if (resp.ContainsHeader(HEADER_LASTMOD))
     {
         return;
     }
     if (lastModified >= 0)
     {
         resp.SetDateHeader(HEADER_LASTMOD, lastModified);
     }
 }
Example #9
0
        /// <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;
            }
            }
        }
Example #14
0
 /// <summary>
 /// Constructs a response adaptor wrapping the given response.
 /// </summary>
 /// <param name="response"></param>
 /// <exception cref="ArgumentException">if the response is null</exception>
 public HttpServletResponseWrapper(IHttpServletResponse response)
     : base(response)
 {
 }
Example #15
0
 // file private
 public NoBodyResponse(IHttpServletResponse r)
     : base(r)
 {
     noBody = new NoBodyOutputStream();
 }
Example #16
0
        /// <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);
        }
Example #17
0
        //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);
            }
        }
Example #18
0
 /// <summary>
 /// Sets the Last-Modified entity header field, if it has not
 /// already been set and if the value is meaningful.  Called before
 /// doGet, to ensure that headers are set before response data is
 /// written.  A subclass might have set this header already, so we
 /// check.
 /// </summary>
 /// <param name="resp"></param>
 /// <param name="lastModified"></param>
 private void MaybeSetLastModified(IHttpServletResponse resp,
     long lastModified)
 {
     if (resp.ContainsHeader(HEADER_LASTMOD))
         return;
     if (lastModified >= 0)
         resp.SetDateHeader(HEADER_LASTMOD, lastModified);
 }
Example #19
0
 /// <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);
     }
 }
Example #20
0
        /// <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;
        }
Example #21
0
        /// <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);
            }
        }
Example #22
0
 // file private
 public NoBodyResponse(IHttpServletResponse r)
     : base(r)
 {
     noBody = new NoBodyOutputStream();
 }
 /// <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);
 }
 // 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>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, ","));
            }
        }
Example #26
0
        /// <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();
        }
Example #27
0
        /// <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>
 /// Constructs a response adaptor wrapping the given response.
 /// </summary>
 /// <param name="response"></param>
 /// <exception cref="ArgumentException">if the response is null</exception>
 public HttpServletResponseWrapper(IHttpServletResponse response)
     : base(response)
 {
 }