org.apache.coyote.Request类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(13.8k)|赞(0)|评价(0)|浏览(159)

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

Request介绍

[英]This is a low-level, efficient representation of a server request. Most fields are GC-free, expensive operations are delayed until the user code needs the information. Processing is delegated to modules, using a hook mechanism. This class is not intended for user code - it is used internally by tomcat for processing the request in the most efficient way. Users ( servlets ) can access the information using a facade, which provides the high-level view of the request. Tomcat defines a number of attributes:

  • "org.apache.tomcat.request" - allows access to the low-level request object in trusted applications
    [中]这是服务器请求的低级别、高效表示。大多数字段都是无GC的,昂贵的操作会被延迟,直到用户代码需要这些信息。使用钩子机制将处理委托给模块。这个类不适用于用户代码——tomcat在内部使用它以最有效的方式处理请求。用户(servlet)可以使用facade访问信息,facade提供请求的高级视图。Tomcat定义了许多属性:
    *“org.apache.tomcat.request”-允许访问受信任应用程序中的低级请求对象

代码示例

代码示例来源:origin: line/armeria

@Nullable
private Request convertRequest(ServiceRequestContext ctx, AggregatedHttpMessage req) throws Throwable {
  final String mappedPath = ctx.mappedPath();
  final Request coyoteReq = new Request();
  coyoteReq.scheme().setString(req.scheme());
  coyoteReq.remoteAddr().setString(remoteAddr.getAddress().getHostAddress());
  coyoteReq.remoteHost().setString(remoteAddr.getHostString());
  coyoteReq.setRemotePort(remoteAddr.getPort());
  coyoteReq.localAddr().setString(localAddr.getAddress().getHostAddress());
  coyoteReq.localName().setString(hostName());
  coyoteReq.setLocalPort(localAddr.getPort());
    coyoteReq.serverName().setString(hostHeader);
  } else {
    coyoteReq.serverName().setString(hostHeader.substring(0, colonPos));
    try {
      final int port = Integer.parseInt(hostHeader.substring(colonPos + 1));
      coyoteReq.setServerPort(port);
    } catch (NumberFormatException e) {
  coyoteReq.method().setString(method.name());
  coyoteReq.requestURI().setBytes(uriBytes, 0, uriBytes.length);
    coyoteReq.queryString().setString(ctx.query());
  final MimeHeaders cHeaders = coyoteReq.getMimeHeaders();

代码示例来源:origin: org.apache.tomcat/tomcat-catalina

@Override
public void dispatch(ServletContext context, String path) {
  synchronized (asyncContextLock) {
    if (log.isDebugEnabled()) {
      logDebug("dispatch   ");
    if (dispatch != null) {
      throw new IllegalStateException(
          sm.getString("asyncContextImpl.dispatchingStarted"));
    if (request.getAttribute(ASYNC_REQUEST_URI)==null) {
      request.setAttribute(ASYNC_REQUEST_URI, request.getRequestURI());
      request.setAttribute(ASYNC_CONTEXT_PATH, request.getContextPath());
      request.setAttribute(ASYNC_SERVLET_PATH, request.getServletPath());
    if (!(requestDispatcher instanceof AsyncDispatcher)) {
      throw new UnsupportedOperationException(
          sm.getString("asyncContextImpl.noAsyncDispatcher"));
    this.dispatch = new AsyncRunnable(
        request, applicationDispatcher, servletRequest, servletResponse);
    this.request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCH, null);
    clearServletRequestResponse();

代码示例来源:origin: tomcat/catalina

ByteChunk uriBC = req.requestURI().getByteChunk();
int semicolon = uriBC.indexOf(match, 0, match.length(), 0);
  int start = uriBC.getStart();
  int end = uriBC.getEnd();
  int semicolon2 = uriBC.indexOf(';', sessionIdStart);
  if (semicolon2 >= 0) {
    request.setRequestedSessionId
      (new String(uriBC.getBuffer(), start + sessionIdStart, 
          semicolon2 - sessionIdStart));
    uriBC.setBytes(buf, start, end - start - semicolon2 + semicolon);
  } else {
    request.setRequestedSessionId
      (new String(uriBC.getBuffer(), start + sessionIdStart, 
          (end - start) - sessionIdStart));
    uriBC.setEnd(start + semicolon);
  request.setRequestedSessionURL(true);

代码示例来源:origin: org.ops4j.pax.tipi/org.ops4j.pax.tipi.tomcat-embed-core

final synchronized boolean onDataAvailable() {
  if (readInterest) {
    if (log.isDebugEnabled()) {
      log.debug(sm.getString("stream.inputBuffer.dispatch"));
    }
    readInterest = false;
    coyoteRequest.action(ActionCode.DISPATCH_READ, null);
    // Always need to dispatch since this thread is processing
    // the incoming connection and streams are processed on their
    // own.
    coyoteRequest.action(ActionCode.DISPATCH_EXECUTE, null);
    return true;
  } else {
    if (log.isDebugEnabled()) {
      log.debug(sm.getString("stream.inputBuffer.signal"));
    }
    synchronized (inBuffer) {
      inBuffer.notifyAll();
    }
    return false;
  }
}

代码示例来源:origin: codefollower/Tomcat-Research

@Override
public void complete() {
  if (log.isDebugEnabled()) {
    logDebug("complete   ");
  }
  check();
  request.getCoyoteRequest().action(ActionCode.COMMIT, null);
  request.getCoyoteRequest().action(ActionCode.ASYNC_COMPLETE, null);
  clearServletRequestResponse();
}

代码示例来源:origin: com.tomitribe.tribestream/tribestream-container

String password = null;
final MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization");
if (authorization != null) {
  authorization.toBytes();
  final ByteChunk authorizationBC = authorization.getByteChunk();
  if (authorizationBC.startsWithIgnoreCase("basic ", 0)) {
    authorizationBC.setOffset(authorizationBC.getOffset() + 6);
    final byte[] decoded = Base64.decodeBase64(authorizationBC.getBuffer(), authorizationBC.getOffset(), authorizationBC.getLength());
  final Principal principal = context.getRealm().authenticate(username, password);
  if (principal != null) {
    register(request, response, principal, HttpServletRequest.BASIC_AUTH, username, password);

代码示例来源:origin: org.apache.tomcat/tomcat-catalina

/**
 * Reject the request that was denied by this valve.
 * <p>If <code>invalidAuthenticationWhenDeny</code> is true
 * and the context has <code>preemptiveAuthentication</code>
 * set, set an invalid authorization header to trigger basic auth.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be processed
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
protected void denyRequest(Request request, Response response)
    throws IOException, ServletException {
  if (invalidAuthenticationWhenDeny) {
    Context context = request.getContext();
    if (context != null && context.getPreemptiveAuthentication()) {
      if (request.getCoyoteRequest().getMimeHeaders().getValue("authorization") == null) {
        request.getCoyoteRequest().getMimeHeaders().addValue("authorization").setString("invalid");
      }
      getNext().invoke(request, response);
      return;
    }
  }
  response.sendError(denyStatus);
}

代码示例来源:origin: org.apache.geronimo.modules/geronimo-tomcat6

request.getCoyoteRequest().getMimeHeaders()
.getValue("authorization");
authorization.toBytes();
ByteChunk authorizationBC = authorization.getByteChunk();
if (authorizationBC.startsWithIgnoreCase("basic ", 0)) {
  authorizationBC.setOffset(authorizationBC.getOffset() + 6);
  CharChunk authorizationCC = authorization.getCharChunk();
  Base64.decode(authorizationBC, authorizationCC);
try {
  MessageBytes authenticate =
      response.getCoyoteResponse().getMimeHeaders()
      .addValue(AUTHENTICATE_BYTES, 0, AUTHENTICATE_BYTES.length);
  CharChunk authenticateCC = authenticate.getCharChunk();
  authenticateCC.append("Basic realm=\"");

代码示例来源:origin: line/armeria

private static HttpHeaders convertResponse(Response coyoteRes) {
  final HttpHeaders headers = HttpHeaders.of(HttpStatus.valueOf(coyoteRes.getStatus()));
  final String contentType = coyoteRes.getContentType();
  if (contentType != null && !contentType.isEmpty()) {
    headers.set(HttpHeaderNames.CONTENT_TYPE, contentType);
  }
  final long contentLength = coyoteRes.getBytesWritten(true); // 'true' will trigger flush.
  final String method = coyoteRes.getRequest().method().toString();
  if (!"HEAD".equals(method)) {
    headers.setLong(HttpHeaderNames.CONTENT_LENGTH, contentLength);
  }
  final MimeHeaders cHeaders = coyoteRes.getMimeHeaders();
  final int numHeaders = cHeaders.size();
  for (int i = 0; i < numHeaders; i++) {
    final AsciiString name = toHeaderName(cHeaders.getName(i));
    if (name == null) {
      continue;
    }
    final String value = toHeaderValue(cHeaders.getValue(i));
    if (value == null) {
      continue;
    }
    headers.add(name.toLowerCase(), value);
  }
  return headers;
}

代码示例来源:origin: org.osivia.portal.core/osivia-portal-jbossas-jbossweb-lib

/*      */   public String getRemoteHost()
/*      */   {
/* 1181 */     if (this.remoteHost == null) {
/* 1182 */       if (!this.connector.getEnableLookups()) {
/* 1183 */         this.remoteHost = getRemoteAddr();
/*      */       } else {
/* 1185 */         this.coyoteRequest.action(ActionCode.ACTION_REQ_HOST_ATTRIBUTE, this.coyoteRequest);
/*      */ 
/* 1187 */         this.remoteHost = this.coyoteRequest.remoteHost().toString();
/*      */       }
/*      */     }
/* 1190 */     return this.remoteHost;
/*      */   }
/*      */

代码示例来源:origin: org.ops4j.pax.tipi/org.ops4j.pax.tipi.tomcat-embed-core

final boolean receivedEndOfHeaders() throws ConnectionException {
  if (coyoteRequest.method().isNull() || coyoteRequest.scheme().isNull() ||
      coyoteRequest.requestURI().isNull()) {
    throw new ConnectionException(sm.getString("stream.header.required",
        getConnectionId(), getIdentifier()), Http2Error.PROTOCOL_ERROR);
  }
  // Cookie headers need to be concatenated into a single header
  // See RFC 7540 8.1.2.5
  // Can only do this once the headers are fully received
  if (cookieHeader != null) {
    coyoteRequest.getMimeHeaders().addValue("cookie").setString(cookieHeader.toString());
  }
  return headerState == HEADER_STATE_REGULAR || headerState == HEADER_STATE_PSEUDO;
}

代码示例来源:origin: org.apache.tomcat/tomcat-catalina

/**
 * Check the configuration for aborted uploads and if configured to do so,
 * disable the swallowing of any remaining input and close the connection
 * once the response has been written.
 */
protected void checkSwallowInput() {
  Context context = getContext();
  if (context != null && !context.getSwallowAbortedUploads()) {
    coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null);
  }
}

代码示例来源:origin: codefollower/Tomcat-Research

/** Called by the processor before recycling the request. It'll collect
 * statistic information.
 */
void updateCounters() {
  bytesReceived+=req.getBytesRead();
  bytesSent+=req.getResponse().getContentWritten();
  requestCount++;
  if( req.getResponse().getStatus() >=400 )
    errorCount++;
  long t0=req.getStartTime();
  long t1=System.currentTimeMillis();
  long time=t1-t0;
  this.lastRequestProcessingTime = time;
  processingTime+=time;
  if( maxTime < time ) {
    maxTime=time;
    maxRequestUri=req.requestURI().toString();
  }
}

代码示例来源:origin: org.glassfish.metro/webservices-extra

/**
 * Intercept the request and decide if we cache the static resource. If the
 * static resource is already cached, return it.
 */
public int handle(Request req, int handlerCode) throws IOException{
  if (fileCache == null) return Handler.CONTINUE;
  
  if (handlerCode == Handler.RESPONSE_PROCEEDED && fileCache.isEnabled()){
    String docroot = SelectorThread.getWebAppRootPath();
    MessageBytes mb = req.requestURI();
    ByteChunk requestURI = mb.getByteChunk();
    String uri = req.requestURI().toString();                
    fileCache.add(FileCache.DEFAULT_SERVLET_NAME,docroot,uri,
           req.getResponse().getMimeHeaders(),false);        
  } else if (handlerCode == Handler.HEADERS_PARSED) {
    ByteChunk requestURI = req.requestURI().getByteChunk(); 
    if (fileCache.sendCache(requestURI.getBytes(), requestURI.getStart(),
              requestURI.getLength(), socketChannel,
              keepAlive(req))){
      return Handler.BREAK;   
    }
  }     
  return Handler.CONTINUE;
}

代码示例来源:origin: org.apache.tomcat/tomcat-catalina

public boolean timeout() {
  AtomicBoolean result = new AtomicBoolean();
  request.getCoyoteRequest().action(ActionCode.ASYNC_TIMEOUT, result);
  // Avoids NPEs during shutdown. A call to recycle will null this field.
  Context context = this.context;
  if (result.get()) {
    ClassLoader oldCL = context.bind(false, null);
    try {
      List<AsyncListenerWrapper> listenersCopy = new ArrayList<>();
      listenersCopy.addAll(listeners);
      for (AsyncListenerWrapper listener : listenersCopy) {
        try {
          listener.fireOnTimeout(event);
        } catch (Throwable t) {
          ExceptionUtils.handleThrowable(t);
          log.warn(sm.getString("asyncContextImpl.onTimeoutError",
              listener.getClass().getName()), t);
        }
      }
      request.getCoyoteRequest().action(
          ActionCode.ASYNC_IS_TIMINGOUT, result);
    } finally {
      context.unbind(false, oldCL);
    }
  }
  return !result.get();
}

代码示例来源:origin: org.apache.tomcat/tomcat-catalina

/**
 * @return the remote IP address making this Request.
 */
@Override
public String getRemoteAddr() {
  if (remoteAddr == null) {
    coyoteRequest.action
      (ActionCode.REQ_HOST_ADDR_ATTRIBUTE, coyoteRequest);
    remoteAddr = coyoteRequest.remoteAddr().toString();
  }
  return remoteAddr;
}

代码示例来源:origin: tomcat/catalina

/**
 * Returns the Internet Protocol (IP) address of the interface on
 * which the request  was received.
 */       
public String getLocalAddr(){
  if (localAddr == null) {
    coyoteRequest.action
      (ActionCode.ACTION_REQ_LOCAL_ADDR_ATTRIBUTE, coyoteRequest);
    localAddr = coyoteRequest.localAddr().toString();
  }
  return localAddr;    
}

代码示例来源:origin: org.apache.tomcat/tomcat-catalina

public void setStarted(Context context, ServletRequest request,
    ServletResponse response, boolean originalRequestResponse) {
  synchronized (asyncContextLock) {
    this.request.getCoyoteRequest().action(
        ActionCode.ASYNC_START, this);
    this.context = context;
    this.servletRequest = request;
    this.servletResponse = response;
    this.hasOriginalRequestAndResponse = originalRequestResponse;
    this.event = new AsyncEvent(this, request, response);
    List<AsyncListenerWrapper> listenersCopy = new ArrayList<>();
    listenersCopy.addAll(listeners);
    listeners.clear();
    for (AsyncListenerWrapper listener : listenersCopy) {
      try {
        listener.fireOnStartAsync(event);
      } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        log.warn(sm.getString("asyncContextImpl.onStartAsyncError",
            listener.getClass().getName()), t);
      }
    }
  }
}

代码示例来源:origin: org.jboss.web/jbossweb

/** Called by the processor before recycling the request. It'll collect
 * statistic information.
 */
void updateCounters() {
  bytesReceived+=req.getBytesRead();
  bytesSent+=req.getResponse().getBytesWritten();
  requestCount++;
  if( req.getResponse().getStatus() >=400 )
    errorCount++;
  long t0=req.getStartTime();
  long t1=System.currentTimeMillis();
  long time=t1-t0;
  this.lastRequestProcessingTime = time;
  processingTime+=time;
  if( maxTime < time ) {
    maxTime=time;
    maxRequestUri=req.requestURI().toString();
  }
}

代码示例来源:origin: jboss.remoting/jboss-remoting

private void populateRequestMetadata(RequestMap metadata, Request req)
{
 MimeHeaders headers = req.getMimeHeaders();
 Enumeration nameEnum = headers.names();
 while (nameEnum.hasMoreElements())
 {
   Object nameObj = nameEnum.nextElement();
   if (nameObj instanceof String)
   {
    Object valueObj = headers.getHeader((String) nameObj);
    metadata.put(nameObj, valueObj);
   }
 }
 metadata.put(HTTPMetadataConstants.METHODTYPE, req.method().getString());
 metadata.put(HTTPMetadataConstants.PATH, req.requestURI().getString());
 metadata.put(HTTPMetadataConstants.HTTPVERSION, req.protocol().getString());
}

相关文章

微信公众号

最新文章

更多

Request类方法