Ejemplo n.º 1
0
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                                      )
        {
            FileInputStream editFileIn = null;

            try
            {
                ServletContext context = GetServletContext();
                Configuration  conf    = (Configuration)GetServletContext().GetAttribute(JspHelper.CurrentConf
                                                                                         );
                string journalId = request.GetParameter(JournalIdParam);
                QuorumJournalManager.CheckJournalId(journalId);
                JNStorage storage = JournalNodeHttpServer.GetJournalFromContext(context, journalId
                                                                                ).GetStorage();
                // Check security
                if (!CheckRequestorOrSendError(conf, request, response))
                {
                    return;
                }
                // Check that the namespace info is correct
                if (!CheckStorageInfoOrSendError(storage, request, response))
                {
                    return;
                }
                long segmentTxId       = ServletUtil.ParseLongParam(request, SegmentTxidParam);
                FileJournalManager fjm = storage.GetJournalManager();
                FilePath           editFile;
                lock (fjm)
                {
                    // Synchronize on the FJM so that the file doesn't get finalized
                    // out from underneath us while we're in the process of opening
                    // it up.
                    FileJournalManager.EditLogFile elf = fjm.GetLogFile(segmentTxId);
                    if (elf == null)
                    {
                        response.SendError(HttpServletResponse.ScNotFound, "No edit log found starting at txid "
                                           + segmentTxId);
                        return;
                    }
                    editFile = elf.GetFile();
                    ImageServlet.SetVerificationHeadersForGet(response, editFile);
                    ImageServlet.SetFileNameHeaders(response, editFile);
                    editFileIn = new FileInputStream(editFile);
                }
                DataTransferThrottler throttler = ImageServlet.GetThrottler(conf);
                // send edits
                TransferFsImage.CopyFileToStream(response.GetOutputStream(), editFile, editFileIn
                                                 , throttler);
            }
            catch (Exception t)
            {
                string errMsg = "getedit failed. " + StringUtils.StringifyException(t);
                response.SendError(HttpServletResponse.ScInternalServerError, errMsg);
                throw new IOException(errMsg);
            }
            finally
            {
                IOUtils.CloseStream(editFileIn);
            }
        }
Ejemplo n.º 2
0
        protected override void doGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                var PathAndQuery = req.GetPathAndQuery().Substring(UrlPattern.Length);

                // not allowed to do so:
                // http://groups.google.com/group/google-appengine/browse_thread/thread/68a480cb7bec869e
                // http://www.ozelwebtasarim.com/index.php/google/10004-google-app-engine-java-utf-8-character-encoding-problem
                //resp.setHeader("Content-Encoding", "utf-8");

                if (PathAndQuery.Length > 1)
                {
                    resp.setContentType("text/html; charset=utf-8");
                    resp.getWriter().println(Launch(PathAndQuery.Substring(1)));
                }
                else
                {
                    resp.setContentType("text/html; charset=utf-8");
                    resp.getWriter().println(Launch(null));
                }
            }
            catch
            {
                // either swallow of throw a runtime exception
            }
        }
Ejemplo n.º 3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldSwallowAnyExceptionsThrownByTheRequest() throws java.io.IOException, javax.servlet.ServletException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldSwallowAnyExceptionsThrownByTheRequest()
        {
            HttpServletRequest request = mock(typeof(HttpServletRequest));

            when(request.getHeader(anyString())).thenThrow(new Exception());
            _filter.doFilter(request, null, _filterChain);
        }
Ejemplo n.º 4
0
		/// <summary>
		/// 校验Redis是否登录
		/// </summary>
		public virtual Visitor isLogin(HttpServletRequest request)
		{

			string xId = CookieUtils.getCookieValue(request, LoginConstant.XONE_COOKIE_NAME_STRING);

			if (!string.ReferenceEquals(xId, null))
			{

				Visitor visitor = (Visitor) redisCacheMgr.get(this.getRedisKey(xId));

				//
				// 登录了
				//
				if (visitor != null)
				{

					return visitor;

				}
				else
				{

					return null;
				}

			}
			else
			{

				return null;
			}
		}
Ejemplo n.º 5
0
        /// <summary>
        /// Enforces the content-type to be application/octet-stream for
        /// POST and PUT requests.
        /// </summary>
        /// <param name="request">servlet request.</param>
        /// <param name="response">servlet response.</param>
        /// <param name="chain">filter chain.</param>
        /// <exception cref="System.IO.IOException">thrown if an IO error occurrs.</exception>
        /// <exception cref="Javax.Servlet.ServletException">thrown if a servet error occurrs.
        ///     </exception>
        public virtual void DoFilter(ServletRequest request, ServletResponse response, FilterChain
                                     chain)
        {
            bool contentTypeOK          = true;
            HttpServletRequest  httpReq = (HttpServletRequest)request;
            HttpServletResponse httpRes = (HttpServletResponse)response;
            string method = httpReq.GetMethod();

            if (method.Equals("PUT") || method.Equals("POST"))
            {
                string op = httpReq.GetParameter(HttpFSFileSystem.OpParam);
                if (op != null && UploadOperations.Contains(StringUtils.ToUpperCase(op)))
                {
                    if (Sharpen.Runtime.EqualsIgnoreCase("true", httpReq.GetParameter(HttpFSParametersProvider.DataParam
                                                                                      .Name)))
                    {
                        string contentType = httpReq.GetContentType();
                        contentTypeOK = Sharpen.Runtime.EqualsIgnoreCase(HttpFSFileSystem.UploadContentType
                                                                         , contentType);
                    }
                }
            }
            if (contentTypeOK)
            {
                chain.DoFilter(httpReq, httpRes);
            }
            else
            {
                httpRes.SendError(HttpServletResponse.ScBadRequest, "Data upload requests must have content-type set to '"
                                  + HttpFSFileSystem.UploadContentType + "'");
            }
        }
Ejemplo n.º 6
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void doFilter(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse, javax.servlet.FilterChain chain) throws java.io.IOException, javax.servlet.ServletException
        public override void DoFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        {
            HttpServletRequest  request  = ( HttpServletRequest )servletRequest;
            HttpServletResponse response = ( HttpServletResponse )servletResponse;

            response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, _accessControlAllowOrigin);
            if (!string.ReferenceEquals(_vary, null))
            {
                response.setHeader(VARY, _vary);
            }

            IEnumerator <string> requestMethodEnumeration = request.getHeaders(ACCESS_CONTROL_REQUEST_METHOD);

            if (requestMethodEnumeration != null)
            {
                while (requestMethodEnumeration.MoveNext())
                {
                    string requestMethod = requestMethodEnumeration.Current;
                    AddAllowedMethodIfValid(requestMethod, response);
                }
            }

            IEnumerator <string> requestHeaderEnumeration = request.getHeaders(ACCESS_CONTROL_REQUEST_HEADERS);

            if (requestHeaderEnumeration != null)
            {
                while (requestHeaderEnumeration.MoveNext())
                {
                    string requestHeader = requestHeaderEnumeration.Current;
                    AddAllowedHeaderIfValid(requestHeader, response);
                }
            }

            chain.doFilter(request, response);
        }
Ejemplo n.º 7
0
 private void LogInstances(HttpServletRequest req, HttpServletResponse res, PrintWriter
                           @out)
 {
     Log.Info("request: {}", req);
     Log.Info("response: {}", res);
     Log.Info("writer: {}", @out);
 }
Ejemplo n.º 8
0
        /// <exception cref="System.IO.IOException"/>
        private bool CheckStorageInfoOrSendError(JNStorage storage, HttpServletRequest request
                                                 , HttpServletResponse response)
        {
            int    myNsId                 = storage.GetNamespaceID();
            string myClusterId            = storage.GetClusterID();
            string theirStorageInfoString = StringEscapeUtils.EscapeHtml(request.GetParameter
                                                                             (StorageinfoParam));

            if (theirStorageInfoString != null)
            {
                int theirNsId = StorageInfo.GetNsIdFromColonSeparatedString(theirStorageInfoString
                                                                            );
                string theirClusterId = StorageInfo.GetClusterIdFromColonSeparatedString(theirStorageInfoString
                                                                                         );
                if (myNsId != theirNsId || !myClusterId.Equals(theirClusterId))
                {
                    string msg = "This node has namespaceId '" + myNsId + " and clusterId '" + myClusterId
                                 + "' but the requesting node expected '" + theirNsId + "' and '" + theirClusterId
                                 + "'";
                    response.SendError(HttpServletResponse.ScForbidden, msg);
                    Log.Warn("Received an invalid request file transfer request from " + request.GetRemoteAddr
                                 () + ": " + msg);
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 9
0
        private static ServletRequest Request(string userAgent)
        {
            HttpServletRequest request = mock(typeof(HttpServletRequest));

            when(request.getHeader("User-Agent")).thenReturn(userAgent);
            return(request);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Authenticates a request looking for the <code>delegation</code>
        /// query-string parameter and verifying it is a valid token.
        /// </summary>
        /// <remarks>
        /// Authenticates a request looking for the <code>delegation</code>
        /// query-string parameter and verifying it is a valid token. If there is not
        /// <code>delegation</code> query-string parameter, it delegates the
        /// authentication to the
        /// <see cref="Org.Apache.Hadoop.Security.Authentication.Server.KerberosAuthenticationHandler
        ///     "/>
        /// unless it is
        /// disabled.
        /// </remarks>
        /// <param name="request">the HTTP client request.</param>
        /// <param name="response">the HTTP client response.</param>
        /// <returns>the authentication token for the authenticated request.</returns>
        /// <exception cref="System.IO.IOException">thrown if an IO error occurred.</exception>
        /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException
        ///     ">thrown if the authentication failed.</exception>
        public override AuthenticationToken Authenticate(HttpServletRequest request, HttpServletResponse
                                                         response)
        {
            AuthenticationToken token;
            string delegationParam = GetDelegationToken(request);

            if (delegationParam != null)
            {
                try
                {
                    Org.Apache.Hadoop.Security.Token.Token <AbstractDelegationTokenIdentifier> dt = new
                                                                                                    Org.Apache.Hadoop.Security.Token.Token();
                    dt.DecodeFromUrlString(delegationParam);
                    UserGroupInformation ugi = tokenManager.VerifyToken(dt);
                    string shortName         = ugi.GetShortUserName();
                    // creating a ephemeral token
                    token = new AuthenticationToken(shortName, ugi.GetUserName(), GetType());
                    token.SetExpires(0);
                    request.SetAttribute(DelegationTokenUgiAttribute, ugi);
                }
                catch (Exception ex)
                {
                    token = null;
                    HttpExceptionUtils.CreateServletExceptionResponse(response, HttpServletResponse.ScForbidden
                                                                      , new AuthenticationException(ex));
                }
            }
            else
            {
                token = authHandler.Authenticate(request, response);
            }
            return(token);
        }
Ejemplo n.º 11
0
        protected override void doPost(HttpServletRequest request, HttpServletResponse response)
        {
            request.setCharacterEncoding("Shift_JIS");
            response.setContentType("text/plain; charset=Shift_JIS");
            StreamWriter output = response.getWriter();

            foreach (Part part in request.getParts())
            {
                output.WriteLine("name.." + part.getName());
                foreach (String headerName in part.getHeaderNames())
                {
                    output.WriteLine(headerName + "=" + part.getHeader(headerName));
                }
                output.WriteLine("Content-Type.." + part.getContentType());
                output.WriteLine("Name.." + part.getName() + "/size.." + part.getSize());
                StreamReader reader = new StreamReader(part.getInputStream(), Encoding.GetEncoding("Shift_JIS"));
                int          ch;
                while ((ch = reader.Read()) >= 0)
                {
                    output.Write((char)(ch & 0xffff));
                }
                reader.Close();
                output.WriteLine("\n==================================");
            }
            output.WriteLine("text_name=" + request.getParameter("text_name"));
        }
        // http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control
        // http://board.flashkit.com/board/showthread.php?t=782484

        protected override void doGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                var p = req.GetPathAndQuery();

                if (p.Length > UrlPattern.Length + 1)
                {
                    p = p.Substring(UrlPattern.Length + 1);
                }
                else
                {
                    p = "";
                }

                if ("zip" == p)
                {
                    resp.setContentType(ZIPFile.ContentType);
                    resp.getOutputStream().write((sbyte[])(object)GetContent());
                    resp.getOutputStream().flush();
                }
                else
                {
                    resp.setContentType("text/html");
                    resp.getWriter().println(Launch(p));
                    resp.getWriter().flush();
                }
            }
            catch (csharp.ThrowableException ex)
            {
                // either swallow of throw a runtime exception

                ((java.lang.Throwable)(object) ex).printStackTrace();
            }
        }
        /// <exception cref="System.Exception"/>
        public virtual void TestRequestWithAuthorization()
        {
            string              token    = KerberosTestUtils.DoAsClient(new _Callable_225());
            HttpServletRequest  request  = Org.Mockito.Mockito.Mock <HttpServletRequest>();
            HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>();

            Org.Mockito.Mockito.When(request.GetHeader(KerberosAuthenticator.Authorization)).
            ThenReturn(KerberosAuthenticator.Negotiate + " " + token);
            Org.Mockito.Mockito.When(request.GetServerName()).ThenReturn("localhost");
            AuthenticationToken authToken = handler.Authenticate(request, response);

            if (authToken != null)
            {
                Org.Mockito.Mockito.Verify(response).SetHeader(Org.Mockito.Mockito.Eq(KerberosAuthenticator
                                                                                      .WwwAuthenticate), Org.Mockito.Mockito.Matches(KerberosAuthenticator.Negotiate +
                                                                                                                                     " .*"));
                Org.Mockito.Mockito.Verify(response).SetStatus(HttpServletResponse.ScOk);
                Assert.Equal(KerberosTestUtils.GetClientPrincipal(), authToken
                             .GetName());
                Assert.True(KerberosTestUtils.GetClientPrincipal().StartsWith(authToken
                                                                              .GetUserName()));
                Assert.Equal(GetExpectedType(), authToken.GetType());
            }
            else
            {
                Org.Mockito.Mockito.Verify(response).SetHeader(Org.Mockito.Mockito.Eq(KerberosAuthenticator
                                                                                      .WwwAuthenticate), Org.Mockito.Mockito.Matches(KerberosAuthenticator.Negotiate +
                                                                                                                                     " .*"));
                Org.Mockito.Mockito.Verify(response).SetStatus(HttpServletResponse.ScUnauthorized
                                                               );
            }
        }
Ejemplo n.º 14
0
        /// <exception cref="System.IO.IOException"/>
        private static UserGroupInformation GetTokenUGI(ServletContext context, HttpServletRequest
                                                        request, string tokenString, Configuration conf)
        {
            Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier> token = new Org.Apache.Hadoop.Security.Token.Token
                                                                                       <DelegationTokenIdentifier>();
            token.DecodeFromUrlString(tokenString);
            IPEndPoint serviceAddress = GetNNServiceAddress(context, request);

            if (serviceAddress != null)
            {
                SecurityUtil.SetTokenService(token, serviceAddress);
                token.SetKind(DelegationTokenIdentifier.HdfsDelegationKind);
            }
            ByteArrayInputStream      buf = new ByteArrayInputStream(token.GetIdentifier());
            DataInputStream           @in = new DataInputStream(buf);
            DelegationTokenIdentifier id  = new DelegationTokenIdentifier();

            id.ReadFields(@in);
            if (context != null)
            {
                NameNode nn = NameNodeHttpServer.GetNameNodeFromContext(context);
                if (nn != null)
                {
                    // Verify the token.
                    nn.GetNamesystem().VerifyToken(id, token.GetPassword());
                }
            }
            UserGroupInformation ugi = id.GetUser();

            ugi.AddToken(token);
            return(ugi);
        }
Ejemplo n.º 15
0
        /// <exception cref="System.Exception"/>
        private void _testUserName(bool anonymous)
        {
            PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler();

            try
            {
                Properties props = new Properties();
                props.SetProperty(PseudoAuthenticationHandler.AnonymousAllowed, bool.ToString(anonymous
                                                                                              ));
                handler.Init(props);
                HttpServletRequest  request  = Org.Mockito.Mockito.Mock <HttpServletRequest>();
                HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>();
                Org.Mockito.Mockito.When(request.GetQueryString()).ThenReturn(PseudoAuthenticator
                                                                              .UserName + "=" + "user");
                AuthenticationToken token = handler.Authenticate(request, response);
                NUnit.Framework.Assert.IsNotNull(token);
                Assert.Equal("user", token.GetUserName());
                Assert.Equal("user", token.GetName());
                Assert.Equal(PseudoAuthenticationHandler.Type, token.GetType()
                             );
            }
            finally
            {
                handler.Destroy();
            }
        }
        // http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control
        // http://board.flashkit.com/board/showthread.php?t=782484
        protected override void doGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                var p = req.GetPathAndQuery();

                if (p.Length > UrlPattern.Length + 1)
                    p = p.Substring(UrlPattern.Length + 1);
                else
                    p = "";

                if ("zip" == p)
                {
                    resp.setContentType(ZIPFile.ContentType);
                    resp.getOutputStream().write((sbyte[])(object)GetContent());
                    resp.getOutputStream().flush();
                }
                else
                {
                    resp.setContentType("text/html");
                    resp.getWriter().println(Launch(p));
                    resp.getWriter().flush();
                }
            }
            catch (csharp.ThrowableException ex)
            {
                // either swallow of throw a runtime exception

                ((java.lang.Throwable)(object)ex).printStackTrace();

            }
        }
Ejemplo n.º 17
0
        /// <summary>Get DFSClient for a namenode corresponding to the BPID from a datanode</summary>
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="System.Exception"/>
        public static DFSClient GetDFSClient(HttpServletRequest request, DataNode datanode
                                             , Configuration conf, UserGroupInformation ugi)
        {
            string nnAddr = request.GetParameter(JspHelper.NamenodeAddress);

            return(GetDFSClient(ugi, nnAddr, conf));
        }
Ejemplo n.º 18
0
 public _HttpServletRequestWrapper_269(DelegationTokenAuthenticationFilter _enclosing
                                       , UserGroupInformation ugiF, HttpServletRequest baseArg1)
     : base(baseArg1)
 {
     this._enclosing = _enclosing;
     this.ugiF       = ugiF;
 }
Ejemplo n.º 19
0
        public virtual void Mdc()
        {
            HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>();

            Org.Mockito.Mockito.When(request.GetUserPrincipal()).ThenReturn(null);
            Org.Mockito.Mockito.When(request.GetMethod()).ThenReturn("METHOD");
            Org.Mockito.Mockito.When(request.GetPathInfo()).ThenReturn("/pathinfo");
            ServletResponse response = Org.Mockito.Mockito.Mock <ServletResponse>();
            AtomicBoolean   invoked  = new AtomicBoolean();
            FilterChain     chain    = new _FilterChain_55(invoked);

            MDC.Clear();
            Filter filter = new MDCFilter();

            filter.Init(null);
            filter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.IsTrue(invoked.Get());
            NUnit.Framework.Assert.IsNull(MDC.Get("hostname"));
            NUnit.Framework.Assert.IsNull(MDC.Get("user"));
            NUnit.Framework.Assert.IsNull(MDC.Get("method"));
            NUnit.Framework.Assert.IsNull(MDC.Get("path"));
            Org.Mockito.Mockito.When(request.GetUserPrincipal()).ThenReturn(new _Principal_78
                                                                                ());
            invoked.Set(false);
            chain = new _FilterChain_86(invoked);
            filter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.IsTrue(invoked.Get());
            HostnameFilter.HostnameTl.Set("HOST");
            invoked.Set(false);
            chain = new _FilterChain_103(invoked);
            filter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.IsTrue(invoked.Get());
            HostnameFilter.HostnameTl.Remove();
            filter.Destroy();
        }
        protected override void doGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                var Path = req.getServletPath();
                var Query = req.getQueryString();
                var PathAndQuery = Path;
                if (Query != null)
                    PathAndQuery += "?" + Query;

                if (PathAndQuery != "/")
                {
                    //resp.setContentType("text/html");
                    //resp.getWriter().println(
                    resp.sendRedirect(
                        GetTinEyeVersion(GetPosterLink(PathAndQuery))
                        //.ToImage()
                    );
                }
                else
                {
                    resp.setContentType("text/html");
                    resp.getWriter().println(Launch(PathAndQuery));
                }
            }
            catch
            {
                // either swallow of throw a runtime exception
            }
        }
Ejemplo n.º 21
0
        private static HttpServletRequest ToLowerCase(HttpServletRequest request)
        {
            IDictionary <string, string[]> original = (IDictionary <string, string[]>)request.GetParameterMap
                                                          ();

            if (!ParamFilter.ContainsUpperCase(original.Keys))
            {
                return(request);
            }
            IDictionary <string, IList <string> > m = new Dictionary <string, IList <string> >();

            foreach (KeyValuePair <string, string[]> entry in original)
            {
                string         key     = StringUtils.ToLowerCase(entry.Key);
                IList <string> strings = m[key];
                if (strings == null)
                {
                    strings = new AList <string>();
                    m[key]  = strings;
                }
                foreach (string v in entry.Value)
                {
                    strings.AddItem(v);
                }
            }
            return(new _HttpServletRequestWrapper_111(m, request));
        }
Ejemplo n.º 22
0
        public static ClientConnectionInfo Create(HttpServletRequest request)
        {
            string        connectionId;
            string        protocol = request.Scheme;
            SocketAddress clientAddress;
            SocketAddress serverAddress;
            string        requestURI = request.RequestURI;

            JettyHttpConnection connection = JettyHttpConnection.CurrentJettyHttpConnection;

            if (connection != null)
            {
                connectionId  = connection.Id();
                clientAddress = connection.ClientAddress();
                serverAddress = connection.ServerAddress();
            }
            else
            {
                // connection is unknown, connection object can't be extracted or is missing from the Jetty thread-local
                // get all the available information directly from the request
                connectionId  = null;
                clientAddress = new InetSocketAddress(request.RemoteAddr, request.RemotePort);
                serverAddress = new InetSocketAddress(request.ServerName, request.ServerPort);
            }

            return(new HttpConnectionInfo(connectionId, protocol, clientAddress, serverAddress, requestURI));
        }
Ejemplo n.º 23
0
        protected override void doGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                var PathAndQuery = req.GetPathAndQuery().Substring(UrlPattern.Length);

                // not allowed to do so:
                // http://groups.google.com/group/google-appengine/browse_thread/thread/68a480cb7bec869e
                // http://www.ozelwebtasarim.com/index.php/google/10004-google-app-engine-java-utf-8-character-encoding-problem
                //resp.setHeader("Content-Encoding", "utf-8");

                if (PathAndQuery.Length > 1)
                {
                    resp.setContentType("text/html; charset=utf-8");
                    resp.getWriter().println(Launch(PathAndQuery.Substring(1)));
                }
                else
                {
                    resp.setContentType("text/html; charset=utf-8");
                    resp.getWriter().println(Launch(null));
                }
            }
            catch
            {
                // either swallow of throw a runtime exception
            }
        }
Ejemplo n.º 24
0
        /// <exception cref="System.Exception"/>
        public virtual void TestNonDefaultNonBrowserUserAgentAsBrowser()
        {
            HttpServletRequest  request  = Org.Mockito.Mockito.Mock <HttpServletRequest>();
            HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>();

            if (handler != null)
            {
                handler.Destroy();
                handler = null;
            }
            handler = GetNewAuthenticationHandler();
            Properties props = GetDefaultProperties();

            props.SetProperty("alt-kerberos.non-browser.user-agents", "foo, bar");
            try
            {
                handler.Init(props);
            }
            catch (Exception ex)
            {
                handler = null;
                throw;
            }
            // Pretend we're something that will not match with "foo" (or "bar")
            Org.Mockito.Mockito.When(request.GetHeader("User-Agent")).ThenReturn("blah");
            // Should use alt authentication
            AuthenticationToken token = handler.Authenticate(request, response);

            Assert.Equal("A", token.GetUserName());
            Assert.Equal("B", token.GetName());
            Assert.Equal(GetExpectedType(), token.GetType());
        }
Ejemplo n.º 25
0
        /// <exception cref="System.IO.IOException"/>
        private void ValidateRequest(ServletContext context, Configuration conf, HttpServletRequest
                                     request, HttpServletResponse response, FSImage nnImage, string theirStorageInfoString
                                     )
        {
            if (UserGroupInformation.IsSecurityEnabled() && !IsValidRequestor(context, request
                                                                              .GetUserPrincipal().GetName(), conf))
            {
                string errorMsg = "Only Namenode, Secondary Namenode, and administrators may access "
                                  + "this servlet";
                response.SendError(HttpServletResponse.ScForbidden, errorMsg);
                Log.Warn("Received non-NN/SNN/administrator request for image or edits from " + request
                         .GetUserPrincipal().GetName() + " at " + request.GetRemoteHost());
                throw new IOException(errorMsg);
            }
            string myStorageInfoString = nnImage.GetStorage().ToColonSeparatedString();

            if (theirStorageInfoString != null && !myStorageInfoString.Equals(theirStorageInfoString
                                                                              ))
            {
                string errorMsg = "This namenode has storage info " + myStorageInfoString + " but the secondary expected "
                                  + theirStorageInfoString;
                response.SendError(HttpServletResponse.ScForbidden, errorMsg);
                Log.Warn("Received an invalid request file transfer request " + "from a secondary with storage info "
                         + theirStorageInfoString);
                throw new IOException(errorMsg);
            }
        }
Ejemplo n.º 26
0
 public _PrivilegedExceptionAction_50(ContentSummaryServlet _enclosing, HttpServletRequest
                                      request, HttpServletResponse response)
 {
     this._enclosing = _enclosing;
     this.request    = request;
     this.response   = response;
 }
Ejemplo n.º 27
0
 /// <exception cref="Javax.Servlet.ServletException"/>
 /// <exception cref="System.IO.IOException"/>
 protected override void DoPut(HttpServletRequest request, HttpServletResponse response
                               )
 {
     try
     {
         ServletContext context = GetServletContext();
         FSImage        nnImage = NameNodeHttpServer.GetFsImageFromContext(context);
         Configuration  conf    = (Configuration)GetServletContext().GetAttribute(JspHelper.CurrentConf
                                                                                  );
         ImageServlet.PutImageParams parsedParams = new ImageServlet.PutImageParams(request
                                                                                    , response, conf);
         NameNodeMetrics metrics = NameNode.GetNameNodeMetrics();
         ValidateRequest(context, conf, request, response, nnImage, parsedParams.GetStorageInfoString
                             ());
         UserGroupInformation.GetCurrentUser().DoAs(new _PrivilegedExceptionAction_458(parsedParams
                                                                                       , nnImage, response, request, conf, metrics));
     }
     catch (Exception t)
     {
         // Metrics non-null only when used inside name node
         // Now that we have a new checkpoint, we might be able to
         // remove some old ones.
         string errMsg = "PutImage failed. " + StringUtils.StringifyException(t);
         response.SendError(HttpServletResponse.ScGone, errMsg);
         throw new IOException(errMsg);
     }
 }
        // http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control
        // http://board.flashkit.com/board/showthread.php?t=782484
        // http://www.adobe.com/devnet/flashplayer/articles/fplayer9_security_02.html
        protected override void doGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                resp.setContentType("text/x-cross-domain-policy");

                Console.WriteLine(UrlPattern);
                resp.getWriter().print(@"
            <?xml version=""1.0""?>
            <!DOCTYPE cross-domain-policy SYSTEM ""http://www.adobe.com/xml/dtds/cross-domain-policy.dtd"">
            <cross-domain-policy>
            <site-control permitted-cross-domain-policies=""all""/>
            <allow-access-from domain=""*"" secure=""false""/>
            <allow-http-request-headers-from domain=""*"" headers=""*"" secure=""false""/>
            </cross-domain-policy>
            ".Trim());

                resp.getWriter().flush();
            }
            catch (csharp.ThrowableException ex)
            {
                // either swallow of throw a runtime exception

                ((java.lang.Throwable)(object)ex).printStackTrace();

            }
        }
Ejemplo n.º 29
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void doFilter(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse, javax.servlet.FilterChain filterChain) throws java.io.IOException, javax.servlet.ServletException
        public override void DoFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        {
            ValidateRequestType(servletRequest);
            ValidateResponseType(servletResponse);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) servletRequest;
            HttpServletRequest request = ( HttpServletRequest )servletRequest;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) servletResponse;
            HttpServletResponse response = ( HttpServletResponse )servletResponse;

            try
            {
                LoginContext loginContext = AuthDisabledLoginContext;
                string       userAgent    = request.getHeader(HttpHeaders.USER_AGENT);

                JettyHttpConnection.updateUserForCurrentConnection(loginContext.Subject().username(), userAgent);

                filterChain.doFilter(new AuthorizedRequestWrapper(BASIC_AUTH, "neo4j", request, loginContext), servletResponse);
            }
            catch (AuthorizationViolationException e)
            {
                UnauthorizedAccess(e.Message).accept(response);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Get
        /// <see cref="Org.Apache.Hadoop.Security.UserGroupInformation"/>
        /// and possibly the delegation token out of
        /// the request.
        /// </summary>
        /// <param name="context">the ServletContext that is serving this request.</param>
        /// <param name="request">the http request</param>
        /// <param name="conf">configuration</param>
        /// <param name="secureAuthMethod">the AuthenticationMethod used in secure mode.</param>
        /// <param name="tryUgiParameter">Should it try the ugi parameter?</param>
        /// <returns>a new user from the request</returns>
        /// <exception cref="Org.Apache.Hadoop.Security.AccessControlException">if the request has no token
        ///     </exception>
        /// <exception cref="System.IO.IOException"/>
        public static UserGroupInformation GetUGI(ServletContext context, HttpServletRequest
                                                  request, Configuration conf, UserGroupInformation.AuthenticationMethod secureAuthMethod
                                                  , bool tryUgiParameter)
        {
            UserGroupInformation ugi = null;
            string usernameFromQuery = GetUsernameFromQuery(request, tryUgiParameter);
            string doAsUserFromQuery = request.GetParameter(DoAsParam.Name);
            string remoteUser;

            if (UserGroupInformation.IsSecurityEnabled())
            {
                remoteUser = request.GetRemoteUser();
                string tokenString = request.GetParameter(DelegationParameterName);
                if (tokenString != null)
                {
                    // Token-based connections need only verify the effective user, and
                    // disallow proxying to different user.  Proxy authorization checks
                    // are not required since the checks apply to issuing a token.
                    ugi = GetTokenUGI(context, request, tokenString, conf);
                    CheckUsername(ugi.GetShortUserName(), usernameFromQuery);
                    CheckUsername(ugi.GetShortUserName(), doAsUserFromQuery);
                }
                else
                {
                    if (remoteUser == null)
                    {
                        throw new IOException("Security enabled but user not authenticated by filter");
                    }
                }
            }
            else
            {
                // Security's not on, pull from url or use default web user
                remoteUser = (usernameFromQuery == null) ? GetDefaultWebUserName(conf) : usernameFromQuery;
            }
            // not specified in request
            if (ugi == null)
            {
                // security is off, or there's no token
                ugi = UserGroupInformation.CreateRemoteUser(remoteUser);
                CheckUsername(ugi.GetShortUserName(), usernameFromQuery);
                if (UserGroupInformation.IsSecurityEnabled())
                {
                    // This is not necessarily true, could have been auth'ed by user-facing
                    // filter
                    ugi.SetAuthenticationMethod(secureAuthMethod);
                }
                if (doAsUserFromQuery != null)
                {
                    // create and attempt to authorize a proxy user
                    ugi = UserGroupInformation.CreateProxyUser(doAsUserFromQuery, ugi);
                    ProxyUsers.Authorize(ugi, GetRemoteAddr(request));
                }
            }
            if (Log.IsDebugEnabled())
            {
                Log.Debug("getUGI is returning: " + ugi.GetShortUserName());
            }
            return(ugi);
        }
Ejemplo n.º 31
0
        public virtual AuthenticationResult extractAuthenticatedUser(HttpServletRequest request, ProcessEngine engine)
        {
            string authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);

            if (!string.ReferenceEquals(authorizationHeader, null) && authorizationHeader.StartsWith(BASIC_AUTH_HEADER_PREFIX, StringComparison.Ordinal))
            {
                string encodedCredentials = authorizationHeader.Substring(BASIC_AUTH_HEADER_PREFIX.Length);
                string decodedCredentials = StringHelper.NewString(Base64.decodeBase64(encodedCredentials));
                int    firstColonIndex    = decodedCredentials.IndexOf(":", StringComparison.Ordinal);

                if (firstColonIndex == -1)
                {
                    return(AuthenticationResult.unsuccessful());
                }
                else
                {
                    string userName = decodedCredentials.Substring(0, firstColonIndex);
                    string password = decodedCredentials.Substring(firstColonIndex + 1);
                    if (isAuthenticated(engine, userName, password))
                    {
                        return(AuthenticationResult.successful(userName));
                    }
                    else
                    {
                        return(AuthenticationResult.unsuccessful(userName));
                    }
                }
            }
            else
            {
                return(AuthenticationResult.unsuccessful());
            }
        }
Ejemplo n.º 32
0
        public virtual TasksInfo GetJobTasks(HttpServletRequest hsr, string jid, string type
                                             )
        {
            Init();
            Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job job = AMWebServices.GetJobFromJobIdString
                                                                 (jid, ctx);
            CheckAccess(job, hsr);
            TasksInfo allTasks = new TasksInfo();

            foreach (Task task in job.GetTasks().Values)
            {
                TaskType ttype = null;
                if (type != null && !type.IsEmpty())
                {
                    try
                    {
                        ttype = MRApps.TaskType(type);
                    }
                    catch (YarnRuntimeException)
                    {
                        throw new BadRequestException("tasktype must be either m or r");
                    }
                }
                if (ttype != null && task.GetType() != ttype)
                {
                    continue;
                }
                allTasks.Add(new TaskInfo(task));
            }
            return(allTasks);
        }
Ejemplo n.º 33
0
        public virtual TaskAttemptsInfo GetJobTaskAttempts(HttpServletRequest hsr, string
                                                           jid, string tid)
        {
            Init();
            TaskAttemptsInfo attempts = new TaskAttemptsInfo();

            Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job job = AMWebServices.GetJobFromJobIdString
                                                                 (jid, ctx);
            CheckAccess(job, hsr);
            Task task = AMWebServices.GetTaskFromTaskIdString(tid, job);

            foreach (TaskAttempt ta in task.GetAttempts().Values)
            {
                if (ta != null)
                {
                    if (task.GetType() == TaskType.Reduce)
                    {
                        attempts.Add(new ReduceTaskAttemptInfo(ta, task.GetType()));
                    }
                    else
                    {
                        attempts.Add(new TaskAttemptInfo(ta, task.GetType(), false));
                    }
                }
            }
            return(attempts);
        }
Ejemplo n.º 34
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void doFilter(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, javax.servlet.FilterChain chain) throws java.io.IOException, javax.servlet.ServletException
        public override void DoFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        {
            ValidateRequestType(request);
            ValidateResponseType(response);

            HttpServletRequest httpReq = ( HttpServletRequest )request;
            string             path    = httpReq.ContextPath + (httpReq.PathInfo == null ? "" : httpReq.PathInfo);

            bool requestIsForbidden = false;

            foreach (UriPathWildcardMatcher uriPathWildcardMatcher in _rules.Keys)
            {
                if (uriPathWildcardMatcher.Matches(path))
                {
                    HashSet <ForbiddingSecurityRule> securityRules = _rules[uriPathWildcardMatcher];
                    foreach (ForbiddingSecurityRule securityRule in securityRules)
                    {
                        // 401 on the first failed rule we come along
                        if (!securityRule.IsAuthorized(httpReq))
                        {
                            CreateUnauthorizedChallenge(response, securityRule);
                            return;
                        }
                        requestIsForbidden |= securityRule.IsForbidden(httpReq);
                    }
                }
            }
            if (requestIsForbidden)
            {
                CreateForbiddenResponse(response);
                return;
            }

            chain.doFilter(request, response);
        }
Ejemplo n.º 35
0
		public J2EEPrincipal(HttpServletRequest req)
		{
			_request = req;
			string authType = req.getAuthType();
			if (authType == null)
				authType = "";
			_identity = new GenericIdentity(req.getRemoteUser(), authType);
		}
Ejemplo n.º 36
0
		override protected void service(HttpServletRequest req, HttpServletResponse resp)
		{
			string servletPath = ServletIncludeUtils.getServletPath(req);
			TextWriter writer = (TextWriter)ServletIncludeUtils.getTextWriter(req);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(servletPath);
			HttpServletResponseWrapper wrapper = new AspxResponseWrapper(resp, writer);
			dispatcher.include(req, wrapper);
		}
Ejemplo n.º 37
0
		public ServletWorkerRequest (HttpServlet servlet, HttpServletRequest req, HttpServletResponse resp)
			: base (req.getContextPath(), req.getServletPath (), req.getRequestURI ()) {

			_HttpServlet = servlet;
			_HttpServletRequest = req;
			_HttpServletResponse = resp;

		}
Ejemplo n.º 38
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public void afterCompletion(javax.servlet.http.HttpServletRequest arg0, javax.servlet.http.HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception
		public override void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, object arg2, Exception arg3)
		{

			// 删除
			MDC.remove(SESSION_KEY);
			ThreadContext.removeSessionId();
			ThreadContext.clean();
		}
Ejemplo n.º 39
0
		override protected void service(HttpServletRequest req, HttpServletResponse resp)
		{
			resp.setHeader("X-Powered-By", "ASP.NET");
			resp.setHeader("X-AspNet-Version", "1.1.4322");

			String filename = getServletContext().getRealPath(req.getServletPath());
			ServletOutputStream hos;
			try {
				hos = resp.getOutputStream();
			}
			catch (java.lang.IllegalStateException e)
			{
				string mimeType = getServletContext().getMimeType(filename);
				if (mimeType == null || mimeType.StartsWith("text")) {
					sendFileUsingWriter(resp, filename);
					return;
				}
				else
					throw e;
			}
			try 
			{
				string mimeType = this.getServletContext().getMimeType(filename);
				if (mimeType == null)
					mimeType = "text/plain";
				
				resp.setContentType(mimeType);

				FileStream fis = null;
				try {
					fis = new FileStream(filename,FileMode.Open,FileAccess.Read);
					byte[] buf = new byte[4 * 1024];  // 4K buffer
					int bytesRead;
					while ((bytesRead = fis.Read(buf,0,buf.Length)) != -1 &&
						   bytesRead != 0) {
						hos.write(TypeUtils.ToSByteArray(buf), 0, bytesRead);
					}
				}
				finally {
					if (fis != null) fis.Close();
				}
			}
			catch (System.IO.FileNotFoundException e) 
			{
				resp.setStatus(404,"Object Not Found.");
				HttpException myExp = new HttpException (404, "File '" + filename + "' not found.");
				hos.print(((HttpException) myExp).GetHtmlErrorMessage ());
				hos.flush();
			}
			catch(Exception e) 
			{
				Trace.WriteLine (String.Format ("ERROR in Static File Reading {0},{1}", e.GetType (), e.Message));
				resp.setStatus(500);
				HttpException myExp = new HttpException ("Exception in Reading static file", e);
				hos.print(((HttpException) myExp).GetHtmlErrorMessage ());
				hos.flush();
			}
		}
Ejemplo n.º 40
0
		/// <summary>
		/// 自定义的全局错误
		/// </summary>
		/// <param name="request"> </param>
		/// <param name="response"> </param>
		/// <param name="message"> </param>
		/// <param name="errorCode">
		/// </param>
		/// <exception cref="IOException"> </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: protected void returnJsonSystemError(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, String message, com.baidu.dsp.common.constant.ErrorCode errorCode) throws java.io.IOException
		protected internal virtual void returnJsonSystemError(HttpServletRequest request, HttpServletResponse response, string message, ErrorCode errorCode)
		{

			JsonObjectBase jsonObjectBase = JsonObjectUtils.buildGlobalError(message, errorCode);

			response.setHeader("Cache-Control", "no-cache");
			response.ContentType = "application/json;charset=UTF-8";
			response.CharacterEncoding = "UTF-8";

			response.Writer.write(JsonUtils.toJson(jsonObjectBase));
		}
Ejemplo n.º 41
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception
		public override bool preHandle(HttpServletRequest request, HttpServletResponse response, object handler)
		{

			// 初始化会话
			ThreadContext.init();

			// 放SessionId
			string token = TokenUtil.generateToken();
			MDC.put(SESSION_KEY, token);
			ThreadContext.putSessionId(token);

			return true;
		}
Ejemplo n.º 42
0
		/// <summary>
		/// 校验Redis是否登录
		/// </summary>
		public virtual Visitor isLogin(HttpServletRequest request)
		{

			long? userId = 1L;

			User user = userMgr.getUser(userId);

			Visitor visitor = new Visitor();
			visitor.Id = userId;
			visitor.LoginUserId = userId;
			visitor.LoginUserName = user.Name;

			return visitor;
		}
Ejemplo n.º 43
0
		public virtual void login(HttpServletRequest request, User user, int expireTime)
		{

			Visitor visitor = new Visitor();

			visitor.Id = user.Id;
			visitor.LoginUserId = user.Id;
			visitor.LoginUserName = user.Name;

			//
			// 更新session
			//
			updateSessionVisitor(request.Session, visitor);
		}
        // level editor
        // - save locally
        // -- as cookie
        // -- to google gears
        // -- to file
        // - save to the bulldog system
        // -- description
        // -- preview
        // - upload new assets for custom levels (pay extra for storage to avoid spam)
        protected override void doGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                resp.sendRedirect(Link);
            }
            catch (csharp.ThrowableException ex)
            {
                // either swallow of throw a runtime exception

                ((java.lang.Throwable)(object)ex).printStackTrace();

            }
        }
        // http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control
        // http://board.flashkit.com/board/showthread.php?t=782484
        protected override void doGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                resp.setContentType("text/html");
                resp.getWriter().println(Launch(req.GetPathAndQuery()));
                resp.getWriter().flush();
            }
            catch (csharp.ThrowableException ex)
            {
                // either swallow of throw a runtime exception

                ((java.lang.Throwable)(object)ex).printStackTrace();

            }
        }
        // http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control
        // http://board.flashkit.com/board/showthread.php?t=782484
        protected override void doGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                resp.setContentType("application/rss+xml");

                resp.getWriter().print(GetContent());

                resp.getWriter().flush();
            }
            catch (csharp.ThrowableException ex)
            {
                // either swallow of throw a runtime exception

                ((java.lang.Throwable)(object)ex).printStackTrace();

            }
        }
        // http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control
        // http://board.flashkit.com/board/showthread.php?t=782484
        protected override void doGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                resp.setContentType(YAMLDocument.ContentType);

                resp.getWriter().print(GameReferenceExtensions.Default.ToYAML());

                resp.getWriter().flush();
            }
            catch (csharp.ThrowableException ex)
            {
                // either swallow of throw a runtime exception

                ((java.lang.Throwable)(object)ex).printStackTrace();

            }
        }
        // http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html#site-control
        // http://board.flashkit.com/board/showthread.php?t=782484
        protected override void doGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                resp.setContentType(ZIPFile.ContentType);

                resp.getOutputStream().write((sbyte[])(object)GetContent());

                resp.getOutputStream().flush();
            }
            catch (csharp.ThrowableException ex)
            {
                // either swallow of throw a runtime exception

                ((java.lang.Throwable)(object)ex).printStackTrace();

            }
        }
Ejemplo n.º 49
0
		public static string getIp(HttpServletRequest request)
		{
			if (null == request)
			{
				return null;
			}
			string ip = request.getHeader("x-forwarded-for");
			if (!validateIp(ip))
			{
				ip = request.getHeader("Proxy-Client-IP");
				if (!validateIp(ip))
				{
					ip = request.getHeader("WL-Proxy-Client-IP");
					if (!validateIp(ip))
					{
						ip = request.RemoteAddr;
					}
				}
			}
			return ip;
		}
Ejemplo n.º 50
0
		/// <summary>
		/// 登录
		/// </summary>
		public virtual void login(HttpServletRequest request, User user, int expireTime)
		{

			Visitor visitor = new Visitor();

			//
			//
			//
			visitor.Id = user.Id;
			visitor.LoginUserId = user.Id;
			visitor.LoginUserName = user.Name;
			visitor.RoleId = user.RoleId;
			visitor.setAppIds(user.OwnApps);

			//
			// 更新session
			//
			updateSessionVisitor(request.Session, visitor);

			//
			// 更新Redis数据
			//
			updateRedisVisitor(visitor, request, expireTime);
		}
Ejemplo n.º 51
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public void postHandle(javax.servlet.http.HttpServletRequest arg0, javax.servlet.http.HttpServletResponse arg1, Object arg2, org.springframework.web.servlet.ModelAndView arg3) throws Exception
		public override void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, object arg2, ModelAndView arg3)
		{
		}
Ejemplo n.º 52
0
		/// <summary>
		/// 登出
		/// </summary>
		/// <param name="request">
		/// 
		/// @return </param>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @NoAuth @RequestMapping(value = "/signout", method = org.springframework.web.bind.annotation.RequestMethod.GET) @ResponseBody public com.baidu.dsp.common.vo.JsonObjectBase signout(javax.servlet.http.HttpServletRequest request)
		public virtual JsonObjectBase signout(HttpServletRequest request)
		{

			redisLogin.logout(request);

			return buildSuccess("ok", "ok");
		}
Ejemplo n.º 53
0
		/// <summary>
		/// 登录
		/// </summary>
		/// <param name="signin"> </param>
		/// <param name="request">
		/// 
		/// @return </param>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @NoAuth @RequestMapping(value = "/signin", method = org.springframework.web.bind.annotation.RequestMethod.POST) @ResponseBody public com.baidu.dsp.common.vo.JsonObjectBase signin(@Valid com.baidu.disconf.web.service.sign.form.SigninForm signin, javax.servlet.http.HttpServletRequest request)
		public virtual JsonObjectBase signin(SigninForm signin, HttpServletRequest request)
		{

			LOG.info(signin.ToString());

			// 验证
			authValidator.validateLogin(signin);

			// 数据库登录
			User user = signMgr.signin(signin.Name);

			// 过期时间
			int expireTime = LoginConstant.SESSION_EXPIRE_TIME;
			if (signin.Remember.Equals(1))
			{
				expireTime = LoginConstant.SESSION_EXPIRE_TIME2;
			}

			// redis login
			redisLogin.login(request, user, expireTime);

			VisitorVo visitorVo = userMgr.CurVisitor;

			return buildSuccess("visitor", visitorVo);
		}
Ejemplo n.º 54
0
		protected override void service (HttpServletRequest req, HttpServletResponse resp)
		{
			const string assemblies = "/assemblies";
			const string getping = "getping";
			const string setping = "setping";
            const string version = "2.2";
			string servletPath = req.getServletPath ();

			if (String.CompareOrdinal (assemblies, 0, servletPath, 0, assemblies.Length) == 0) {
				if (servletPath.Length == assemblies.Length ||
						servletPath [assemblies.Length] == '/') {
					string requestURI = req.getRequestURI ();
					bool getp = requestURI.EndsWith (getping, StringComparison.Ordinal);
					if (!getp && requestURI.EndsWith (setping, StringComparison.Ordinal)) {
                        getServletContext().setAttribute(getping, version);
						getp = true;
					}

					if (getp) {
						string ping = (string) getServletContext ().getAttribute (getping);
						if (ping == null)
							ping = "0";
						resp.getOutputStream ().print (ping);
						return;
					}
				}
			}
			resp.setContentType ("text/html");

			try 
			{
				// Very important - to update Virtual Path!!!
				AppDomain servletDomain = (AppDomain)this.getServletContext().getAttribute(J2EEConsts.APP_DOMAIN);
				if (!_appVirDirInited) {
					string appVPath = req.getContextPath ();
					if (appVPath == null || appVPath.Length == 0)
						appVPath = "/";
					servletDomain.SetData (IAppDomainConfig.APP_VIRT_DIR, appVPath);
					servletDomain.SetData (".hostingVirtualPath", req.getContextPath ());
					_appVirDirInited = true;
				}

				// Put to the TLS current AppDomain of the servlet, so anyone can use it.
				[email protected](servletDomain);

				// put request to the TLS
				//Thread.SetData(_servletRequestSlot, req);
				//// put response to the TLS
				//Thread.SetData(_servletResponseSlot, resp);
				//// put the servlet object to the TLS
				//Thread.SetData(_servletSlot, this);

				resp.setHeader("X-Powered-By", "ASP.NET");
				resp.setHeader("X-AspNet-Version", "1.1.4322");

				HttpWorkerRequest gwr = new ServletWorkerRequest (this, req, resp);
				CultureInfo culture = (CultureInfo) [email protected] (req.getLocale ());
				Thread currentTread = Thread.CurrentThread;
				currentTread.CurrentCulture = culture;
				currentTread.CurrentUICulture = culture;
				HttpRuntime.ProcessRequest(gwr);
			}
			finally 
			{
				HttpContext.Current = null;
				//Thread.SetData(_servletRequestSlot, null);
				//Thread.SetData(_servletResponseSlot, null);
				//Thread.SetData(_servletSlot, null);
				[email protected]();
			}
		}
Ejemplo n.º 55
0
	override protected void service (HttpServletRequest req, HttpServletResponse resp) {
		string pathInfo = req.getRequestURI ();
		string contextPath = req.getContextPath ();
		if (pathInfo.Equals (contextPath) ||
			((pathInfo.Length - contextPath.Length) == 1) &&
			pathInfo [pathInfo.Length - 1] == '/' && pathInfo.StartsWith (contextPath))
			pathInfo = contextPath + req.getServletPath ();
		if (pathInfo.EndsWith (".aspx") ||
			pathInfo.EndsWith (".asmx") ||
			pathInfo.EndsWith (".invoke")) {
			base.service (req, resp);
		}
		else {
			staticServlet.service (req, resp);
		}
	}
 /// 
 /// <param name="resp"></param>
 /// <param name="req"></param>
 public override void _jspService(HttpServletResponse resp, HttpServletRequest req)
 {
 }
Ejemplo n.º 57
0
		/// <summary>
		/// 登出
		/// </summary>
		public virtual void logout(HttpServletRequest request)
		{

			// 更新session
			updateSessionVisitor(request.Session, null);

			// 更新redis
			updateRedisVisitor(null, request, 0);
		}
Ejemplo n.º 58
0
		/// <param name="visitor"> </param>
		private void updateRedisVisitor(Visitor visitor, HttpServletRequest request, int expireTime)
		{

			string xcookieName = CookieUtils.getCookieValue(request, LoginConstant.XONE_COOKIE_NAME_STRING);

			// 更新Redis数据
			if (!string.ReferenceEquals(xcookieName, null))
			{

				// 更新
				if (visitor != null)
				{

					redisCacheMgr.put(this.getRedisKey(xcookieName), expireTime, visitor);
				}
				else
				{

					// 删除
					redisCacheMgr.remove(this.getRedisKey(xcookieName));
				}
			}
		}
Ejemplo n.º 59
-1
        public JettyWebConnection(IWebServer webServer, String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
            : base(webServer, CallingFrom.Web)
        {
            Response = response;
            BaseRequest = baseRequest;
            Request = request;

            _RequestedFile = target;

            org.eclipse.jetty.io.EndPoint jettyEndpoint = baseRequest.getConnection().getEndPoint();
            string remoteAddress = jettyEndpoint.getRemoteAddr();
            int remotePort = jettyEndpoint.getRemotePort();

            _RemoteEndPoint = new IPEndPoint(IPAddress.Parse(remoteAddress), remotePort);
        }
Ejemplo n.º 60
-2
        /// <exception cref="System.Exception"/>
        private void Test(string method, string operation, string contentType, bool upload
                          , bool error)
        {
            HttpServletRequest  request  = Org.Mockito.Mockito.Mock <HttpServletRequest>();
            HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>();

            Org.Mockito.Mockito.Reset(request);
            Org.Mockito.Mockito.When(request.GetMethod()).ThenReturn(method);
            Org.Mockito.Mockito.When(request.GetParameter(HttpFSFileSystem.OpParam)).ThenReturn
                (operation);
            Org.Mockito.Mockito.When(request.GetParameter(HttpFSParametersProvider.DataParam.
                                                          Name)).ThenReturn(bool.ToString(upload));
            Org.Mockito.Mockito.When(request.GetContentType()).ThenReturn(contentType);
            FilterChain chain  = Org.Mockito.Mockito.Mock <FilterChain>();
            Filter      filter = new CheckUploadContentTypeFilter();

            filter.DoFilter(request, response, chain);
            if (error)
            {
                Org.Mockito.Mockito.Verify(response).SendError(Org.Mockito.Mockito.Eq(HttpServletResponse
                                                                                      .ScBadRequest), Org.Mockito.Mockito.Contains("Data upload"));
            }
            else
            {
                Org.Mockito.Mockito.Verify(chain).DoFilter(request, response);
            }
        }