Java Code Examples for io.netty.handler.codec.http.HttpMethod#POST

The following examples show how to use io.netty.handler.codec.http.HttpMethod#POST . 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: QueryStringDecoderAndRouter.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

    // for POST requests, check Content-Type header
    if ( request.getMethod() == HttpMethod.POST ) {
        if (!mediaTypeChecker.isContentTypeValid(request.headers())) {
            DefaultHandler.sendErrorResponse(ctx, request,
                    String.format("Unsupported media type for Content-Type: %s", request.headers().get(HttpHeaders.Names.CONTENT_TYPE)),
                    HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE
            );
            return;
        }
    }

    // for GET or POST requests, check Accept header
    if ( request.getMethod() == HttpMethod.GET || request.getMethod() == HttpMethod.POST ) {
        if (!mediaTypeChecker.isAcceptValid(request.headers())) {
            DefaultHandler.sendErrorResponse(ctx, request,
                    String.format("Unsupported media type for Accept: %s", request.headers().get(HttpHeaders.Names.ACCEPT)),
                    HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE
            );
            return;
        }
    }
    router.route(ctx, HttpRequestWithDecodedQueryParams.create(request));
}
 
Example 2
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private void testRegisterModelConnectionFailed() throws InterruptedException {
    Channel channel = connect(true);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    "/models?url=http%3A%2F%2Flocalhost%3A18888%2Ffake.mar&synchronous=false");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(result, ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.BAD_REQUEST.code());
    Assert.assertEquals(
            resp.getMessage(),
            "Failed to download model from: http://localhost:18888/fake.mar");
}
 
Example 3
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private void testLoadModelWithInitialWorkersWithJSONReqBody(Channel channel)
        throws InterruptedException {
    testUnregisterModel(channel);

    result = null;
    latch = new CountDownLatch(1);
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/models");
    req.headers().add("Content-Type", "application/json");
    req.content()
            .writeCharSequence(
                    "{'url':'noop-v0.1', 'model_name':'noop_v0.1', 'initial_workers':'1', 'synchronous':'true'}",
                    CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    channel.writeAndFlush(req);
    latch.await();

    StatusResponse resp = JsonUtils.GSON.fromJson(result, StatusResponse.class);
    Assert.assertEquals(resp.getStatus(), "Workers scaled");
}
 
Example 4
Source File: HttpRequestImpl.java    From dorado with Apache License 2.0 6 votes vote down vote up
public HttpRequestImpl(FullHttpRequest request) {
	this.request = request;
	this.parameters = new HashMap<>();
	this.headers = request.headers();
	this.multipartFiles = new ArrayList<>();

	this.uriParser = new URIParser();

	// 解析querystring上面的参数
	queryStringDecoder = new QueryStringDecoder(request.uri());
	uriParser.parse(queryStringDecoder.path());
	parameters.putAll(queryStringDecoder.parameters());
	in = new InputStreamImpl(request);

	if (request.method() == HttpMethod.POST) {
		parseHttpPostRequest(request);
	}
}
 
Example 5
Source File: TestVerifyPinRESTHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private FullHttpRequest createRequest(String pin, String place) {
   PersonCapability.VerifyPinRequest.Builder builder = PersonCapability.VerifyPinRequest.builder();
   
   if(pin != null) {
      builder.withPin(pin);
   }
   
   if (place != null) {
      builder.withPlace(place);
   }

   ClientMessage msg = ClientMessage.builder()
         .withCorrelationId("correlationid")
         .withDestination(person.getAddress())
         .withPayload(builder.build())
         .create();

   FullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/person/VerifyPin");
   req.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/json");

   ByteBuf buffer = Unpooled.copiedBuffer(JSON.toJson(msg), CharsetUtil.UTF_8);
   req.headers().add(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes());
   req.content().clear().writeBytes(buffer);
   return req;
}
 
Example 6
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testPredictionsJson"})
public void testInvocationsJson() throws InterruptedException {
    Channel channel = TestUtils.getInferenceChannel(configManager);
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/invocations?model_name=noop");
    req.content().writeCharSequence("{\"data\": \"test\"}", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    channel.writeAndFlush(req);
    TestUtils.getLatch().await();

    Assert.assertEquals(TestUtils.getResult(), "OK");
}
 
Example 7
Source File: HttpPostRequestEncoderTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataIsMultipleOfChunkSize2() throws Exception {
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
            HttpMethod.POST, "http://localhost");
    HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true);
    int length = 7943;
    char[] array = new char[length];
    Arrays.fill(array, 'a');
    String longText = new String(array);
    encoder.addBodyAttribute("foo", longText);

    assertNotNull(encoder.finalizeRequest());

    checkNextChunkSize(encoder, 8080);

    HttpContent httpContent = encoder.readChunk((ByteBufAllocator) null);
    assertTrue("Expected LastHttpContent is not received", httpContent instanceof LastHttpContent);
    httpContent.release();

    assertTrue("Expected end of input is not receive", encoder.isEndOfInput());
}
 
Example 8
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
private void testPredictions(String modelName, String expectedOutput, String version)
        throws InterruptedException {
    Channel channel = TestUtils.getInferenceChannel(configManager);
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    String requestURL = "/predictions/" + modelName;
    if (version != null) {
        requestURL += "/" + version;
    }
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, requestURL);
    req.content().writeCharSequence("data=test", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers()
            .set(
                    HttpHeaderNames.CONTENT_TYPE,
                    HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
    channel.writeAndFlush(req);

    TestUtils.getLatch().await();
    Assert.assertEquals(TestUtils.getResult(), expectedOutput);
}
 
Example 9
Source File: GoogleHomeHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Inject
public GoogleHomeHandler(
   @Named(BEARER_AUTH_NAME) RequestAuthorizer authorizer,
   GoogleBridgeConfig config,
   OAuthDAO oauthDao,
   @Named(VoiceBridgeConfig.NAME_EXECUTOR) ExecutorService executor,
   PlatformMessageBus bus,
   VoiceBridgeMetrics metrics,
   PlacePopulationCacheManager populationCacheMgr
) {
   super(new WildcardMatcher("/ha", HttpMethod.POST), authorizer, new ResponderImpl(config, oauthDao, bus, executor, metrics, populationCacheMgr));
}
 
Example 10
Source File: HttpRequestDecoderTest.java    From timely with Apache License 2.0 5 votes vote down vote up
@Test
public void testLookupPostWithLimitAndTags() throws Exception {
// @formatter:off
    String content =
    "{\n" +
    "    \"metric\": \"sys.cpu.user\",\n" +
    "    \"limit\": 3000,\n" +
    "    \"tags\":[\n" +
    "        {\n" +
    "            \"host\":\"*\"\n" +
    "        }\n"+
    "    ]\n" +
    "}";
    // @formatter:on
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/api/search/lookup");
    request.content().writeBytes(content.getBytes());
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(SearchLookupRequest.class, results.iterator().next().getClass());
    SearchLookupRequest lookup = (SearchLookupRequest) results.iterator().next();
    Assert.assertEquals("sys.cpu.user", lookup.getQuery());
    Assert.assertEquals(3000, lookup.getLimit());
    Assert.assertEquals(1, lookup.getTags().size());
    Tag tag = lookup.getTags().iterator().next();
    Assert.assertEquals("host", tag.getKey());
    Assert.assertEquals("*", tag.getValue());
}
 
Example 11
Source File: HttpRequestDecoderTest.java    From timely with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryPostGlobalAnnotations() throws Exception {
// @formatter:off
    String content = "" +
    "{"
    + "\"start\":1447767369171,"
    + "\"queries\":"
    +  "["
    +   "{"
    +      "\"metric\":\"sys.cpu.user\","
    +      "\"aggregator\":\"sum\","
    +      "\"downsample\":\"30s-avg\""
    +   "}"
    +  "],"
    + "\"msResolution\":false,"
    + "\"globalAnnotations\":true,"
    + "\"showQuery\":true"
    + "}";
    // @formatter:on
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/api/query");
    request.content().writeBytes(content.getBytes());
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(QueryRequest.class, results.iterator().next().getClass());
    QueryRequest query = (QueryRequest) results.iterator().next();
    Assert.assertEquals(1447767369171L, query.getStart());
    Assert.assertEquals(false, query.isMsResolution());
    Assert.assertEquals(true, query.isGlobalAnnotations());
    Assert.assertEquals(true, query.isShowQuery());
    Assert.assertEquals(1, query.getQueries().size());
    Iterator<SubQuery> iter = query.getQueries().iterator();
    SubQuery first = iter.next();
    Assert.assertEquals(true, first.isMetricQuery());
    Assert.assertEquals(false, first.isTsuidQuery());
    Assert.assertEquals("sum", first.getAggregator());
    Assert.assertEquals("sys.cpu.user", first.getMetric());
}
 
Example 12
Source File: HttpPostRequestEncoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiFileUploadInHtml5Mode() throws Exception {
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
            HttpMethod.POST, "http://localhost");

    DefaultHttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);

    HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(factory,
            request, true, CharsetUtil.UTF_8, EncoderMode.HTML5);
    File file1 = new File(getClass().getResource("/file-01.txt").toURI());
    encoder.addBodyAttribute("foo", "bar");
    encoder.addBodyFileUpload("quux", file1, "text/plain", false);

    String multipartDataBoundary = encoder.multipartDataBoundary;
    String content = getRequestBody(encoder);

    String expected = "--" + multipartDataBoundary + "\r\n" +
            CONTENT_DISPOSITION + ": form-data; name=\"foo\"" + "\r\n" +
            CONTENT_LENGTH + ": 3" + "\r\n" +
            CONTENT_TYPE + ": text/plain; charset=UTF-8" + "\r\n" +
            "\r\n" +
            "bar" +
            "\r\n" +
            "--" + multipartDataBoundary + "\r\n" +
            CONTENT_DISPOSITION + ": form-data; name=\"quux\"; filename=\"file-01.txt\"" + "\r\n" +
            CONTENT_LENGTH + ": " + file1.length() + "\r\n" +
            CONTENT_TYPE + ": text/plain" + "\r\n" +
            CONTENT_TRANSFER_ENCODING + ": binary" + "\r\n" +
            "\r\n" +
            "File 01" + StringUtil.NEWLINE +
            "\r\n" +
            "--" + multipartDataBoundary + "--" + "\r\n";

    assertEquals(expected, content);
}
 
Example 13
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
private void testModelsInvokeJson(Channel channel) throws InterruptedException {
    result = null;
    latch = new CountDownLatch(1);
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/models/noop/invoke");
    req.content().writeCharSequence("{\"data\": \"test\"}", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    channel.writeAndFlush(req);
    latch.await();

    Assert.assertEquals(result, "OK");
}
 
Example 14
Source File: NettyRequestTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link NettyRequest#addContent(HttpContent)} and
 * {@link NettyRequest#readInto(AsyncWritableChannel, Callback)} with different digest algorithms (including a test
 * with no digest algorithm).
 * @throws Exception
 */
@Test
public void contentAddAndReadTest() throws Exception {
  String[] digestAlgorithms = {"", "MD5", "SHA-1", "SHA-256"};
  HttpMethod[] methods = {HttpMethod.POST, HttpMethod.PUT};
  for (HttpMethod method : methods) {
    for (String digestAlgorithm : digestAlgorithms) {
      contentAddAndReadTest(digestAlgorithm, true, method);
      contentAddAndReadTest(digestAlgorithm, false, method);
    }
  }
}
 
Example 15
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
private void testLogging(Channel inferChannel, Channel mgmtChannel)
        throws NoSuchFieldException, IllegalAccessException, InterruptedException, IOException {
    setConfiguration("default_workers_per_model", "2");
    loadTests(mgmtChannel, "logging", "logging");
    int niter = 5;
    int expected = 2;
    for (int i = 0; i < niter; i++) {
        latch = new CountDownLatch(1);
        DefaultFullHttpRequest req =
                new DefaultFullHttpRequest(
                        HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/logging");
        req.content().writeCharSequence("data=test", CharsetUtil.UTF_8);
        HttpUtil.setContentLength(req, req.content().readableBytes());
        req.headers()
                .set(
                        HttpHeaderNames.CONTENT_TYPE,
                        HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
        inferChannel.writeAndFlush(req);
        latch.await();
        Assert.assertEquals(httpStatus, HttpResponseStatus.OK);
    }

    File logfile = new File("build/logs/mms_log.log");
    Assert.assertTrue(logfile.exists());
    Scanner logscanner = new Scanner(logfile, "UTF-8");
    int count = 0;
    while (logscanner.hasNextLine()) {
        String line = logscanner.nextLine();
        if (line.contains("LoggingService inference [PID]:")) {
            count = count + 1;
        }
    }
    Logger logger = LoggerFactory.getLogger(ModelServerTest.class);
    logger.info("testLogging, found {}, min expected {}.", count, expected);
    Assert.assertTrue(count >= expected);
    unloadTests(mgmtChannel, "logging");
}
 
Example 16
Source File: HttpHandler.java    From netty-pubsub with MIT License 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
	// TODO Auto-generated method stub
	try {
		ByteBuf content = msg.content();
		byte[] bts = new byte[content.readableBytes()];
		content.readBytes(bts);
		String result = null;
		if(msg.getMethod() == HttpMethod.GET) {
			String url = msg.getUri().toString();
			result =JSON.toJSONString(UrlUtil.parse(url).params);
			doGet(result);
			
		}else if(msg.getMethod() == HttpMethod.POST) {
			//result = "post method and paramters is "+ new String(bts);
			doPost(new String(bts,"utf-8"));
		}
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
		response.headers().set("content-Type","text/html;charset=UTF-8");
		StringBuilder sb = new StringBuilder();
		sb.append("OK");
		ByteBuf responseBuf = Unpooled.copiedBuffer(sb,CharsetUtil.UTF_8);
		response.content().writeBytes(responseBuf);
		responseBuf.release();
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
		}catch (Exception e) {
			e.printStackTrace();
		}
}
 
Example 17
Source File: HttpRequestDecoderTest.java    From qonduit with Apache License 2.0 5 votes vote down vote up
/**
 * Only /login requests are handled
 */
@Test(expected = QonduitException.class)
public void testVersionPost() throws Exception {
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/version");
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals("VersionRequest", results.iterator().next().getClass().getSimpleName());
}
 
Example 18
Source File: HandlePublisher.java    From reactor-guice with Apache License 2.0 4 votes vote down vote up
private Mono<?> invokeMethod(HttpServerRequest request, HttpServerResponse response, Method method, Object handleObject, com.doopp.reactor.guice.RequestAttribute requestAttribute, ModelMap modelMap) {

        // value of url quest
        Map<String, List<String>> questParams = new HashMap<>();
        // values of form post
        Map<String, List<String>> formParams = new HashMap<>();
        // values of file upload
        Map<String, List<FileUpload>> fileParams = new HashMap<>();
        // get results
        this.queryParams(request, questParams);

        Mono<Object[]> objectMono;

        if (request.method() == HttpMethod.POST || request.method() == HttpMethod.PUT || request.method() == HttpMethod.DELETE) {
            objectMono = request.receive()
                .aggregate()
                .flatMap(byteBuf -> {
                    this.formParams(request, byteBuf, formParams, fileParams);
                    return methodParams(
                            method,
                            request,
                            response,
                            requestAttribute,
                            modelMap,
                            byteBuf,
                            questParams,
                            formParams,
                            fileParams
                    );
                });
        } else {
                // this.formParams(request, null, formParams, fileParams);
                objectMono = methodParams(
                        method,
                        request,
                        response,
                        requestAttribute,
                        modelMap,
                        null,
                        questParams,
                        formParams,
                        fileParams
                );
        }
        return objectMono.flatMap(oo -> {
            fileParams
                    .forEach((name, fileUploads)->fileUploads
                            .forEach(ReferenceCounted::release));
            try {
                Object result = method.invoke(handleObject, oo);
                return (result instanceof Mono<?>) ? (Mono<?>) result : Mono.just(result);
            } catch (Exception e) {
                return Mono.error(e);
            }
        });
    }
 
Example 19
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));
}
 
Example 20
Source File: HttpRequestDecoderTest.java    From timely with Apache License 2.0 4 votes vote down vote up
@Test
public void testQueryEmptyTags() throws Exception {
// @formatter:off
    String content =
            "{\n"+
                    "    \"start\": 1356998400,\n"+
                    "    \"end\": 1356998460,\n"+
                    "    \"queries\": [\n"+
                    "        {\n"+
                    "            \"aggregator\": \"sum\",\n"+
                    "            \"metric\": \"sys.cpu.user\",\n"+
                    "            \"rate\": \"true\",\n"+
                    "            \"rateOptions\": \n"+
                    "                {\"counter\":false,\"counterMax\":100,\"resetValue\":0},\n"+
                    "            \"tags\":[]" +
                    "        }\n"+
                    "    ]\n"+
                    "}";
    // @formatter:on
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/api/query");
    request.content().writeBytes(content.getBytes());
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(QueryRequest.class, results.iterator().next().getClass());
    QueryRequest query = (QueryRequest) results.iterator().next();
    Assert.assertEquals(1356998400, query.getStart());
    Assert.assertEquals(1356998460, query.getEnd());

    Assert.assertEquals(1, query.getQueries().size());
    Iterator<SubQuery> iter = query.getQueries().iterator();
    SubQuery first = iter.next();
    Assert.assertEquals(true, first.isMetricQuery());
    Assert.assertEquals(false, first.isTsuidQuery());
    Assert.assertEquals("sum", first.getAggregator());
    Assert.assertEquals("sys.cpu.user", first.getMetric());
    Assert.assertEquals(true, first.isRate());
    RateOption firstRateOption = first.getRateOptions();
    Assert.assertEquals(false, firstRateOption.isCounter());
    Assert.assertEquals(100, firstRateOption.getCounterMax());
    Assert.assertEquals(0, firstRateOption.getResetValue());
    Assert.assertEquals(false, first.getDownsample().isPresent());
    Assert.assertEquals(0, first.getTags().size());
    query.validate();

}