io.netty.handler.codec.http.multipart.Attribute Java Examples

The following examples show how to use io.netty.handler.codec.http.multipart.Attribute. 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: HttpRequestImpl.java    From dorado with Apache License 2.0 6 votes vote down vote up
private void parseHttpPostRequest(FullHttpRequest request) {
	HttpPostRequestDecoder decoder = null;
	try {
		decoder = new HttpPostRequestDecoder(request);
		for (InterfaceHttpData httpData : decoder.getBodyHttpDatas()) {
			HttpDataType _type = httpData.getHttpDataType();
			if (_type == HttpDataType.Attribute) {
				Attribute attribute = (Attribute) httpData;
				parseAttribute(attribute);
			} else if (_type == HttpDataType.FileUpload) {
				FileUpload upload = (FileUpload) httpData;
				multipartFiles.add(MultipartFileFactory.create(upload));
			}
		}
	} catch (Exception ex) {
		LogUtils.warn(ex.getMessage());
	} finally {
		// 注意这个地方,一定要调用destroy方法,如果不调用会导致内存泄漏
		if (decoder != null)
			decoder.destroy();
	}
}
 
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: FormParam.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object get(ChannelHandlerContext ctx, URIDecoder uriDecoder) {
    List<InterfaceHttpData> bodyHttpDatas = uriDecoder.getBodyHttpDatas();
    if (bodyHttpDatas == null || bodyHttpDatas.size() == 0) {
        return null;
    }

    for (InterfaceHttpData data : bodyHttpDatas) {
        if (name.equals(data.getName())) {
            if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                Attribute attribute = (Attribute) data;
                try {
                    return ReflectionUtil.castTo(type, attribute.getValue());
                } catch (IOException e) {
                    log.error("Error getting form params. Reason : {}", e.getMessage(), e);
                }
            }
        }
    }

    return null;
}
 
Example #4
Source File: HttpUtil.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@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());
   }
}
 
Example #5
Source File: HttpRequestParameters.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: HttpTestServerHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #7
Source File: OAuthUtil.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #8
Source File: HttpTestServerHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #9
Source File: WebRequestHandler.java    From Summer with Apache License 2.0 5 votes vote down vote up
private void doPost(ChannelHandlerContext ctx, SessionContext sctx) {
	WebRequest webRequest = getWebRequest();
	JSONObject data = webRequest.getData();
	try {
		while (postRequestDecoder.hasNext()) {
			InterfaceHttpData httpData = postRequestDecoder.next();
			try {
				if (httpData.getHttpDataType() == HttpDataType.Attribute || 
						httpData.getHttpDataType() == HttpDataType.InternalAttribute) {
					Attribute attribute = (Attribute) httpData;
					data.put(attribute.getName(), attribute.getValue());
				} else if (httpData.getHttpDataType() == HttpDataType.FileUpload) {
					FileUpload fileUpload = (FileUpload) httpData;
					if (fileUpload.isCompleted()) {
						webRequest.getFileUploadMap().put(fileUpload.getName(), new WebFileUpload(fileUpload));
					} else {
						log.error("fileUpload not complete name[{}]", fileUpload.getName());
					}
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			} finally {
				postRequestDecoder.removeHttpDataFromClean(httpData);
				httpData.release();
			}
		}
	} catch (EndOfDataDecoderException ignored) {
		
	}
	if (webRequest.isDynamic()) {
		doWork(ctx, sctx, webRequest);
	} else {
		doFile(ctx, sctx, webRequest);
	}
}
 
Example #10
Source File: HttpRequestImpl.java    From dorado with Apache License 2.0 5 votes vote down vote up
private void parseAttribute(Attribute attribute) throws Exception {
	if (this.parameters.containsKey(attribute.getName())) {
		this.parameters.get(attribute.getName()).add(attribute.getValue());
	} else {
		List<String> values = new ArrayList<>();
		values.add(attribute.getValue());
		this.parameters.put(attribute.getName(), values);
	}
}
 
Example #11
Source File: FormData.java    From styx with Apache License 2.0 5 votes vote down vote up
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);
                }
            }));
}
 
Example #12
Source File: Request.java    From ServerCore with Apache License 2.0 5 votes vote down vote up
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();
                }
            }
        });

    }
 
Example #13
Source File: HttpWsServer.java    From zbus-server with MIT License 5 votes vote down vote up
private void handleUploadFile(InterfaceHttpData data, Message uploadMessage) throws IOException{
	FileForm fileForm = (FileForm)uploadMessage.getBody();
       if(fileForm == null){
       	fileForm = new FileForm();
       	uploadMessage.setBody(fileForm);
       }
       
	if (data.getHttpDataType() == HttpDataType.Attribute) {
           Attribute attribute = (Attribute) data;
           fileForm.attributes.put(attribute.getName(), attribute.getValue());
           return;
	}
	
	if (data.getHttpDataType() == HttpDataType.FileUpload) {
           FileUpload fileUpload = (FileUpload) data;
           Http.FileUpload file = new Http.FileUpload();
           file.fileName = fileUpload.getFilename();
           file.contentType = fileUpload.getContentType();
           file.data = fileUpload.get(); 
           
           List<Http.FileUpload> uploads = fileForm.files.get(data.getName());
           if(uploads == null){
           	uploads = new ArrayList<Http.FileUpload>();
           	fileForm.files.put(data.getName(), uploads);
           }
           uploads.add(file);
	}
}
 
Example #14
Source File: TdIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #15
Source File: UploadHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@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();
   }
}
 
Example #16
Source File: HttpRequest.java    From blade with Apache License 2.0 5 votes vote down vote up
private void writeHttpData(InterfaceHttpData data) {
    try {
        InterfaceHttpData.HttpDataType dataType = data.getHttpDataType();
        if (dataType == InterfaceHttpData.HttpDataType.Attribute) {
            parseAttribute((Attribute) data);
        } else if (dataType == InterfaceHttpData.HttpDataType.FileUpload) {
            parseFileUpload((FileUpload) data);
        }
    } catch (IOException e) {
        log.error("Parse request parameter error", e);
    }
}
 
Example #17
Source File: HttpRequest.java    From blade with Apache License 2.0 5 votes vote down vote up
private void parseAttribute(Attribute attribute) throws IOException {
    var name = attribute.getName();
    var value = attribute.getValue();

    List<String> values;
    if (this.parameters.containsKey(name)) {
        values = this.parameters.get(name);
        values.add(value);
    } else {
        values = new ArrayList<>();
        values.add(value);
        this.parameters.put(name, values);
    }
}
 
Example #18
Source File: HttpController.java    From litchi with Apache License 2.0 5 votes vote down vote up
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)));
    }
}
 
Example #19
Source File: ServletTextPart.java    From spring-boot-protocol with Apache License 2.0 4 votes vote down vote up
public ServletTextPart(Attribute attribute, ResourceManager resourceManager) {
    this.attribute = attribute;
    this.resourceManager = resourceManager;
}
 
Example #20
Source File: HttpRequestParamDecoder.java    From fastjgame with Apache License 2.0 4 votes vote down vote up
@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));
}