Java Code Examples for io.netty.handler.codec.http.multipart.HttpPostRequestDecoder#isMultipart()

The following examples show how to use io.netty.handler.codec.http.multipart.HttpPostRequestDecoder#isMultipart() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RequestInfoImpl.java    From riposte with Apache License 2.0 6 votes vote down vote up
public RequestInfoImpl(@NotNull HttpRequest request) {
    this(
        request.uri(),
        request.method(),
        request.headers(),
        HttpUtils.extractTrailingHeadersIfPossible(request),
        null,
        HttpUtils.extractCookies(request),
        null,
        HttpUtils.extractContentChunks(request),
        request.protocolVersion(),
        HttpUtil.isKeepAlive(request),
        (request instanceof FullHttpRequest),
        HttpPostRequestDecoder.isMultipart(request)
    );
}
 
Example 2
Source File: ServletNettyChannelHandler.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
void copyHttpBodyData(FullHttpRequest fullHttpReq, MockHttpServletRequest servletRequest){
	ByteBuf bbContent = fullHttpReq.content();	
	
	if(bbContent.hasArray()) {				
		servletRequest.setContent(bbContent.array());
	} else {			
		if(fullHttpReq.getMethod().equals(HttpMethod.POST)){
			HttpPostRequestDecoder decoderPostData  = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), fullHttpReq);
			String bbContentStr = bbContent.toString(Charset.forName(UTF_8));
			servletRequest.setContent(bbContentStr.getBytes());
			if( ! decoderPostData.isMultipart() ){
				List<InterfaceHttpData> postDatas = decoderPostData.getBodyHttpDatas();
				for (InterfaceHttpData postData : postDatas) {
					if (postData.getHttpDataType() == HttpDataType.Attribute) {
						Attribute attribute = (Attribute) postData;
						try {											
							servletRequest.addParameter(attribute.getName(),attribute.getValue());
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}	
			}
		}			
	}	
}
 
Example 3
Source File: HttpRequest.java    From blade with Apache License 2.0 4 votes vote down vote up
public void init(String remoteAddress) {
    this.remoteAddress = remoteAddress.substring(1);
    this.keepAlive = HttpUtil.isKeepAlive(nettyRequest);
    this.url = nettyRequest.uri();

    int pathEndPos = this.url().indexOf('?');
    this.uri = pathEndPos < 0 ? this.url() : this.url().substring(0, pathEndPos);
    this.protocol = nettyRequest.protocolVersion().text();
    this.method = nettyRequest.method().name();

    String cleanUri = this.uri;
    if (!"/".equals(this.contextPath())) {
        cleanUri = PathKit.cleanPath(cleanUri.replaceFirst(this.contextPath(), "/"));
        this.uri = cleanUri;
    }

    this.httpHeaders = nettyRequest.headers();

    if (!HttpServerHandler.PERFORMANCE) {
        SessionManager sessionManager = WebContext.blade().sessionManager();
        if (null != sessionManager) {
            this.session = SESSION_HANDLER.createSession(this);
        }
    }

    if ("GET".equals(this.method())) {
        return;
    }

    try {
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(HTTP_DATA_FACTORY, nettyRequest);
        this.isMultipart = decoder.isMultipart();

        List<ByteBuf> byteBuffs = new ArrayList<>(this.contents.size());

        for (HttpContent content : this.contents) {
            if (!isMultipart) {
                byteBuffs.add(content.content().copy());
            }

            decoder.offer(content);
            this.readHttpDataChunkByChunk(decoder);
            content.release();
        }
        if (!byteBuffs.isEmpty()) {
            this.body = Unpooled.copiedBuffer(byteBuffs.toArray(new ByteBuf[0]));
        }
    } catch (Exception e) {
        throw new HttpParseException("build decoder fail", e);
    }
}
 
Example 4
Source File: NettyMessageProcessor.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Handles a {@link HttpRequest}.
 * <p/>
 * Does some state maintenance for all HTTP methods by creating a {@link RestRequest} wrapping this
 * {@link HttpRequest}
 * <p/>
 * In case of POST, delegates handling of {@link RestRequest} to the {@link RestRequestHandler}.
 * @param httpRequest the {@link HttpRequest} that needs to be handled.
 * @return {@code true} if the handling succeeded without problems.
 * @throws RestServiceException if there is an error handling the current {@link HttpRequest}.
 */
private boolean handleRequest(HttpRequest httpRequest) throws RestServiceException {
  boolean success = true;
  if (responseChannel == null || requestContentFullyReceived) {
    // Once all content associated with a request has been received, this channel is clear to receive new requests.
    // If the client sends a request without waiting for the response, it is possible to screw things up a little
    // but doing so would constitute an error and no proper client would do that.
    long processingStartTime = System.currentTimeMillis();
    resetState();
    nettyMetrics.requestArrivalRate.mark();
    if (!httpRequest.decoderResult().isSuccess()) {
      success = false;
      logger.warn("Decoder failed because of malformed request on channel {}", ctx.channel(),
          httpRequest.decoderResult().cause());
      nettyMetrics.malformedRequestError.inc();
      onRequestAborted(new RestServiceException("Decoder failed because of malformed request",
          RestServiceErrorCode.MalformedRequest));
    } else {
      try {
        // We need to maintain state about the request itself for the subsequent parts (if any) that come in. We will
        // attach content to the request as the content arrives.
        if ((HttpMethod.POST.equals(httpRequest.method()) || HttpMethod.PUT.equals(httpRequest.method()))
            && HttpPostRequestDecoder.isMultipart(httpRequest)) {
          nettyMetrics.multipartPostRequestRate.mark();
          request = new NettyMultipartRequest(httpRequest, ctx.channel(), nettyMetrics,
              nettyConfig.nettyBlacklistedQueryParams, nettyConfig.nettyMultipartPostMaxSizeBytes);
        } else {
          request =
              new NettyRequest(httpRequest, ctx.channel(), nettyMetrics, nettyConfig.nettyBlacklistedQueryParams);
        }
        responseChannel.setRequest(request);
        logger.trace("Channel {} now handling request {}", ctx.channel(), request.getUri());
        // We send POST that is not multipart for handling immediately since we expect valid content with it that will
        // be streamed in. In the case of POST that is multipart, all the content has to be received for Netty's
        // decoder and NettyMultipartRequest to work. So it is scheduled for handling when LastHttpContent is received.
        // With any other method that we support, we do not expect any valid content. LastHttpContent is a Netty thing.
        // So we wait for LastHttpContent (throw an error if we don't receive it or receive something else) and then
        // schedule the other methods for handling in handleContent().
        if ((request.getRestMethod().equals(RestMethod.POST) || request.getRestMethod().equals(RestMethod.PUT))
            && !HttpPostRequestDecoder.isMultipart(httpRequest)) {
          requestHandler.handleRequest(request, responseChannel);
        }
      } catch (RestServiceException e) {
        success = false;
        onRequestAborted(e);
      } finally {
        if (request != null) {
          request.getMetricsTracker().nioMetricsTracker.addToRequestProcessingTime(
              System.currentTimeMillis() - processingStartTime);
        }
      }
    }
  } else {
    // We have received a request when we were not expecting one. This shouldn't happen and the channel is closed
    // because it is in a bad state.
    success = false;
    logger.error("New request received when previous request is yet to be fully received on channel {}. Request under"
        + " processing: {}. Unexpected request: {}", ctx.channel(), request.getUri(), httpRequest.uri());
    nettyMetrics.duplicateRequestError.inc();
    onRequestAborted(new RestServiceException("Received request in the middle of another request",
        RestServiceErrorCode.BadRequest));
  }
  return success;
}
 
Example 5
Source File: NettyRequest.java    From ambry with Apache License 2.0 2 votes vote down vote up
/**
 * Provides info on whether this request is multipart or not.
 * @return {@code true} if multipart. {@code false} otherwise.
 */
protected boolean isMultipart() {
  return HttpPostRequestDecoder.isMultipart(request);
}