org.eclipse.jetty.server.Handler类的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(13.7k)|赞(0)|评价(0)|浏览(209)

本文整理了Java中org.eclipse.jetty.server.Handler类的一些代码示例,展示了Handler类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Handler类的具体详情如下:
包路径:org.eclipse.jetty.server.Handler
类名称:Handler

Handler介绍

[英]A Jetty Server Handler.

A Handler instance is required by a Server to handle incoming HTTP requests.

A Handler may:

  • Completely generate the HTTP Response
  • Examine/modify the request and call another Handler (see HandlerWrapper).
  • Pass the request to one or more other Handlers (see HandlerCollection).
    Handlers are passed the servlet API request and response object, but are not Servlets. The servlet container is implemented by handlers for context, security, session and servlet that modify the request object before passing it to the next stage of handling.
    [中]Jetty服务器处理程序。
    服务器需要处理程序实例来处理传入的HTTP请求。
    处理人可以:
    *完全生成HTTP响应
    *检查/修改请求并调用另一个处理程序(请参见HandlerWrapper)。
    *将请求传递给一个或多个其他处理程序(请参见HandlerCollection)。
    处理程序被传递给servlet API请求和响应对象,但不是servlet。servlet容器由上下文、安全性、会话和servlet的处理程序实现,这些处理程序在将请求对象传递到下一个处理阶段之前修改请求对象。

代码示例

代码示例来源:origin: AsyncHttpClient/async-http-client

@Override
 public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  Handler handler = HttpServer.this.handlers.poll();
  if (handler == null) {
   response.sendError(500, "No handler enqueued");
   response.getOutputStream().flush();
   response.getOutputStream().close();
  } else {
   handler.handle(target, baseRequest, request, response);
  }
 }
}

代码示例来源:origin: gocd/gocd

@Before
public void setUp() throws Exception {
  initMocks(this);
  when(server.getThreadPool()).thenReturn(new QueuedThreadPool(1));
  Answer<Void> setHandlerMock = invocation -> {
    serverLevelHandler = (Handler) invocation.getArguments()[0];
    serverLevelHandler.setServer((Server) invocation.getMock());
    return null;
  };
  Mockito.doAnswer(setHandlerMock).when(server).setHandler(any(Handler.class));

代码示例来源:origin: igniterealtime/Openfire

/**
 * Removes a Jetty handler to be added to the embedded web server that is used to expose BOSH (HTTP-bind)
 * functionality.
 *
 * Removing a handler, even when null, or non-existing, might have side-effects as introduced by the Jetty
 * implementation. At the time of writing, Jetty will re
 *
 * @param handler The handler (should not be null).
 */
public void removeJettyHandler( Handler handler )
{
  if (handler instanceof WebAppContext) {
    // A work-around of the Jetty bug described at https://github.com/eclipse/jetty.project/issues/1425
    // NOTE: According to some comments on WebAppLoaderFix, this may stop working on Java 9.
    // Hopefully the Jetty team will have fixed the underlying bug by then
    WebAppLoaderFix.checkAndClose(((WebAppContext) handler).getClassLoader());
  }
  extensionHandlers.removeHandler( handler );
  if ( handler.isStarted() )
  {
    try
    {
      handler.stop();
    }
    catch ( Exception e )
    {
      Log.warn( "Unable to stop the handler that was removed: {}", handler, e );
    }
  }
}

代码示例来源:origin: igniterealtime/Openfire

/**
 * Adds a Jetty handler to be added to the embedded web server that is used to expose BOSH (HTTP-bind)
 * functionality.
 *
 * @param handler The handler (cannot be null).
 */
public void addJettyHandler( Handler handler )
{
  if ( handler == null )
  {
    throw new IllegalArgumentException( "Argument 'handler' cannot be null." );
  }
  extensionHandlers.addHandler( handler );
  if ( !handler.isStarted() && extensionHandlers.isStarted() )
  {
    try
    {
      handler.start();
    }
    catch ( Exception e )
    {
      Log.warn( "Unable to start handler {}", handler, e );
    }
  }
}

代码示例来源:origin: javaee/grizzly-ahc

@Override
  public void handle(String pathInContext, org.eclipse.jetty.server.Request request, HttpServletRequest httpRequest,
            HttpServletResponse httpResponse) throws IOException, ServletException {
    String authorization = httpRequest.getHeader("Authorization");
    if (authorization != null && authorization.equals("Basic dXNlcjpwYXNzd2Q="))
    {
      httpResponse.addHeader("target", request.getHttpURI().getPath());
      target.handle(pathInContext, request, httpRequest, httpResponse);
    }
    else
    {
      httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      httpResponse.setHeader("www-authenticate", "Basic realm=\"Fake Realm\"");
      httpResponse.getOutputStream().flush();
      httpResponse.getOutputStream().close();
      request.setHandled(true);
    }
  }
}

代码示例来源:origin: Codecademy/EventHub

@Override
public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
 Map<String, String[]> params = httpServletRequest.getParameterMap();
 if(params.containsKey("callback")) {
  OutputStream out = httpServletResponse.getOutputStream();
  GenericResponseWrapper wrapper = new GenericResponseWrapper(httpServletResponse);
  try {
   handler.handle(s, request, httpServletRequest, wrapper);
   if (httpServletResponse.getStatus() >= 400) {
    out.write((params.get("callback")[0] + "({error: 'error'});").getBytes());
   } else {
    out.write((params.get("callback")[0] + "(").getBytes());
    out.write(wrapper.getData());
    out.write(");".getBytes());
   }
   wrapper.setContentType("text/javascript;charset=UTF-8");
   out.close();
  } catch (Exception e) {
   out.write((params.get("callback")[0] + "({error: 'error'});").getBytes());
   wrapper.setContentType("text/javascript;charset=UTF-8");
   out.close();
   throw e;
  }
 } else {
  handler.handle(s, request, httpServletRequest, httpServletResponse);
 }
}

代码示例来源:origin: com.ovea.tajin.servers/tajin-server-jetty9

/**
 * Checks the incoming request against the whitelist and blacklist
 *
 * @see org.eclipse.jetty.server.handler.HandlerWrapper#handle(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
  // Get the real remote IP (not the one set by the forwarded headers (which may be forged))
  HttpChannel channel = baseRequest.getHttpChannel();
  if (channel!=null)
  {
    EndPoint endp=channel.getEndPoint();
    if (endp!=null)
    {
      InetSocketAddress address = endp.getRemoteAddress();
      if (address!=null && !isAddrUriAllowed(address.getHostString(),baseRequest.getPathInfo()))
      {
        response.sendError(HttpStatus.FORBIDDEN_403);
        baseRequest.setHandled(true);
        return;
      }
    }
  }
  getHandler().handle(target,baseRequest, request, response);
}

代码示例来源:origin: gocd/gocd

private MockResponse request(String target, String acceptHeaderValue) throws Exception {
  Request baseRequest = mock(Request.class);
  HttpFields httpFields = new HttpFields();
  if (acceptHeaderValue != null) {
    httpFields.add("Accept", acceptHeaderValue);
  }
  when(baseRequest.getHttpFields()).thenReturn(httpFields);
  HttpServletRequest servletRequest = mock(HttpServletRequest.class);
  HttpServletResponse servletResponse = mock(HttpServletResponse.class);
  PrintWriter printWriter = mock(PrintWriter.class);
  when(servletResponse.getWriter()).thenReturn(printWriter);
  handler.getHandler().handle(target, baseRequest, servletRequest, servletResponse);
  return new MockResponse(servletResponse, printWriter);
}

代码示例来源:origin: org.eclipse.jetty.aggregate/jetty-webapp

/**
 * Checks the incoming request against the whitelist and blacklist
 * 
 * @see org.eclipse.jetty.server.handler.HandlerWrapper#handle(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
  // Get the real remote IP (not the one set by the forwarded headers (which may be forged))
  AbstractHttpConnection connection = baseRequest.getConnection();
  if (connection!=null)
  {
    EndPoint endp=connection.getEndPoint();
    if (endp!=null)
    {
      String addr = endp.getRemoteAddr();
      if (addr!=null && !isAddrUriAllowed(addr,baseRequest.getPathInfo()))
      {
        response.sendError(HttpStatus.FORBIDDEN_403);
        baseRequest.setHandled(true);
        return;
      }
    }
  }
  
  getHandler().handle(target,baseRequest, request, response);
}

代码示例来源:origin: org.eclipse.jetty/jetty-security

@Override
public void handle(String pathInContext, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  final Response base_response = baseRequest.getResponse();
  final Handler handler=getHandler();
      if (!baseRequest.isHandled())
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        baseRequest.setHandled(true);
      if (!baseRequest.isHandled())
          if (!authorized)
        handler.handle(pathInContext, baseRequest, request, response);
        if (authenticator!=null)
          authenticator.secureResponse(request, response, isAuthMandatory, userAuth);
          handler.handle(pathInContext, baseRequest, request, response);
        if (_identityService!=null)
          previousIdentity = _identityService.associate(null);
        handler.handle(pathInContext, baseRequest, request, response);
        if (authenticator!=null)
          authenticator.secureResponse(request, response, isAuthMandatory, null);
    handler.handle(pathInContext, baseRequest, request, response);

代码示例来源:origin: com.yahoo.vespa/jdisc_http_service

@Override
public void handle(String path, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
  inFlight.incrementAndGet();
  /* The control flow logic here is mostly a copy from org.eclipse.jetty.server.handler.StatisticsHandler.handle(..) */
  try {
    Handler handler = getHandler();
    if (handler != null && shutdown.get() == null && isStarted()) {
      handler.handle(path, baseRequest, request, response);
    } else if (!baseRequest.isHandled()) {
      baseRequest.setHandled(true);
      response.sendError(HttpStatus.SERVICE_UNAVAILABLE_503);
    }
  } finally {
    HttpChannelState state = baseRequest.getHttpChannelState();
    if (state.isSuspended()) {
      if (state.isInitial()) {
        state.addListener(completionWatcher);
      }
    } else if (state.isInitial()) {
      observeEndOfRequest(baseRequest, response);
    }
  }
}

代码示例来源:origin: org.sonatype.nexus.restlight/nexus-restlight-test-harness

public void handle( final String target, final Request baseRequest,
          final HttpServletRequest request, final HttpServletResponse response )
  throws IOException, ServletException
{
  Logger logger = LoggerFactory.getLogger( ConversationalFixture.class );
  if ( conversation == null || conversation.isEmpty() )
  {
    logger.error( "Missing conversation." );
    response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "No conversation specified." );
    ((Request) request).setHandled( true );
  }
  else if ( conversation.size() <= conversationIndex )
  {
    logger.error( "Out of conversation elements. No conversation element at index: " + conversationIndex );
    response.sendError( HttpServletResponse.SC_NOT_IMPLEMENTED, "Out of conversation elements. No conversation element at index: " + conversationIndex );
    ((Request) request).setHandled( true );
  }
  else
  {
    RESTTestFixture fixture = conversation.get( conversationIndex++ );
    fixture.getTestHandler().handle( target, baseRequest, request, response );
    traversedConversation.add( fixture );
  }
}

代码示例来源:origin: org.eclipse.jetty/server

@Override
  public void destroy()
  {
    if (!isStopped())
      throw new IllegalStateException("!STOPPED");
    Handler[] children=getChildHandlers();
    setHandlers(null);
    for (Handler child: children)
      child.destroy();
    super.destroy();
  }
}

代码示例来源:origin: org.eclipse.jetty.aggregate/jetty-all-server

if (!_mutableWhenRunning && isStarted())
  throw new IllegalStateException(STARTED);
_handlers = handlers;
Server server = getServer();
MultiException mex = new MultiException();
for (int i=0;handlers!=null && i<handlers.length;i++)
  if (handlers[i].getServer()!=server)
    handlers[i].setServer(server);
if (getServer()!=null)
  getServer().getContainer().update(this, old_handlers, handlers, "handler");
      if (old_handlers[i].isStarted())
        old_handlers[i].stop();
      mex.add(e);
mex.ifExceptionThrowRuntime();

代码示例来源:origin: org.fabric3/fabric3-jetty

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    if (!request.isSecure()) {
      baseRequest.getResponse().sendRedirect("https://" + baseRequest.getServerName() + ":" + httpsPort + baseRequest.getPathInfo());
      baseRequest.setHandled(true);
    } else {
      getHandler().handle(target, baseRequest, request, response);
    }

  }
}

代码示例来源:origin: org.eclipse.jetty.aggregate/jetty-server

@Override
public void setServer(Server server)
{
  if (isStarted())
    throw new IllegalStateException(STARTED);
  
  Server old_server=getServer();
  
  super.setServer(server);
  Handler[] h=getHandlers();
  for (int i=0;h!=null && i<h.length;i++)
    h[i].setServer(server);
  
  if (server!=null && server!=old_server)
    server.getContainer().update(this, null,_handlers, "handler");
  
}

代码示例来源:origin: org.eclipse.jetty.aggregate/jetty-webapp

@Override
protected void doStop() throws Exception
{
  MultiException mex=new MultiException();
  try { super.doStop(); } catch(Throwable e){mex.add(e);}
  if (_handlers!=null)
  {
    for (int i=_handlers.length;i-->0;)
      try{_handlers[i].stop();}catch(Throwable e){mex.add(e);}
  }
  mex.ifExceptionThrow();
}

代码示例来源:origin: com.ovea.tajin.server/tajin-server-jetty9

/**
 * @param handlers The handlers to set.
 */
public void setHandlers(Handler[] handlers)
{
  if (!_mutableWhenRunning && isStarted())
    throw new IllegalStateException(STARTED);
  if (handlers!=null)
    for (Handler handler:handlers)
      if (handler.getServer()!=getServer())
        handler.setServer(getServer());
  
  updateBeans(_handlers, handlers);
  _handlers = handlers;
}

代码示例来源:origin: neo4j/neo4j

@Override
  public void handle( String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException
  {
    HttpChannel httpChannel = baseRequest.getHttpChannel();
    if ( httpChannel != null ) // if the channel is not null, all good, you handle yourself.
    {
      super.handle( target, baseRequest, request, response );
    }
    else // if we do not have a real channel, then we just log ourselves
    {
      try
      {
        if ( _handler != null )
        {
          _handler.handle( target, baseRequest, request, response );
        }
      }
      finally
      {
        RequestLog requestLog = getRequestLog();
        if ( requestLog != null && baseRequest.getDispatcherType() == DispatcherType.REQUEST )
        {
          requestLog.log( baseRequest, (Response) response );
        }
      }
    }
  }
}

代码示例来源:origin: dropwizard/dropwizard

@Override
public void handle(String target,
          Request baseRequest,
          HttpServletRequest request,
          HttpServletResponse response) throws IOException, ServletException {
  final Handler handler = handlers.getBest(baseRequest.getRequestURI());
  if (handler != null) {
    handler.handle(target, baseRequest, request, response);
  }
}

相关文章