@Override public CompletableFuture<Void> create(String name, String query, CreateOptions options, UserCredentials userCredentials) { checkArgument(!isNullOrEmpty(name), "name is null or empty"); checkArgument(!isNullOrEmpty(query), "query is null or empty"); checkNotNull(options, "options is null"); QueryStringEncoder queryStringEncoder = new QueryStringEncoder(projectionsUri(options.mode)); queryStringEncoder.addParam("name", name); queryStringEncoder.addParam("type", "JS"); queryStringEncoder.addParam("enabled", Boolean.toString(options.enabled)); switch (options.mode) { case ONE_TIME: queryStringEncoder.addParam("checkpoints", Boolean.toString(options.checkpoints)); case CONTINUOUS: queryStringEncoder.addParam("emit", Boolean.toString(options.emit)); queryStringEncoder.addParam("trackemittedstreams", Boolean.toString(options.trackEmittedStreams)); } return post(queryStringEncoder.toString(), query, userCredentials, HttpResponseStatus.CREATED); }
@Test public void testQueryParamsWithIncludedTypes() throws Exception { HTTPRequestValidationHandler validationHandler = HTTPRequestValidationHandler.create().addQueryParam("param1", ParameterType.BOOL, true).addQueryParam("param2", ParameterType.INT, true); router.get("/testQueryParams").handler(validationHandler); router.get("/testQueryParams").handler(routingContext -> { RequestParameters params = routingContext.get("parsedParameters"); routingContext.response().setStatusMessage(params.queryParameter("param1").getBoolean().toString() + params .queryParameter("param2").getInteger().toString()).end(); }).failureHandler(generateFailureHandler(false)); QueryStringEncoder encoder = new QueryStringEncoder("/testQueryParams"); String param1 = getSuccessSample(ParameterType.BOOL).getBoolean().toString(); String param2 = getSuccessSample(ParameterType.INT).getInteger().toString(); encoder.addParam("param1", param1); encoder.addParam("param2", param2); testRequest(HttpMethod.GET, encoder.toString(), 200, param1 + param2); }
@Test public void testQueryParamsArrayAndPathParamsWithIncludedTypes() throws Exception { HTTPRequestValidationHandler validationHandler = HTTPRequestValidationHandler.create().addPathParam("pathParam1", ParameterType.INT).addQueryParamsArray("awesomeArray", ParameterType.EMAIL, true).addQueryParam("anotherParam", ParameterType.DOUBLE, true); router.get("/testQueryParams/:pathParam1").handler(validationHandler); router.get("/testQueryParams/:pathParam1").handler(routingContext -> { RequestParameters params = routingContext.get("parsedParameters"); routingContext.response().setStatusMessage(params.pathParameter("pathParam1").getInteger().toString() + params .queryParameter("awesomeArray").getArray().size() + params.queryParameter("anotherParam").getDouble() .toString()).end(); }).failureHandler(generateFailureHandler(false)); String pathParam = getSuccessSample(ParameterType.INT).getInteger().toString(); String arrayValue1 = getSuccessSample(ParameterType.EMAIL).getString(); String arrayValue2 = getSuccessSample(ParameterType.EMAIL).getString(); String anotherParam = getSuccessSample(ParameterType.DOUBLE).getDouble().toString(); QueryStringEncoder encoder = new QueryStringEncoder("/testQueryParams/" + URLEncoder.encode(pathParam, "UTF-8")); encoder.addParam("awesomeArray", arrayValue1); encoder.addParam("awesomeArray", arrayValue2); encoder.addParam("anotherParam", anotherParam); testRequest(HttpMethod.GET, encoder.toString(), 200, pathParam + "2" + anotherParam); }
@Test public void testQueryParamsArrayAndPathParamsFailureWithIncludedTypes() throws Exception { HTTPRequestValidationHandler validationHandler = HTTPRequestValidationHandler.create().addPathParam("pathParam1", ParameterType.INT).addQueryParamsArray("awesomeArray", ParameterType.EMAIL, true).addQueryParam("anotherParam", ParameterType.DOUBLE, true); router.get("/testQueryParams/:pathParam1").handler(validationHandler); router.get("/testQueryParams/:pathParam1").handler(routingContext -> { RequestParameters params = routingContext.get("parsedParameters"); routingContext.response().setStatusMessage(params.pathParameter("pathParam1").getInteger().toString() + params .queryParameter("awesomeArray").getArray().size() + params.queryParameter("anotherParam").getDouble() .toString()).end(); }).failureHandler(generateFailureHandler(true)); String pathParam = getSuccessSample(ParameterType.INT).getInteger().toString(); String arrayValue1 = getFailureSample(ParameterType.EMAIL); String arrayValue2 = getSuccessSample(ParameterType.EMAIL).getString(); String anotherParam = getSuccessSample(ParameterType.DOUBLE).getDouble().toString(); QueryStringEncoder encoder = new QueryStringEncoder("/testQueryParams/" + URLEncoder.encode(pathParam, "UTF-8")); encoder.addParam("awesomeArray", arrayValue1); encoder.addParam("awesomeArray", arrayValue2); encoder.addParam("anotherParam", anotherParam); testRequest(HttpMethod.GET, encoder.toString(), 400, "failure:NO_MATCH"); }
/** * {@inheritDoc} */ @Override public HttpRequest convertRequest(Envelope request) { ByteBuf requestBuffer = Unpooled.buffer(request.getSerializedSize()); try { OutputStream outputStream = new ByteBufOutputStream(requestBuffer); request.writeTo(outputStream); outputStream.flush(); } catch (IOException e) { // deliberately ignored, as the underlying operation doesn't involve I/O } String host = ((InetSocketAddress) channel().remoteAddress()).getAddress().getHostAddress(); String uriPath = String.format("%s%s/%s", path, request.getService(), request.getMethod()); FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, new QueryStringEncoder(uriPath).toString(), requestBuffer); httpRequest.headers().set(HttpHeaders.Names.HOST, host); httpRequest.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, requestBuffer.readableBytes()); httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, QuartzProtocol.CONTENT_TYPE); return httpRequest; }
public void sendGet(Message message, long timeout) throws Exception { synchronized(waitingAckMessages) { if(waitingAckMessages.size() >= bufferSize) { waitingAckMessages.wait(timeout); if(waitingAckMessages.size() >= bufferSize) { throw new TimeoutException("fail to send the message in " + timeout + "ms") ; } } QueryStringEncoder encoder = new QueryStringEncoder(path); encoder.addParam("data", toStringData(message)); client.get(encoder.toString()); sendCount++ ; String messageId = message.getHeader().getKey() ; waitingAckMessages.put(messageId, message) ; } }
@Override public CompletableFuture<Void> update(String name, String query, UpdateOptions options, UserCredentials userCredentials) { checkArgument(!isNullOrEmpty(name), "name is null or empty"); checkArgument(!isNullOrEmpty(query), "query is null or empty"); checkNotNull(options, "options is null"); QueryStringEncoder queryStringEncoder = new QueryStringEncoder(projectionUri(name) + "/query"); queryStringEncoder.addParam("type", "JS"); if (options.emit != null) { queryStringEncoder.addParam("emit", Boolean.toString(options.emit)); } return put(queryStringEncoder.toString(), query, userCredentials, HttpResponseStatus.OK); }
@Override public CompletableFuture<Void> delete(String name, DeleteOptions options, UserCredentials userCredentials) { checkArgument(!isNullOrEmpty(name), "name is null or empty"); checkNotNull(options, "options is null"); QueryStringEncoder queryStringEncoder = new QueryStringEncoder(projectionUri(name)); queryStringEncoder.addParam("deleteStateStream", Boolean.toString(options.deleteStateStream)); queryStringEncoder.addParam("deleteCheckpointStream", Boolean.toString(options.deleteCheckpointStream)); queryStringEncoder.addParam("deleteEmittedStreams", Boolean.toString(options.deleteEmittedStreams)); return delete(queryStringEncoder.toString(), userCredentials, HttpResponseStatus.OK); }
private URI encodeQueryParameters(Request request, String endpointUri) throws MalformedURLException, URISyntaxException { QueryStringEncoder encoder = new QueryStringEncoder(endpointUri); if (request.parameters() != null && !request.parameters().isEmpty()) { for (Map.Entry<String, List<String>> queryParam : request.parameters().entrySet()) { if (queryParam.getValue() != null) { for (String value : queryParam.getValue()) { encoder.addParam(queryParam.getKey(), (value != null && !value.isEmpty()) ? value : null); } } } } return encoder.toUri(); }
public void sendGet(String key, Map<String, String> params, long timeout) throws Exception { Request request = new Request("GET", key, params, null) ; MethodMonitor methodMonitor = monitor.getMethodMonitor("GET"); methodMonitor.incrCount(); synchronized(waitingRequests) { if(waitingRequests.size() >= bufferSize) { waitingRequests.wait(timeout); if(waitingRequests.size() >= bufferSize) { methodMonitor.incrClientLimitTimeoutCount(); ; throw new TimeoutException("fail to send the message in " + timeout + "ms") ; } } try { QueryStringEncoder encoder = new QueryStringEncoder(path); if(params != null) { for(Map.Entry<String, String> entry : params.entrySet()) { encoder.addParam(entry.getKey(), entry.getValue()); } } ChannelFuture future = client.get(encoder.toString()); handleFuture(future, request) ; } catch(Exception ex) { methodMonitor.incrUnknownErrorCount(); throw ex ; } } }
@Test public void testQueryParamsFailureWithIncludedTypes() throws Exception { HTTPRequestValidationHandler validationHandler = HTTPRequestValidationHandler.create().addQueryParam("param1", ParameterType.BOOL, true).addQueryParam("param2", ParameterType.INT, true); router.get("/testQueryParams").handler(validationHandler); router.get("/testQueryParams").handler(routingContext -> { RequestParameters params = routingContext.get("parsedParameters"); routingContext.response().setStatusMessage(params.queryParameter("param1").getBoolean().toString() + params .queryParameter("param2").getInteger().toString()); }).failureHandler(generateFailureHandler(true)); QueryStringEncoder encoder = new QueryStringEncoder("/testQueryParams"); encoder.addParam("param1", getFailureSample(ParameterType.BOOL)); encoder.addParam("param2", getFailureSample(ParameterType.INT)); testRequest(HttpMethod.GET, encoder.toString(), 400, "failure:NO_MATCH"); }
private URI transformedUri() { if (null == params || params.isEmpty()) { return uri; } QueryStringEncoder encoder = new QueryStringEncoder(uri.toString()); for (Map.Entry<String, String> entry : params.entrySet()) { encoder.addParam(entry.getKey(), entry.getValue()); } return URI.create(encoder.toString()); }
/** * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload * due to limitation on request size). * * @return the list of headers that will be used in every example after **/ private static List<Entry<String, String>> formget( Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception { // XXX /formget // No use of HttpPostRequestEncoder since not a POST Channel channel = bootstrap.connect(host, port).sync().channel(); // Prepare the HTTP request. QueryStringEncoder encoder = new QueryStringEncoder(get); // add Form attribute encoder.addParam("getform", "GET"); encoder.addParam("info", "first value"); encoder.addParam("secondinfo", "secondvalue ���&"); // not the big one since it is not compatible with GET size // encoder.addParam("thirdinfo", textArea); encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n"); encoder.addParam("Send", "Send"); URI uriGet = new URI(encoder.toString()); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); HttpHeaders headers = request.headers(); headers.set(HttpHeaderNames.HOST, host); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE); headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaderNames.REFERER, uriSimple.toString()); headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); //connection will not close but needed // headers.set("Connection","keep-alive"); // headers.set("Keep-Alive","300"); headers.set( HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode( new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")) ); // send request channel.writeAndFlush(request); // Wait for the server to close the connection. channel.closeFuture().sync(); // convert headers to list return headers.entries(); }
/** * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload * due to limitation on request size). * * @return the list of headers that will be used in every example after **/ private static List<Entry<String, String>> formget( Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception { // XXX /formget // No use of HttpPostRequestEncoder since not a POST Channel channel = bootstrap.connect(host, port).sync().channel(); // Prepare the HTTP request. QueryStringEncoder encoder = new QueryStringEncoder(get); // add Form attribute encoder.addParam("getform", "GET"); encoder.addParam("info", "first value"); encoder.addParam("secondinfo", "secondvalue ���&"); // not the big one since it is not compatible with GET size // encoder.addParam("thirdinfo", textArea); encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n"); encoder.addParam("Send", "Send"); URI uriGet = new URI(encoder.toString()); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); HttpHeaders headers = request.headers(); headers.set(HttpHeaders.Names.HOST, host); headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + ',' + HttpHeaders.Values.DEFLATE); headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaders.Names.REFERER, uriSimple.toString()); headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaders.Names.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); //connection will not close but needed // headers.set("Connection","keep-alive"); // headers.set("Keep-Alive","300"); headers.set( HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode( new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")) ); // send request List<Entry<String, String>> entries = headers.entries(); channel.writeAndFlush(request); // Wait for the server to close the connection. channel.closeFuture().sync(); return entries; }
/** * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload due to limitation * on request size). * * @return the list of headers that will be used in every example after **/ private static List<Entry<String, String>> formGet(Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception { // Start the connection attempt. // No use of HttpPostRequestEncoder since not a POST Channel channel = bootstrap.connect(host, port).sync().channel(); // Prepare the HTTP request. QueryStringEncoder encoder = new QueryStringEncoder(get); // add Form attribute encoder.addParam("getform", "GET"); encoder.addParam("info", "first value"); encoder.addParam("secondinfo", "secondvalue ���&"); // not the big one since it is not compatible with GET size // encoder.addParam("thirdinfo", textArea); encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n"); encoder.addParam("Send", "Send"); URI uriGet; try { uriGet = new URI(encoder.toString()); } catch (URISyntaxException e) { logger.log(Level.WARNING, "Error: ", e); return null; } FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); HttpHeaders headers = request.headers(); headers.set(HttpHeaders.Names.HOST, host); headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + ',' + HttpHeaders.Values.DEFLATE); headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaders.Names.REFERER, uriSimple.toString()); headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaders.Names.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // send request List<Entry<String, String>> entries = headers.entries(); channel.writeAndFlush(request).sync(); // Wait for the server to close the connection. channel.closeFuture().sync(); return entries; }
/** * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload due to limitation * on request size). * * @return the list of headers that will be used in every example after **/ private static List<Entry<String, String>> formGet(Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception { // Start the connection attempt. // No use of HttpPostRequestEncoder since not a POST Channel channel = bootstrap.connect(host, port).sync().channel(); // Prepare the HTTP request. QueryStringEncoder encoder = new QueryStringEncoder(get); // add Form attribute encoder.addParam("getform", "GET"); encoder.addParam("info", "first value"); encoder.addParam("secondinfo", "secondvalue ���&"); // not the big one since it is not compatible with GET size // encoder.addParam("thirdinfo", textArea); encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n"); encoder.addParam("Send", "Send"); URI uriGet; try { uriGet = new URI(encoder.toString()); } catch (URISyntaxException e) { logger.log(Level.WARNING, "Error: ", e); return null; } FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); HttpHeaders headers = request.headers(); headers.set(HttpHeaders.Names.HOST, host); headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP.toString() + ',' + HttpHeaders.Values.DEFLATE.toString()); headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaders.Names.REFERER, uriSimple.toString()); headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaders.Names.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // send request List<Entry<String, String>> entries = headers.entries(); channel.writeAndFlush(request).sync(); // Wait for the server to close the connection. channel.closeFuture().sync(); return entries; }
@Override public <O extends Message> ListenableFuture<O> encodeMethodCall(final ClientMethod<O> method, Message input) { clientLogger.logMethodCall(method); final JsonResponseFuture<O> responseFuture = handler.newProvisionalResponse(method); JsonObject request = new JsonRpcRequest(method.serviceName(), method.name(), new JsonPrimitive(responseFuture.requestId()), Messages.toJson(input)).toJson(); ByteBuf requestBuffer = Unpooled.buffer(); JsonWriter writer = new JsonWriter( new OutputStreamWriter(new ByteBufOutputStream(requestBuffer), Charsets.UTF_8)); GSON.toJson(request, writer); try { writer.flush(); } catch (IOException ioe) { // Deliberately ignored, as this doesn't involve any I/O } String host = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress(); QueryStringEncoder encoder = new QueryStringEncoder(rpcPath); encoder.addParam("pp", "0"); HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, encoder.toString(), requestBuffer); httpRequest.headers().set(HttpHeaders.Names.HOST, host); httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, JsonRpcProtocol.CONTENT_TYPE); httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, requestBuffer.readableBytes()); channel.writeAndFlush(httpRequest).addListener(new GenericFutureListener<ChannelFuture>() { public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { clientLogger.logLinkError(method, future.cause()); handler.finish(responseFuture.requestId()); responseFuture.setException(future.cause()); } } }); return responseFuture; }