类 io.netty.handler.codec.http.multipart.HttpPostRequestDecoder 源码实例Demo

下面列出了怎么用 io.netty.handler.codec.http.multipart.HttpPostRequestDecoder 的API类实例代码及写法,或者点击链接到github查看源代码。


private static Map<String,String> getAttribs(FullHttpRequest request) {
   String header = HttpHeaders.getHeader(request, HttpHeaders.Names.CONTENT_TYPE);
   if (HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED.equalsIgnoreCase(header)) {
      Map<String,String> attribs = new HashMap<>();
      HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request);
      List<InterfaceHttpData> data = decoder.getBodyHttpDatas();
      
      if (data != null) {
         for (InterfaceHttpData datum : data) {
            if (datum.getHttpDataType() == HttpDataType.Attribute) {
               Attribute attribute = (Attribute)datum;                
               try {
                  attribs.put(attribute.getName(), attribute.getString());
               } catch (IOException e) {
                  e.printStackTrace();
               }
            }
         }
         return attribs;
      }
   }
   return null;
}
 

private Map<String, List<String>> parsePostFormParameters(FullHttpRequest request) {
   HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request);
   Map<String, List<String>> attributes = new HashMap<String, List<String>>();
   List<InterfaceHttpData> datas = decoder.getBodyHttpDatas();
   for (InterfaceHttpData data : datas) {
      if (data.getHttpDataType() == HttpDataType.Attribute) {
         try {
            String name = data.getName();
            String value = ((Attribute) data).getString();
            attributes.putIfAbsent(name, new ArrayList<String>());
            attributes.get(name).add(value);
         } catch (IOException e) {
            LOGGER.error("Error getting HTTP attribute from POST request");
         }
      }
   }
   decoder.destroy();
   return attributes;
}
 
源代码3 项目: arcusplatform   文件: HttpUtil.java

@Nullable
public static String extractFormParam(HttpPostRequestDecoder decoder, String name, boolean required) throws HttpException {
   InterfaceHttpData data = decoder.getBodyHttpData(name);
   try {
      String value = null;
      if(data != null && data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
         Attribute attribute = (Attribute) data;
         value = attribute.getValue();
      }
      if(value == null && required) {
         throw new HttpException(HttpResponseStatus.BAD_REQUEST.code());
      }
      return value;
   } catch(IOException ioe) {
      throw new HttpException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
   }
}
 
源代码4 项目: dfactor   文件: DFHttpMultiData.java

protected DFHttpMultiData(HttpPostRequestDecoder reqDecoder) {
	this.reqDecoder = reqDecoder;
	List<InterfaceHttpData> lsReqData = reqDecoder.getBodyHttpDatas();
	if(lsReqData.isEmpty()){
		lsData = null;
		partNum = 0;
	}else{
		int tmpNum = 0;
		lsData = new ArrayList<>(lsReqData.size());
		for(InterfaceHttpData reqData : lsReqData){
			if(reqData.getHttpDataType() == HttpDataType.FileUpload){
				FileUpload fUp = (FileUpload) reqData;
				String tmpFile = fUp.getFilename();
				if(tmpFile == null || tmpFile.equals("")){
					continue;
				}
				DFHttpData data = new DFHttpData(fUp);
				lsData.add(data);
				++tmpNum;
			}
		}
		partNum = tmpNum;
	}
}
 

/**
 * request parameters put in {@link #parameters}
 *
 * @param req
 */
private void requestParametersHandler(HttpRequest req) {
    if (req.method().equals(HttpMethod.POST)) {
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req);
        try {
            List<InterfaceHttpData> postList = decoder.getBodyHttpDatas();
            for (InterfaceHttpData data : postList) {
                List<String> values = new ArrayList<String>();
                MixedAttribute value = (MixedAttribute) data;
                value.setCharset(CharsetUtil.UTF_8);
                values.add(value.getValue());
                this.parameters.put(data.getName(), values);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
 
源代码6 项目: riposte   文件: RequestInfoImpl.java

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)
    );
}
 

/**
 * request parameters put in {@link #parameters}
 *
 * @param req
 */
private void requestParametersHandler(HttpRequest req) {
    if (req.method().equals(HttpMethod.POST)) {
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req);
        try {
            List<InterfaceHttpData> postList = decoder.getBodyHttpDatas();
            for (InterfaceHttpData data : postList) {
                List<String> values = new ArrayList<String>();
                MixedAttribute value = (MixedAttribute) data;
                value.setCharset(CharsetUtil.UTF_8);
                values.add(value.getValue());
                this.parameters.put(data.getName(), values);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
 

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();
						}
					}
				}	
			}
		}			
	}	
}
 
源代码9 项目: litchi   文件: HttpController.java

public void init(Channel channel, FullHttpRequest request, RouteResult<RouteAction> routeResult, boolean enableCookies) {
    this.channel = channel;
    this.request = request;
    this.routeResult = routeResult;
    this.enableCookies = enableCookies;

    if (this.method() == HttpMethod.POST) {
        try { 
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request);
            decoder.offer(request);
            List<InterfaceHttpData> paramsList = decoder.getBodyHttpDatas();
            for (InterfaceHttpData httpData : paramsList) {
            	if (httpData.getHttpDataType() == HttpDataType.Attribute) {
            		Attribute data = (Attribute) httpData;
            		postMaps.put(data.getName(), data.getValue());
            	} else if (httpData.getHttpDataType() == HttpDataType.FileUpload) {
            		MixedFileUpload fileUpload = (MixedFileUpload) httpData;
            		this.fileUpload = fileUpload;
            	} else {
            		LOGGER.error("not support http data type. type={}", httpData.getHttpDataType());
            	}
            }
        } catch (Exception ex) {
            LOGGER.error("{}", ex);
        }
    }

    if (enableCookies) {
        List<String> cookiesList = request.headers().getAll(HttpHeaderNames.COOKIE);
        cookiesList.forEach(h -> ServerCookieDecoder.STRICT.decode(h).forEach(c -> cookieMaps.put(c.name(), c)));
    }
}
 
源代码10 项目: arcusplatform   文件: UploadHandler.java

@Override
public void sendResponse(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   long startTime = System.nanoTime();

   HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req);
   try {
      String place = null;
      int num = 0;
      while(decoder.hasNext()) {
         num++;

         InterfaceHttpData httpData = decoder.next();
         if(httpData.getHttpDataType() == HttpDataType.Attribute && httpData.getName().equalsIgnoreCase("place")) {
            place = ((Attribute) httpData).getValue();
         } else if(httpData.getHttpDataType() == HttpDataType.FileUpload) {
            String camProtAddr = URLDecoder.decode(httpData.getName(), "UTF-8");
            Device d = findCamera(camProtAddr);
            if(d == null) {
               UPLOAD_UNKNOWN.inc();
               logger.warn("ignoring preview upload for non-existent camera {}", camProtAddr);
               continue;
            }
            write(place, d, (FileUpload) httpData);
         }
      }
      HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
      ChannelFuture future = ctx.writeAndFlush(response);
      if(!HttpHeaders.isKeepAlive(req)) {
         future.addListener(ChannelFutureListener.CLOSE);
      }

      UPLOAD_NUM.update(num);
      UPLOAD_SUCCESS.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
   } catch (Exception ex) {
      UPLOAD_FAIL.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
   } finally {
      decoder.cleanFiles();
   }
}
 

private static String formatContent(FullHttpRequest request) {
   String header = HttpHeaders.getHeader(request, HttpHeaders.Names.CONTENT_TYPE);
   StringBuffer bf = new StringBuffer();
   
   if (HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED.equalsIgnoreCase(header)) {
      HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request);
      List<InterfaceHttpData> data = decoder.getBodyHttpDatas();
      
      if (data != null) {
         for (InterfaceHttpData datum : data) {
            if (datum.getHttpDataType() == HttpDataType.Attribute) {
               Attribute attribute = (Attribute)datum;
             
               try {
                  bf.append(attribute.getName()).append(" -> ").append(attribute.getString()).append("\n");
               } catch (IOException e) {
                  e.printStackTrace();
               }
            }
         }
      }
      else {
         bf.append("[No Data]\n");
      }
   }
   else if ("application/json".equalsIgnoreCase(header)) {
      ByteBuf byteBuf = request.content();
      byte[] bytes = new byte[byteBuf.readableBytes()];
      byteBuf.readBytes(bytes);
      String s = new String(bytes, StandardCharsets.UTF_8);
      bf.append(s);
   }
   else {
      bf.append("[Unknown Data Type ").append(header).append("]");
   }
   
   return bf.toString();
}
 
源代码12 项目: arcusplatform   文件: OAuthUtil.java

public static String extractFormParam(HttpPostRequestDecoder decoder, String name, boolean required) throws IOException {
   InterfaceHttpData data = decoder.getBodyHttpData(name);
   if(data != null && data.getHttpDataType() == HttpDataType.Attribute) {
      Attribute attribute = (Attribute) data;
      return attribute.getValue();
   }
   if(required) {
      throw new MissingParameterException(name);
   }

   return null;
}
 
源代码13 项目: arcusplatform   文件: OAuthUtil.java

public static BasicAuthCredentials extractApplicationCredentials(HttpPostRequestDecoder decoder, FullHttpRequest req) throws Exception {
   String authHeader = req.headers().get(HttpHeaders.AUTHORIZATION);
   if(!StringUtils.isBlank(authHeader)) {
      return BasicAuthCredentials.fromAuthHeaderString(authHeader);
   }
   String appId = extractFormParam(decoder, OAuthUtil.ATTR_CLIENT_ID, true);
   String pass = extractFormParam(decoder, OAuthUtil.ATTR_CLIENT_SECRET, true);
   return new BasicAuthCredentials(appId, pass);
}
 
源代码14 项目: Summer   文件: WebRequestHandler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) {
	SessionContext sctx = serverContext.getSessionContextGroup().getSessionByChannel(ctx);
	long now = Calendar.getInstance().getTimeInMillis();
	long last = sctx.getLastRecvTime();
	sctx.setLastRecvTime(now);
	if ((now - last) < serverContext.getConfig().getColdDownMs()) {
		serverContext.getSessionHandlerGroup().sendTooFastMsg(sctx);
	}
	sctx.setHeartCount(0);
	try {
		if (httpObject instanceof HttpRequest) {
			httpRequest = (HttpRequest) httpObject;
			if (!httpRequest.decoderResult().isSuccess()) {
				return;
			}
			String uri = httpRequest.uri();
			if (uri == null) {
				return;
			}
			sctx.setSessionId(parseSessionId(httpRequest.headers().get(HttpHeaderNames.COOKIE)));
			sctx.setRealAddress(ForwardedAddressUtil.parse(httpRequest.headers().get(ForwardedAddressUtil.KEY)));
			HttpMethod method = httpRequest.method();
			if (HttpMethod.GET.equals(method)) {
				doGet(ctx, sctx);
			} else if (HttpMethod.POST.equals(method)) {
				postRequestDecoder = new HttpPostRequestDecoder(factory, httpRequest);
				processHttpContent(ctx, sctx, (HttpContent) httpObject);
			} else {
				log.warn("not found request method[{}]", method.name());
			}
		} else if (httpObject instanceof HttpContent) {
			processHttpContent(ctx, sctx, (HttpContent) httpObject);
		}
	} catch (Exception e) {
		log.error(e.getMessage(), e);
		serverContext.getSessionHandlerGroup().unableParseMsg(sctx);
	}
}
 
源代码15 项目: styx   文件: FormData.java

private Map<String, String> extractParameters(HttpPostRequestDecoder content) {
    return content.getBodyHttpDatas()
            .stream()
            .filter(data -> data instanceof Attribute)
            .map(data -> (Attribute) data)
            .collect(toMap(Attribute::getName, (Function<Attribute, String>) attribute -> {
                try {
                    return attribute.getValue();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }));
}
 
源代码16 项目: ServerCore   文件: Request.java

private void parseParameter() {

        this.parameterParsed = true;

        //解析query参数,默认使用UTF8编码
        QueryStringDecoder queryDecoder = new QueryStringDecoder(this.uri);

        queryDecoder.parameters().forEach((k, v) -> {
            if (v != null && v.size() > 0) {
                parameters.put(k, v.get(0));
            }
        });

        if (this.method == HttpMethod.GET) {
            return;
        }
        //解析post参数
        HttpPostRequestDecoder postDecoder = new HttpPostRequestDecoder(this.msg);
        postDecoder.getBodyHttpDatas().forEach(v -> {
            if (v.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                Attribute attribute = (Attribute) v;
                try {
                    this.parameters.put(attribute.getName(), attribute.getValue());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }
 
源代码17 项目: digdag   文件: TdIT.java

private String domainKey(FullHttpRequest request)
        throws IOException
{
    FullHttpRequest copy = request.copy();
    ReferenceCountUtil.releaseLater(copy);
    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(copy);
    List<InterfaceHttpData> keyDatas = decoder.getBodyHttpDatas("domain_key");
    assertThat(keyDatas, is(not(nullValue())));
    assertThat(keyDatas.size(), is(1));
    InterfaceHttpData domainKeyData = keyDatas.get(0);
    assertThat(domainKeyData.getHttpDataType(), is(HttpDataType.Attribute));
    return ((Attribute) domainKeyData).getValue();
}
 
源代码18 项目: blynk-server   文件: URIDecoder.java

public URIDecoder(HttpRequest httpRequest, Map<String, String> extractedParams) {
    super(httpRequest.uri());
    this.paths = path().split("/");
    if (httpRequest.method() == HttpMethod.PUT || httpRequest.method() == HttpMethod.POST) {
        if (httpRequest instanceof HttpContent) {
            this.contentType = httpRequest.headers().get(HttpHeaderNames.CONTENT_TYPE);
            if (contentType != null && contentType.equals(MediaType.APPLICATION_FORM_URLENCODED)) {
                this.decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), httpRequest);
            } else {
                this.bodyData = ((HttpContent) httpRequest).content();
            }
        }
    }
    this.pathData = extractedParams;
}
 
源代码19 项目: ambry   文件: NettyMultipartRequest.java

/**
 * {@inheritDoc}
 * <p/>
 * Prepares the request for reading by decoding all the content added via {@link #addContent(HttpContent)}.
 * @throws RestServiceException if request channel is closed or if the request could not be decoded/prepared.
 */
@Override
public void prepare() throws RestServiceException {
  if (!isOpen()) {
    nettyMetrics.multipartRequestAlreadyClosedError.inc();
    throw new RestServiceException("Request is closed", RestServiceErrorCode.RequestChannelClosed);
  } else if (!readyForRead) {
    // make sure data is held in memory.
    HttpDataFactory httpDataFactory = new DefaultHttpDataFactory(false);
    HttpPostMultipartRequestDecoder postRequestDecoder =
        new HttpPostMultipartRequestDecoder(httpDataFactory, request);
    try {
      HttpContent httpContent = rawRequestContents.poll();
      while (httpContent != null) {
        try {
          // if the request is also an instance of HttpContent, the HttpPostMultipartRequestDecoder does the offer
          // automatically at the time of construction. We should not add it again.
          if (httpContent != request) {
            postRequestDecoder.offer(httpContent);
          }
        } finally {
          ReferenceCountUtil.release(httpContent);
        }
        httpContent = rawRequestContents.poll();
      }
      for (InterfaceHttpData part : postRequestDecoder.getBodyHttpDatas()) {
        processPart(part);
      }
      requestContents.add(LastHttpContent.EMPTY_LAST_CONTENT);
      readyForRead = true;
    } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) {
      nettyMetrics.multipartRequestDecodeError.inc();
      throw new RestServiceException("There was an error decoding the request", e,
          RestServiceErrorCode.MalformedRequest);
    } finally {
      postRequestDecoder.destroy();
    }
  }
}
 
源代码20 项目: fastjgame   文件: HttpRequestParamDecoder.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
    DecoderResult decoderResult = msg.decoderResult();
    if (!decoderResult.isSuccess()) {
        ctx.writeAndFlush(HttpResponseHelper.newBadRequestResponse())
                .addListener(ChannelFutureListener.CLOSE);
        logger.warn("decode failed.", decoderResult.cause());
        return;
    }
    HttpMethod method = msg.method();
    // 仅限get和post请求
    if (method != HttpMethod.GET && method != HttpMethod.POST) {
        ctx.writeAndFlush(HttpResponseHelper.newBadRequestResponse())
                .addListener(ChannelFutureListener.CLOSE);
        logger.info("unsupported method {}", method.name());
        return;
    }

    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(msg.uri());
    String path = queryStringDecoder.path();
    Map<String, String> paramsMap = new LinkedHashMap<>();

    if (method == HttpMethod.GET) {
        for (Map.Entry<String, List<String>> entry : queryStringDecoder.parameters().entrySet()) {
            paramsMap.put(entry.getKey(), entry.getValue().get(0));
        }
    } else {
        // You <strong>MUST</strong> call {@link #destroy()} after completion to release all resources.
        HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder(msg);
        try {
            for (InterfaceHttpData httpData : postRequestDecoder.getBodyHttpDatas()) {
                if (httpData.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    Attribute attribute = (Attribute) httpData;
                    paramsMap.put(attribute.getName(), attribute.getValue());
                }
            }
        } finally {
            postRequestDecoder.destroy();
        }
    }
    final HttpRequestParam httpRequestParam = new HttpRequestParam(method, paramsMap);
    publish(new HttpRequestEvent(ctx.channel(), path, httpRequestParam, portExtraInfo));
}
 
源代码21 项目: arcusplatform   文件: TokenHandler.java

private FullHttpResponse handleAuthorizationCode(HttpPostRequestDecoder decoder, String appId) throws Exception {
   OAuthMetrics.incAccessTokenRequest();
   String code = OAuthUtil.extractFormParam(decoder, OAuthUtil.ATTR_CODE, true);
   String redirect = OAuthUtil.extractFormParam(decoder, OAuthUtil.ATTR_REDIRECT_URI, false);
   return doHandleAuthorizationCode(code, redirect, appId);
}
 
源代码22 项目: arcusplatform   文件: TokenHandler.java

private FullHttpResponse handleRefreshToken(HttpPostRequestDecoder decoder, String appId) throws Exception {
   OAuthMetrics.incRefreshTokenRequest();
   String refresh = OAuthUtil.extractFormParam(decoder, OAuthUtil.ATTR_REFRESH, true);
   return  doHandleRefreshToken(refresh, appId);
}
 
源代码23 项目: JerryServer   文件: JerryRequest.java

public JerryRequest(FullHttpRequest request) {
    this.request = request;
    decoder = new HttpPostRequestDecoder(request);
    decoder.offer(request);

}
 

/**
 * 如果content-type为multipart/form-data,获取内容列表
 * @return
 */
public List<InterfaceHttpData> getContentFormdata() {
    HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder(request);
    return postRequestDecoder.getBodyHttpDatas();
}
 
源代码25 项目: styx   文件: FormData.java

FormData(HttpPostRequestDecoder content) {
    requireNonNull(content);
    parameters = extractParameters(content);
    content.destroy();
}
 
源代码26 项目: blade   文件: HttpRequest.java

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);
    }
}
 
源代码27 项目: ambry   文件: NettyMessageProcessor.java

/**
 * 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;
}
 
源代码28 项目: ambry   文件: NettyRequest.java

/**
 * 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);
}
 
 同包方法