Java 类io.netty.handler.codec.http.multipart.DefaultHttpDataFactory 实例源码

项目:mqttserver    文件:HttpSessionStore.java   
public static String getPostParameter(HttpRequest req, String name) {
    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(
            new DefaultHttpDataFactory(false), req);

    InterfaceHttpData data = decoder.getBodyHttpData(name);
    if (data.getHttpDataType() == HttpDataType.Attribute) {
        Attribute attribute = (Attribute) data;
        String value = null;
        try {
            value = attribute.getValue();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }

    return null;
}
项目:riposte    文件:RequestInfoImpl.java   
/**
 * {@inheritDoc}
 */
@Override
public synchronized List<InterfaceHttpData> getMultipartParts() {
    if (!isMultipartRequest() || !isCompleteRequestWithAllChunks())
        return null;

    if (multipartData == null) {
        byte[] contentBytes = getRawContentBytes();
        HttpRequest fullHttpRequestForMultipartDecoder =
            (contentBytes == null)
            ? new DefaultFullHttpRequest(getProtocolVersion(), getMethod(), getUri())
            : new DefaultFullHttpRequest(getProtocolVersion(), getMethod(), getUri(),
                                         Unpooled.wrappedBuffer(contentBytes));

        fullHttpRequestForMultipartDecoder.headers().add(getHeaders());

        multipartData = new HttpPostMultipartRequestDecoder(
            new DefaultHttpDataFactory(false), fullHttpRequestForMultipartDecoder, getContentCharset()
        );
    }

    return multipartData.getBodyHttpDatas();
}
项目:netty-cookbook    文件:ServletNettyChannelHandler.java   
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();
                        }
                    }
                }   
            }
        }           
    }   
}
项目:kaa    文件:NettyHttpTestIT.java   
public void setHttpRequest(HttpRequest request) throws BadRequestException, IOException {
  if (request == null) {
    LOG.error("HttpRequest not initialized");
    throw new BadRequestException("HttpRequest not initialized");
  }
  if (!request.getMethod().equals(HttpMethod.POST)) {
    LOG.error("Got invalid HTTP method: expecting only POST");
    throw new BadRequestException("Incorrect method "
        + request.getMethod().toString() + ", expected POST");
  }
  HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
  HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(factory, request);
  InterfaceHttpData data = decoder.getBodyHttpData(HTTP_TEST_ATTRIBUTE);
  if (data == null) {
    LOG.error("HTTP Resolve request inccorect, {} attribute not found", HTTP_TEST_ATTRIBUTE);
    throw new BadRequestException("HTTP Resolve request inccorect, " +
        HTTP_TEST_ATTRIBUTE + " attribute not found");
  }
  Attribute attribute = (Attribute) data;
  requestData = attribute.get();
  LOG.trace("Name {}, type {} found, data size {}", data.getName(), data.getHttpDataType().name(), requestData.length);
}
项目:ambry    文件:FrontendIntegrationTest.java   
/**
 * Creates a {@link HttpPostRequestEncoder} that encodes the given {@code request} and {@code blobContent}.
 * @param request the {@link HttpRequest} containing headers and other metadata about the request.
 * @param blobContent the {@link ByteBuffer} that represents the content of the blob.
 * @param usermetadata the {@link ByteBuffer} that represents user metadata
 * @return a {@link HttpPostRequestEncoder} that can encode the {@code request} and {@code blobContent}.
 * @throws HttpPostRequestEncoder.ErrorDataEncoderException
 * @throws IOException
 */
private HttpPostRequestEncoder createEncoder(HttpRequest request, ByteBuffer blobContent, ByteBuffer usermetadata)
    throws HttpPostRequestEncoder.ErrorDataEncoderException, IOException {
  HttpDataFactory httpDataFactory = new DefaultHttpDataFactory(false);
  HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(httpDataFactory, request, true);
  FileUpload fileUpload = new MemoryFileUpload(RestUtils.MultipartPost.BLOB_PART, RestUtils.MultipartPost.BLOB_PART,
      "application/octet-stream", "", Charset.forName("UTF-8"), blobContent.remaining());
  fileUpload.setContent(Unpooled.wrappedBuffer(blobContent));
  encoder.addBodyHttpData(fileUpload);
  fileUpload =
      new MemoryFileUpload(RestUtils.MultipartPost.USER_METADATA_PART, RestUtils.MultipartPost.USER_METADATA_PART,
          "application/octet-stream", "", Charset.forName("UTF-8"), usermetadata.remaining());
  fileUpload.setContent(Unpooled.wrappedBuffer(usermetadata));
  encoder.addBodyHttpData(fileUpload);
  return encoder;
}
项目:ambry    文件:NettyMultipartRequestTest.java   
/**
 * Creates a {@link HttpPostRequestEncoder} that encodes the given {@code request} and {@code parts}.
 * @param request the {@link HttpRequest} containing headers and other metadata about the request.
 * @param parts the {@link InMemoryFile}s that will form the parts of the request.
 * @return a {@link HttpPostRequestEncoder} that can encode the {@code request} and {@code parts}.
 * @throws HttpPostRequestEncoder.ErrorDataEncoderException
 * @throws IOException
 */
private HttpPostRequestEncoder createEncoder(HttpRequest request, InMemoryFile[] parts)
    throws HttpPostRequestEncoder.ErrorDataEncoderException, IOException {
  HttpDataFactory httpDataFactory = new DefaultHttpDataFactory(false);
  HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(httpDataFactory, request, true);
  if (parts != null) {
    for (InMemoryFile part : parts) {
      FileUpload fileUpload =
          new MemoryFileUpload(part.name, part.name, "application/octet-stream", "", Charset.forName("UTF-8"),
              part.content.remaining());
      fileUpload.setContent(Unpooled.wrappedBuffer(part.content));
      encoder.addBodyHttpData(fileUpload);
    }
  }
  return encoder;
}
项目:gale    文件:GaleRequestProcessor.java   
public GaleRequest process(FullHttpRequest request) {
  GaleRequest result = new GaleRequest();
  result.setUri(request.getUri());
  result.setMethod(request.getMethod());
  result.setHeaders(request.headers());
  result.setVersion(request.getProtocolVersion());

  //parse query parameters
  QueryStringDecoder queryDecoder = new QueryStringDecoder(request.getUri(), CharsetUtil.UTF_8);

  result.setPath(queryDecoder.path());
  result.getParameters().putAll(queryDecoder.parameters());
  //parse body parameters
  HttpPostRequestDecoder bodyDecoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(true), request);

  List<InterfaceHttpData> datum = bodyDecoder.getBodyHttpDatas();
  if (datum != null && !datum.isEmpty()) {
    for (InterfaceHttpData data : datum) {
      String name = data.getName();
      String value = null;
      if (data.getHttpDataType().equals(HttpDataType.Attribute)) {
        //do not parse file data
        Attribute attribute = (Attribute)data;
        try {
          value = attribute.getString(CharsetUtil.UTF_8);
          result.getParameters().add(name, value);
        } catch(Exception e) {
          ELOGGER.error(this.getClass().getName(), e);
        }
      }
    }
  }
  bodyDecoder.destroy();
  return result;
}
项目: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;
}
项目: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();
    }
  }
}
项目:ambry    文件:NettyMessageProcessorTest.java   
/**
 * Creates a {@link HttpPostRequestEncoder} that encodes the given {@code request} and {@code blobContent}.
 * @param request the {@link HttpRequest} containing headers and other metadata about the request.
 * @param blobContent the {@link ByteBuffer} that represents the content of the blob.
 * @return a {@link HttpPostRequestEncoder} that can encode the {@code request} and {@code blobContent}.
 * @throws HttpPostRequestEncoder.ErrorDataEncoderException
 * @throws IOException
 */
private HttpPostRequestEncoder createEncoder(HttpRequest request, ByteBuffer blobContent)
    throws HttpPostRequestEncoder.ErrorDataEncoderException, IOException {
  HttpDataFactory httpDataFactory = new DefaultHttpDataFactory(false);
  HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(httpDataFactory, request, true);
  FileUpload fileUpload = new MemoryFileUpload(RestUtils.MultipartPost.BLOB_PART, RestUtils.MultipartPost.BLOB_PART,
      "application/octet-stream", "", Charset.forName("UTF-8"), blobContent.remaining());
  fileUpload.setContent(Unpooled.wrappedBuffer(blobContent));
  encoder.addBodyHttpData(fileUpload);
  return encoder;
}
项目:kaa    文件:AbstractHttpSyncCommand.java   
@Override
public void parse() throws Exception {
  LOG.trace("CommandName: " + COMMAND_NAME + ": Parse..");
  HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
  HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(factory, getRequest());
  if (decoder.isMultipart()) {
    LOG.trace("Chunked: " + HttpHeaders.isTransferEncodingChunked(getRequest()));
    LOG.trace(": Multipart..");
    List<InterfaceHttpData> datas = decoder.getBodyHttpDatas();
    if (!datas.isEmpty()) {
      for (InterfaceHttpData data : datas) {
        LOG.trace("Multipart1 name " + data.getName() + " type " + data.getHttpDataType().name());
        if (data.getHttpDataType() == HttpDataType.Attribute) {
          Attribute attribute = (Attribute) data;
          if (CommonEpConstans.REQUEST_SIGNATURE_ATTR_NAME.equals(data.getName())) {
            requestSignature = attribute.get();
            if (LOG.isTraceEnabled()) {
              LOG.trace("Multipart name " + data.getName() + " type "
                  + data.getHttpDataType().name() + " Signature set. size: "
                  + requestSignature.length);
              LOG.trace(MessageEncoderDecoder.bytesToHex(requestSignature));
            }

          } else if (CommonEpConstans.REQUEST_KEY_ATTR_NAME.equals(data.getName())) {
            requestKey = attribute.get();
            if (LOG.isTraceEnabled()) {
              LOG.trace("Multipart name " + data.getName() + " type "
                  + data.getHttpDataType().name() + " requestKey set. size: "
                  + requestKey.length);
              LOG.trace(MessageEncoderDecoder.bytesToHex(requestKey));
            }
          } else if (CommonEpConstans.REQUEST_DATA_ATTR_NAME.equals(data.getName())) {
            requestData = attribute.get();
            if (LOG.isTraceEnabled()) {
              LOG.trace("Multipart name " + data.getName() + " type "
                  + data.getHttpDataType().name() + " requestData set. size: "
                  + requestData.length);
              LOG.trace(MessageEncoderDecoder.bytesToHex(requestData));
            }
          } else if (CommonEpConstans.NEXT_PROTOCOL_ATTR_NAME.equals(data.getName())) {
            nextProtocol = ByteBuffer.wrap(attribute.get()).getInt();
            LOG.trace("[{}] next protocol is {}", getSessionUuid(), nextProtocol);
          }
        }
      }
    } else {
      LOG.error("Multipart.. size 0");
      throw new BadRequestException("HTTP Request inccorect, multiprat size is 0");
    }
  }
}
项目:lambdatra    文件:WrappedRequest.java   
/**
 * Creates a {@link HttpPostRequestDecoder} of the request body.
 * 
 * @return a {@link HttpPostRequestDecoder}
 */
public HttpPostRequestDecoder parseBody() {
    return new HttpPostRequestDecoder(new DefaultHttpDataFactory(Short.MAX_VALUE), req);
}
项目:distributeTemplate    文件:MyHttpPostRequestEncoder.java   
/**
 *
 * @param request
 *            the request to encode
 * @param multipart
 *            True if the FORM is a ENCTYPE="multipart/form-data"
 * @throws NullPointerException
 *             for request
 * @throws ErrorDataEncoderException
 *             if the request is not a POST
 */
public MyHttpPostRequestEncoder(HttpRequest request, boolean multipart) throws ErrorDataEncoderException {
    this(new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE), request, multipart,
            HttpConstants.DEFAULT_CHARSET, EncoderMode.RFC1738);
}