io.netty.handler.codec.http.QueryStringEncoder Java Examples

The following examples show how to use io.netty.handler.codec.http.QueryStringEncoder. 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: ProjectionManagerHttp.java    From esjc with MIT License 6 votes vote down vote up
@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);
}
 
Example #2
Source File: AbstractHttpSparknginClient.java    From Sparkngin with GNU Affero General Public License v3.0 6 votes vote down vote up
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) ;
  }
}
 
Example #3
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testCookieExpandedObjectTestOnlyAdditionalPropertiesFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/cookieTests/objectTests/onlyAdditionalProperties").getGet();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/cookieTests/objectTests/onlyAdditionalProperties",
    HttpMethod.GET,
    true,
    validationHandler,
    (routingContext) -> {
      routingContext.response().setStatusCode(200).setStatusMessage("OK").end();
    }
  );

  QueryStringEncoder params = new QueryStringEncoder("/");
  params.addParam("param1", Integer.toString(5));
  params.addParam("param2", "a");
  params.addParam("wellKnownParam", "hello");

  testRequestWithCookies(HttpMethod.GET, "/cookieTests/objectTests/onlyAdditionalProperties", params.toUri().getRawQuery(), 400, errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #4
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testCookieExpandedObjectTestOnlyAdditionalPropertiesFailure()
        throws Exception {
    Operation op = testSpec.getPaths()
            .get("/cookieTests/objectTests/onlyAdditionalProperties")
            .getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/cookieTests/objectTests/onlyAdditionalProperties",
            HttpMethod.GET, true, validationHandler, (routingContext) -> {
                routingContext.response().setStatusCode(200)
                        .setStatusMessage("OK").end();
            });

    QueryStringEncoder params = new QueryStringEncoder("/");
    params.addParam("param1", Integer.toString(5));
    params.addParam("param2", "a");
    params.addParam("wellKnownParam", "hello");

    testRequestWithCookies(HttpMethod.GET,
            "/cookieTests/objectTests/onlyAdditionalProperties",
            params.toUri().getRawQuery(), 400,
            errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #5
Source File: HTTPRequestValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #6
Source File: HTTPRequestValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: HTTPRequestValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: QueryParametersTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void call_percent_character() throws Exception {
    wireMockRule.stubFor(get(urlPathEqualTo("/team/my_team")).willReturn(ok()));

    URI target = new URIBuilder("http://localhost:8082/test/my_team")
            .addParameter("username", "toto")
            .addParameter("password", "password%")
            .build();

    HttpResponse response = Request.Get(target).execute().returnResponse();

    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    QueryStringEncoder encoder = new QueryStringEncoder("/team/my_team");
    encoder.addParam("username", "toto");
    encoder.addParam("password", "password%");

    wireMockRule.verify(getRequestedFor(urlEqualTo(encoder.toString())));
}
 
Example #9
Source File: QueryParametersTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void call_multiple_characters() throws Exception {
    wireMockRule.stubFor(get(urlPathEqualTo("/team/my_team")).willReturn(ok()));
    String query = "RECHERCHE,35147,8;RECHERCHE,670620,1";

    URI target = new URIBuilder("http://localhost:8082/test/my_team")
            .addParameter("q", "RECHERCHE,35147,8;RECHERCHE,670620,1")
            .build();

    HttpResponse response = Request.Get(target).execute().returnResponse();

    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    QueryStringEncoder encoder = new QueryStringEncoder("/team/my_team");
    encoder.addParam("q", query);

    wireMockRule.verify(getRequestedFor(urlEqualTo(encoder.toString())));
}
 
Example #10
Source File: QueryParametersTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void call_get_query_with_multiple_parameter_values() throws Exception {
    wireMockRule.stubFor(get(urlPathEqualTo("/team/my_team")).willReturn(ok()));

    URI target = new URIBuilder("http://localhost:8082/test/my_team")
            .addParameter("country", "fr")
            .addParameter("country", "es")
            .addParameter("type", "MAG")
            .build();

    HttpResponse response = Request.Get(target).execute().returnResponse();

    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    QueryStringEncoder encoder = new QueryStringEncoder("/team/my_team");
    encoder.addParam("country", "fr");
    encoder.addParam("country", "es");
    encoder.addParam("type", "MAG");

    wireMockRule.verify(getRequestedFor(urlEqualTo(encoder.toString())));
}
 
Example #11
Source File: VxApiRouteHandlerParamCheckImpl.java    From VX-API-Gateway with MIT License 6 votes vote down vote up
/**
 * 加载用户请求映射到后台的参数
 * 
 * @param rctHeaders
 *          用户请求的Header
 * @param rctQuerys
 *          用户请求的Query
 * @param reqPaths
 *          Path参数
 * @param reqHeaderParam
 *          请求后端服务的Header
 * @param reqQueryParam
 *          请求后端服务的QueryParam
 * @param reqBodyParam
 *          请求后端服务的BodyParam
 */
private void loadRequestMapParams(Map<String, VxApiParamOptions> thisMapParam, MultiMap rctHeaders, MultiMap rctQuerys, MultiMap reqPaths,
		MultiMap reqHeaderParam, QueryStringEncoder reqQueryParam, QueryStringEncoder reqBodyParam) {
	if (thisMapParam == null || thisMapParam.isEmpty()) {
		return;
	}
	for (VxApiParamOptions options : thisMapParam.values()) {
		String param;
		if (options.getApiParamPosition() == ParamPositionEnum.HEADER) {
			param = rctHeaders.get(options.getApiParamName());
		} else {
			param = rctQuerys.get(options.getApiParamName());
		}
		if (param == null) {
			continue;
		}
		loadParams(options.getSerParamPosition(), options.getSerParamName(), param, reqPaths, reqHeaderParam, reqQueryParam, reqBodyParam);
	}
}
 
Example #12
Source File: RecurlyClient.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Transactions> getTransactionsForAccount(String accountID, @Nullable Date beginTime, @Nullable Date endTime) {
    if (Strings.isNullOrEmpty(accountID)) {
        throw new IllegalArgumentException(ACCOUNT_ID_NULL);
    }

    QueryStringEncoder encoder =
            new QueryStringEncoder(Account.Tags.URL_RESOURCE + "/" + accountID + Transaction.Tags.URL_RESOURCE);
    DateFormat df = new SimpleDateFormat(ISO_8601_DATE_TIME_FORMAT);
    if (beginTime != null) {
        encoder.addParam("begin_time", df.format(beginTime));
    }
    if (endTime != null) {
        encoder.addParam("end_time", df.format(endTime));
    }

    AsyncTimer requestAsyncTimer = requestTaggingAsyncTimer.tag("op", "getTransactionsForAccount");
    return requestAsyncTimer.time(doGET(encoder.toString(), Transactions.class));
}
 
Example #13
Source File: AppLaunchHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
	Client client = factory.get(ctx.channel());
	QueryStringEncoder encoder = getUrl(req);
	SessionHandoff handoff = new SessionHandoff();
	handoff.setIp(getIp(ctx.channel()));
	handoff.setPersonId(client.getPrincipalId());
	handoff.setUrl(encoder.toString());
	handoff.setUsername(client.getPrincipalName());
	String token = appHandoffDao.newToken(handoff);
	encoder.addParam(PARAM_TOKEN, token);
	return redirect(encoder.toString());
}
 
Example #14
Source File: HTTPRequestValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #15
Source File: TestRequest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param encoder
 * @return
 */
public static Consumer<HttpRequest<Buffer>> cookie(QueryStringEncoder encoder) {
  return req -> {
    try {
      String rawQuery = encoder.toUri().getRawQuery();
      if (rawQuery != null && !rawQuery.isEmpty()) {
        req.putHeader("cookie", encoder.toUri().getRawQuery());
      }
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
  };
}
 
Example #16
Source File: QueryStringEncoderBenchmark.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static String nettyEncode(QueryParamGetters params) {
    final QueryStringEncoder encoder = new QueryStringEncoder("", StandardCharsets.UTF_8);
    for (Entry<String, String> e : params) {
        encoder.addParam(e.getKey(), e.getValue());
    }
    return encoder.toString();
}
 
Example #17
Source File: RouteUtils.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String expandQuery(String uri, @Nullable Multimap<String, Object> values) {
    if (values == null) {
        return uri;
    }
    QueryStringEncoder encoder = new QueryStringEncoder(uri);
    values.forEach((key, value) -> value.forEach(o -> encoder.addParam(key, String.valueOf(o))));
    return encoder.toString();
}
 
Example #18
Source File: ProjectionManagerHttp.java    From esjc with MIT License 5 votes vote down vote up
@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);
}
 
Example #19
Source File: ProjectionManagerHttp.java    From esjc with MIT License 5 votes vote down vote up
@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);
}
 
Example #20
Source File: RequestInfo.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public QueryStringEncoder toQueryString(String prefix) {
	QueryStringEncoder encoder = new QueryStringEncoder(prefix + subpath);
	if(queryParameters != null) {
		for(Map.Entry<String, List<String>> e: queryParameters.entrySet()) {
			if(e.getValue().isEmpty()) {
				encoder.addParam(e.getKey(), "");
			}
			else {
				e.getValue().stream().forEach((v) -> encoder.addParam(e.getKey(), v));
			}
		}
	}
	return encoder;
}
 
Example #21
Source File: TunnelClientSocketClientHandler.java    From arthas with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        String text = textFrame.text();

        logger.info("receive TextWebSocketFrame: {}", text);

        QueryStringDecoder queryDecoder = new QueryStringDecoder(text);
        Map<String, List<String>> parameters = queryDecoder.parameters();
        List<String> methodList = parameters.get("method");
        String method = null;
        if (methodList != null && !methodList.isEmpty()) {
            method = methodList.get(0);
        }

        if ("agentRegister".equals(method)) {
            List<String> idList = parameters.get("id");
            if (idList != null && !idList.isEmpty()) {
                this.tunnelClient.setId(idList.get(0));
            }
            registerPromise.setSuccess();
        }

        if ("startTunnel".equals(method)) {
            QueryStringEncoder queryEncoder = new QueryStringEncoder(this.tunnelClient.getTunnelServerUrl());
            queryEncoder.addParam("method", "openTunnel");
            queryEncoder.addParam("clientConnectionId", parameters.get("clientConnectionId").get(0));
            queryEncoder.addParam("id", parameters.get("id").get(0));

            URI forwardUri = queryEncoder.toUri();

            logger.info("start ForwardClient, uri: {}", forwardUri);
            ForwardClient forwardClient = new ForwardClient(forwardUri,
                    new URI(this.tunnelClient.getLocalServerUrl()), tunnelClient.getEventLoopGroup());
            forwardClient.start();
        }

    }
}
 
Example #22
Source File: UserCredentialsAccessTokenProvider.java    From curiostack with MIT License 5 votes vote down vote up
private static ByteBuf createRefreshRequestContent(UserCredentials credentials) {
  QueryStringEncoder formEncoder = new QueryStringEncoder("");
  formEncoder.addParam("client_id", credentials.getClientId());
  formEncoder.addParam("client_secret", credentials.getClientSecret());
  formEncoder.addParam("refresh_token", credentials.getRefreshToken());
  formEncoder.addParam("grant_type", GRANT_TYPE);
  String contentWithQuestionMark = formEncoder.toString();

  ByteBuf content = Unpooled.buffer(contentWithQuestionMark.length() - 1);
  ByteBufUtil.writeAscii(content, contentWithQuestionMark.substring(1));
  return content;
}
 
Example #23
Source File: ValidationHandlerProcessorsIntegrationTest.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Test
public void testCookieParamsSimpleTypes(VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint(2);

  ValidationHandler validationHandler = ValidationHandlerBuilder
    .create(parser)
    .cookieParameter(param("param1", booleanSchema()))
    .cookieParameter(param("param2", intSchema()))
    .build();
  router
    .get("/testCookieParams")
    .handler(validationHandler)
    .handler(routingContext -> {
      RequestParameters params = routingContext.get("parsedParameters");
      routingContext
        .response()
        .setStatusMessage(
          params.cookieParameter("param1").toString() + params.cookieParameter("param2").toString()
        )
        .end();
    });

  QueryStringEncoder successParams = new QueryStringEncoder("/");
  successParams.addParam("param1", "true");
  successParams.addParam("param2", "10");

  testRequest(client, HttpMethod.GET, "/testCookieParams")
    .with(cookie(successParams))
    .expect(statusCode(200), statusMessage("true10"))
    .send(testContext, checkpoint);

  QueryStringEncoder failureParams = new QueryStringEncoder("/");
  failureParams.addParam("param1", "true");
  failureParams.addParam("param2", "bla");

  testRequest(client, HttpMethod.GET, "/testCookieParams")
    .with(cookie(failureParams))
    .expect(statusCode(400))
    .expect(badParameterResponse(
      ParameterProcessorException.ParameterProcessorErrorType.PARSING_ERROR,
      "param2",
      ParameterLocation.COOKIE
    ))
    .send(testContext, checkpoint);
}
 
Example #24
Source File: TunnelClient.java    From arthas with Apache License 2.0 4 votes vote down vote up
public ChannelFuture connect(boolean reconnect) throws SSLException, URISyntaxException, InterruptedException {
    QueryStringEncoder queryEncoder = new QueryStringEncoder(this.tunnelServerUrl);
    queryEncoder.addParam("method", "agentRegister");
    if (id != null) {
        queryEncoder.addParam("id", id);
    }
    // ws://127.0.0.1:7777/ws?method=agentRegister
    final URI agentRegisterURI = queryEncoder.toUri();

    logger.info("Try to register arthas agent, uri: {}", agentRegisterURI);

    String scheme = agentRegisterURI.getScheme() == null ? "ws" : agentRegisterURI.getScheme();
    final String host = agentRegisterURI.getHost() == null ? "127.0.0.1" : agentRegisterURI.getHost();
    final int port;
    if (agentRegisterURI.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = agentRegisterURI.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        throw new IllegalArgumentException("Only WS(S) is supported. tunnelServerUrl: " + tunnelServerUrl);
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    WebSocketClientHandshaker newHandshaker = WebSocketClientHandshakerFactory.newHandshaker(agentRegisterURI,
            WebSocketVersion.V13, null, true, new DefaultHttpHeaders());
    final WebSocketClientProtocolHandler websocketClientHandler = new WebSocketClientProtocolHandler(newHandshaker);
    final TunnelClientSocketClientHandler handler = new TunnelClientSocketClientHandler(TunnelClient.this);

    Bootstrap bs = new Bootstrap();

    bs.group(eventLoopGroup).channel(NioSocketChannel.class).remoteAddress(host, port)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ChannelPipeline p = ch.pipeline();
                    if (sslCtx != null) {
                        p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                    }

                    p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), websocketClientHandler,
                            handler);
                }
            });

    ChannelFuture connectFuture = bs.connect();
    if (reconnect) {
        connectFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.cause() != null) {
                    logger.error("connect to tunnel server error, uri: {}", tunnelServerUrl, future.cause());
                }
            }
        });
    }
    channel = connectFuture.sync().channel();

    return handler.registerFuture();
}
 
Example #25
Source File: AppLaunchHandler.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private QueryStringEncoder getUrl(FullHttpRequest request) throws Exception {
	RequestInfo info = parseUrl(request, PATH);
	logger.debug("Extracted request info [{}]", info);
	String prefix = String.format(URL_FORMAT, appHost, info.getType().name().toLowerCase());
	return info.toQueryString(prefix);
}
 
Example #26
Source File: AuthorizeHandler.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private FullHttpResponse redirectError(String uri, String state, String error) {
   QueryStringEncoder enc = encoder(uri, state);
   enc.addParam(OAuthUtil.ATTR_ERROR, error);
   return redirect(enc);
}
 
Example #27
Source File: AuthorizeHandler.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private FullHttpResponse redirectSuccess(String uri, String state, String code) {
   QueryStringEncoder enc = encoder(uri, state);
   enc.addParam(OAuthUtil.ATTR_CODE, code);
   return redirect(enc);
}
 
Example #28
Source File: AuthorizeHandler.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private FullHttpResponse redirect(QueryStringEncoder encoder) {
   DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
   response.headers().add(HttpHeaders.LOCATION, encoder.toString());
   return response;
}
 
Example #29
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static String getHlsUri(String videoStreamUrl, UUID recordingId, String exp, String sig) {
   QueryStringEncoder enc = new QueryStringEncoder(videoStreamUrl + "/hls/" + recordingId + "/playlist.m3u8");
   enc.addParam("exp", exp);
   enc.addParam("sig", sig);
   return enc.toString();
}
 
Example #30
Source File: HttpUploadClient.java    From tools-journey with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
}