/* (non-Javadoc)
@see info.magnolia.cms.security.auth.login.LoginHandler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
545792
@Override
	public LoginResult handle(HttpServletRequest request, HttpServletResponse response) {
		String userName = request.getRemoteUser();
		if (userName != null && userName.trim().length() > 0) {
			LoginResult result;
			ContainerPreAuthCallbackHandler callbackHandler = new ContainerPreAuthCallbackHandler(userName);
			result = authenticate(callbackHandler, null);
			//result = new LoginResult(LoginResult.STATUS_SUCCEEDED);
			logger.debug("handle() called for user '" + userName 
					+ "', LoginResult.statues=" + result.getStatus() 
					+ ", LoginResult.subject=" + result.getSubject());
			
			/*
			logger.debug("using PlainTextCallbackHandler");
			CredentialsCallbackHandler callbackHandler2 = new PlainTextCallbackHandler(userName, "Test123Test".toCharArray());
			authenticate(callbackHandler2, SecuritySupportBase.DEFAULT_JAAS_LOGIN_CHAIN);
			LoginResult result = new LoginResult(LoginResult.STATUS_SUCCEEDED);
			*/
			return result;
		}else{
			logger.debug("handle() called but the user has not been authenticated by the container.");
		}
		return LoginResult.NOT_HANDLED;
	}
4185
@Override
  public Response handle() throws Exception {
    StatusGenerator gen = new StatusGenerator(getServer());


    JSONObject res = gen.generate();

    List<ServerSideSession> sessions = getServer().getSessions();
    Response resp = new Response();

    resp.setStatus(0);
    resp.setValue(res);
    if (sessions.size() == 0) {
      resp.setSessionId(null);
    } else if (sessions.size() == 1) {
      resp.setSessionId(sessions.get(0).getSessionId());
    } else {
      throw new WebDriverException("NI multi sessions per server.");
    }
    return resp;
  }
1259529
@Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response) {
        handleRequest(request, response, null, null, false);
    }
738254
protected void handle(HttpConnection httpConnection) throws IOException {
		try {
			getServerThread().handleIncomingHttp(httpConnection);
			httpConnection.waitForResponse();
		}
		catch (ConnectException ex) {
			httpConnection.respond(HttpStatus.GONE);
		}
	}
1176148
public void handleResponse(String response) {
        if (messageListener != null) {
            log.debug("Sending Http response");
            messageListener.onOutboundMessage(new RawMessage(response), null);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Sending Http response:" + NEWLINE + response);
            }
        }
    }
844070
public void handle(ServerHttpRequest request, ServerHttpResponse response)
			throws IOException {
		try {
			Assert.state(request.getHeaders().getContentLength() > 0, "No content");
			ObjectInputStream objectInputStream = new ObjectInputStream(
					request.getBody());
			ClassLoaderFiles files = (ClassLoaderFiles) objectInputStream.readObject();
			objectInputStream.close();
			this.server.updateAndRestart(files);
			response.setStatusCode(HttpStatus.OK);
		}
		catch (Exception ex) {
			logger.warn("Unable to handler restart server HTTP request", ex);
			response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
47298
private void handle(final Request request, final Response response, final List<Middleware> middlewares) throws Exception {
		if (middlewares.isEmpty()) {
			throw new NotFoundException();
		}
		
		Middleware current = middlewares.remove(0);
		current.handle(request, response, new MiddlewareChain() {
			@Override
			public void next() throws Exception {
				// recursive call
				handle(request, response, middlewares);
			}
		});
	}
81943
protected void processRequest( HttpServletRequest request,
                                   HttpServletResponse response ) throws ServletException, IOException {
        String authHeader = ((HttpServletRequest)request).getHeader("Authorization");
        String pathInfo= request.getPathInfo();
        
        Object marker = request.getSession().getAttribute("login-required-marker");
        
        if (marker == null && pathInfo.equals("login.do")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.addHeader("WWW-Authenticate", "Basic realm =\"Realm\"");
            request.getSession().setAttribute("login-required-marker", Boolean.FALSE);
            return;
        }

        if (pathInfo.equals("login.do")) {
            response.sendRedirect(request.getContextPath() + "/Console.html");
            return;
        }
        
        String url = request.getRequestURI();
        String servletPath = request.getServletPath();

        request.getSession(true).setAttribute("initial.uri", url);
        logger.debug("Store requested uri " + url);
        
        String dest = url.substring(0, url.indexOf(servletPath));
        response.sendRedirect(dest);
    }
1144986
public void handleGet(HttpRequest request, HttpResponse response) throws HttpException, IOException {
        String uri = request.getRequestLine().getUri();
        LOG.debug("uri {}", uri);
        try {
            ResponseUpdater ru = this.findResponseUpdater(request);
            LOG.debug("request updater {}", ru);
            ru.update(response);
        } catch (IllegalStateException t) {
            LOG.error("Cannot handle request", t);
            throw new HttpException("Cannot handle request", t);
        }
    }
188882
public void handle(String pathInContext, String pathParams, HttpRequest request,
            HttpResponse response) throws HttpException, IOException
    {

        // exempt error pages
        // TODO This probably should be more general?
        if (request.getAttribute("javax.servlet.error.status_code") != null) return;

        try
        {

            String ip = request.getRemoteAddr();
            boolean authorized = checkIP(ip);

            if (!authorized)
            {
                // The IP is NOT allowed
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }
            else
            {
                // The IP is allowed
                return;
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex);
            response.sendError(HttpResponse.__500_Internal_Server_Error);
            request.setHandled(true);
        }
    }
1074865
@Override
    public void handle(WebContext webContext) throws Exception {
        Request request = webContext.getRequest();

        ChannelHandlerContext ctx = webContext.getChannelHandlerContext();

        if (!HttpConst.METHOD_GET.equals(request.method())) {
            sendError(ctx, METHOD_NOT_ALLOWED);
            return;
        }

        Instant start = Instant.now();

        String uri      = URLDecoder.decode(request.uri(), "UTF-8");
        String method   = StringKit.padRight(request.method(), 6);
        String cleanURL = getCleanURL(request, uri);

        // webjars
        if (cleanURL.startsWith(Const.WEB_JARS)) {
            InputStream input = getResourceStreamFromJar(uri);
            writeWithJarFile(request, ctx, uri, start, cleanURL, method, input);
            return;
        }

        // jar file
        if (BladeKit.runtimeIsJAR()) {
            InputStream input = StaticFileHandler.class.getResourceAsStream(cleanURL);
            writeWithJarFile(request, ctx, uri, start, cleanURL, method, input);
            return;
        }

        // disk file
        final String path = sanitizeUri(cleanURL);
        if (path == null) {
            log403(log, method, uri);
            throw new ForbiddenException();
        }

        File file = new File(path);
        if (file.isHidden() || !file.exists()) {
            // gradle resources path
            File resourcesDirectory = getGradleResourcesDirectory();
            if (resourcesDirectory.isDirectory()) {
                file = new File(resourcesDirectory.getPath() + "/" + cleanURL.substring(1));
                if (file.isHidden() || !file.exists()) {
                    throw new NotFoundException(uri);
                }
            } else {
                throw new NotFoundException(uri);
            }
        }

        if (file.isDirectory() && showFileList) {
            sendListing(ctx, uri, getFileMetas(file), cleanURL);
            return;
        }

        if (!file.isFile()) {
            sendError(ctx, FORBIDDEN);
            return;
        }

        // Cache Validation
        if (isHttp304(ctx, request, file.length(), file.lastModified())) {
            log304(log, method, uri);
            return;
        }

        HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        setContentTypeHeader(httpResponse, file);
        setDateAndCacheHeaders(httpResponse, file);

        if (request.useGZIP()) {
            File output = new File(file.getPath() + ".gz");
            IOKit.compressGZIP(file, output);
            file = output;
            setGzip(httpResponse);
        }

        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "r");
        } catch (FileNotFoundException ignore) {
            sendError(ctx, NOT_FOUND);
            return;
        }

        long fileLength = raf.length();

        httpResponse.headers().set(HttpConst.CONTENT_LENGTH, fileLength);
        if (request.keepAlive()) {
            httpResponse.headers().set(HttpConst.CONNECTION, HttpConst.KEEP_ALIVE);
        }

        // Write the initial line and the header.
        ctx.write(httpResponse);

        // Write the content.
        ChannelFuture sendFileFuture;
        ChannelFuture lastContentFuture;
        if (ctx.pipeline().get(SslHandler.class) == null) {
            sendFileFuture = ctx.write(
                    new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                    ctx.newProgressivePromise()
            );

            // Write the end marker.
            lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

        } else {
            sendFileFuture = ctx.writeAndFlush(
                    new HttpChunkedInput(
                            new ChunkedFile(raf, 0, fileLength, 8192)
                    ),
                    ctx.newProgressivePromise());
            // HttpChunkedInput will write the end marker (LastHttpContent) for us.
            lastContentFuture = sendFileFuture;
        }

        sendFileFuture.addListener(ProgressiveFutureListener.build(raf));

        // Decide whether to close the connection or not.
        if (!request.keepAlive()) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
        log200AndCost(log, start, method, uri);
    }
1144849
public void handle(ResourceRequest request, ResourceResponse response) throws IOException {
		logger.debug("Handing ResourceRequest {}", request.getMethod());
		response.setContentType(contentType);
		InputStream input = getRequestStream(request);
		OutputStream output = response.getPortletOutputStream();
		handleRequest(input, output);
		// fix to not flush within handleRequest() but outside so http status code can be set
		output.flush();
	}
564613
@Override
    public void handle(RequestContext context) throws SecurityProviderException, IOException {
        RedirectUtils.redirect(context.getRequest(), context.getResponse(), getTargetUrl());
    }
718041
public void handleConnect(HttpServletRequest request,
                              HttpServletResponse response)
        throws IOException
    {
        String uri = request.getRequestURI();
        
        context.log("CONNECT: "+uri);
        
        InetAddrPort addrPort=new InetAddrPort(uri);
        
        //if (isForbidden(HttpMessage.__SSL_SCHEME,addrPort.getHost(),addrPort.getPort(),false))
        //{
        //    sendForbid(request,response,uri);
        //}
        //else
        {
            InputStream in=request.getInputStream();
            OutputStream out=response.getOutputStream();
            
            Socket socket = new Socket(addrPort.getInetAddress(),addrPort.getPort());
            context.log("Socket: "+socket);
            
            response.setStatus(200);
            response.setHeader("Connection","close");
            response.flushBuffer();
            
            System.err.println(response);

            context.log("out<-in");
            IO.copyThread(socket.getInputStream(),out);
            context.log("in->out");
            IO.copy(in,socket.getOutputStream());
        }
    }
1063849
protected void handle(Authentication authentication) throws IOException, ServletException {
        HttpServletRequest request = http.getCurrentRequest();
        HttpServletResponse response = http.getCurrentResponse();
        String targetUrl = determineTargetUrl(request, response);

        if (response.isCommitted()) {
            logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
            return;
        } else {
            logger.debug("Redirecting to " + targetUrl);
        }

        redirectStrategy.sendRedirect(targetUrl);
    }
745668
@Override
    public void handle(CommandContext ctx, String commandLine) {
        // TODO Validate command

        if (commandLine.contains("--help")) {
            this.printHelp(commandLine, ctx);
            return;
        }

        String[] commands = commandLine.split(" ");

        if (commands.length == 1) {
            ctx.connectController(null, -1);
        } else if (commands.length == 2) {
            if (commandLine.contains("--help")) {
                this.printHelp("help/connect.txt", ctx);
                return;
            }
        } else if (commands.length == 3) {
            String host = commands[1];
            try {
                int port = Integer.parseInt(commands[2]);
                ctx.connectController(host, port);
            } catch (NumberFormatException ne) {
                ctx.printLine("Port must be from 1 to 65535");
            }

        } else {
            ctx.printLine("Invalid command.");
        }

    }
995713
void handle() throws IOException {
        if (null == handler) {
            println("Command not recognized: %s", command());
            return;
        }
        if (handler == Exit.INSTANCE) {
            handler.handle(this);
        }
        CommandLineParser parser = commandLine();
        boolean help = parser.getBoolean("-h", "--help");
        if (help) {
            Help.INSTANCE.showHelp(parser.command(), this);
        } else {
            try {
                session.handler(handler);
                handler.handle(this);
            } catch ($.Break b) {
                throw b;
            } catch (Exception e) {
                console.println("Error: " + e.getMessage());
            }
        }
    }