io.vertx.core.http.WebSocketConnectOptions Java Examples

The following examples show how to use io.vertx.core.http.WebSocketConnectOptions. 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: HttpTermServerBase.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Test
public void testExternalAuthProviderFails(TestContext context) throws Exception {
  AtomicInteger count = new AtomicInteger();
  AuthProvider authProvider = (authInfo, resultHandler) -> {
    count.incrementAndGet();
    resultHandler.handle(Future.failedFuture("not authenticated"));
  };
  Async async = context.async();
  server = createServer(context, new HttpTermOptions().setPort(8080));
  server.authProvider(authProvider);
  server.termHandler(term -> {
    context.fail();
  });
  server.listen(context.asyncAssertSuccess(server -> {
    HttpClient client = vertx.createHttpClient();
    WebSocketConnectOptions options = new WebSocketConnectOptions()
      .setPort(8080)
      .setURI(basePath + "/shell/websocket")
      .addHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("paulo:anothersecret".getBytes()));
    client.webSocket(options, context.asyncAssertFailure(ws -> {
      assertEquals(1, count.get());
      async.complete();
    }));
  }));
}
 
Example #2
Source File: HttpTermServerBase.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Test
public void testDifferentCharset(TestContext context) throws Exception {
  Async async = context.async();
  server = createServer(context, new HttpTermOptions().setPort(8080).setCharset("ISO_8859_1"));
  server.termHandler(term -> {
    term.write("\u20AC");
    term.close();
  });
  server.listen(context.asyncAssertSuccess(server -> {
    HttpClient client = vertx.createHttpClient();
    WebSocketConnectOptions options = new WebSocketConnectOptions()
      .setPort(8080)
      .setURI(basePath + "/shell/websocket")
      .addHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("paulo:anothersecret".getBytes()));
    client.webSocket(options, context.asyncAssertSuccess(ws -> {
      ws.handler(buf -> {
        context.assertTrue(Arrays.equals(new byte[]{63}, buf.getBytes()));
        async.complete();
      });
    }));
  }));
}
 
Example #3
Source File: HttpTermServerBase.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeymapFromFilesystem(TestContext context) throws Exception {
  URL url = TermServer.class.getResource(SSHTermOptions.DEFAULT_INPUTRC);
  File f = new File(url.toURI());
  Async async = context.async();
  server = createServer(context, new HttpTermOptions().setPort(8080).setIntputrc(f.getAbsolutePath()));
  server.termHandler(term -> {
    term.close();
    async.complete();
  });
  server.listen(context.asyncAssertSuccess(server -> {
    HttpClient client = vertx.createHttpClient();
    WebSocketConnectOptions options = new WebSocketConnectOptions()
      .setPort(8080)
      .setURI(basePath + "/shell/websocket")
      .addHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("paulo:anothersecret".getBytes()));
    client.webSocket(options, context.asyncAssertSuccess(ws -> {
      ws.handler(buf -> {
      });
    }));
  }));
}
 
Example #4
Source File: WebsocketClientUtil.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public void open(IpPort ipPort, String url, Handler<Void> onOpen, Handler<Void> onClose,
    Handler<Buffer> onMessage, Handler<Throwable> onException,
    Handler<Throwable> onConnectFailed) {
  HttpClientWithContext vertxHttpClient = websocketClientPool.getClient();
  vertxHttpClient.runOnContext(client -> {
    WebSocketConnectOptions options = new WebSocketConnectOptions();
    options.setHost(ipPort.getHostOrIp()).setPort(ipPort.getPort()).setURI(url)
        .setHeaders(getDefaultHeaders().addAll(getSignAuthHeaders(
            createSignRequest(HttpMethod.GET.name(), ipPort, new RequestParam(), url, new HashMap<>()))));
    client.webSocket(options, asyncResult -> {
      if (asyncResult.failed()) {
        onConnectFailed.handle(asyncResult.cause());
      } else {
        onOpen.handle(null);
        asyncResult.result().exceptionHandler(v -> {
          onException.handle(v);
          try {
            asyncResult.result().close();
          } catch (Exception err) {
            LOGGER.error("ws close error.", err);
          }
        });
        asyncResult.result().closeHandler(v -> {
          onClose.handle(v);
        });
        asyncResult.result().pongHandler(pong -> {
          // ignore, just prevent NPE.
        });
        asyncResult.result().frameHandler((frame) -> onMessage.handle(frame.binaryData()));
      }
    });
  });
}
 
Example #5
Source File: HttpTermServerBase.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecure(TestContext context) {
  Async async = context.async();
  server = createServer(context, new HttpTermOptions().setAuthOptions(
    new JsonObject()
      .put("provider", "shiro")
      .put("type", "PROPERTIES")
      .put("config", new JsonObject().put("properties_path", "classpath:test-auth.properties"))).setPort(8080));
  server.termHandler(term -> {
    term.write("hello");
  });
  server.listen(context.asyncAssertSuccess(server -> {
    HttpClient client = vertx.createHttpClient();
    client.webSocket(8080, "localhost", basePath + "/shell/websocket", context.asyncAssertFailure(err -> {
      // Retry now with auth
      WebSocketConnectOptions options = new WebSocketConnectOptions()
        .setPort(8080)
        .setURI(basePath + "/shell/websocket")
        .addHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("tim:sausages".getBytes()));
      client.webSocket(options, context.asyncAssertSuccess(ws -> {
        ws.handler(buf -> {
          context.assertEquals("hello", buf.toString());
          async.complete();
        });
      }));
    }));
  }));
}
 
Example #6
Source File: ConfigCenterClient.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public void doWatch(String configCenter)
    throws UnsupportedEncodingException, InterruptedException {
  CountDownLatch waiter = new CountDownLatch(1);
  IpPort ipPort = NetUtils.parseIpPortFromURI(configCenter);
  String url = uriConst.REFRESH_ITEMS + "?dimensionsInfo="
      + StringUtils.deleteWhitespace(URLEncoder.encode(serviceName, "UTF-8"));
  Map<String, String> headers = new HashMap<>();
  headers.put("x-domain-name", tenantName);
  if (ConfigCenterConfig.INSTANCE.getToken() != null) {
    headers.put("X-Auth-Token", ConfigCenterConfig.INSTANCE.getToken());
  }
  headers.put("x-environment", environment);

  HttpClientWithContext vertxHttpClient = HttpClients.getClient(ConfigCenterHttpClientOptionsSPI.CLIENT_NAME);

  vertxHttpClient.runOnContext(client -> {
    Map<String, String> authHeaders = new HashMap<>();
    authHeaderProviders.forEach(provider -> authHeaders.putAll(provider.getSignAuthHeaders(
        createSignRequest(null, configCenter + url, headers, null))));
    WebSocketConnectOptions options = new WebSocketConnectOptions();
    options.setHost(ipPort.getHostOrIp()).setPort(refreshPort).setURI(url)
        .setHeaders(new CaseInsensitiveHeaders().addAll(headers)
            .addAll(authHeaders));
    client.webSocket(options, asyncResult -> {
      if (asyncResult.failed()) {
        LOGGER.error(
            "watcher connect to config center {} refresh port {} failed. Error message is [{}]",
            configCenter,
            refreshPort,
            asyncResult.cause().getMessage());
        waiter.countDown();
      } else {
        {
          asyncResult.result().exceptionHandler(e -> {
            LOGGER.error("watch config read fail", e);
            stopHeartBeatThread();
            isWatching = false;
          });
          asyncResult.result().closeHandler(v -> {
            LOGGER.warn("watching config connection is closed accidentally");
            stopHeartBeatThread();
            isWatching = false;
          });

          asyncResult.result().pongHandler(pong -> {
            // ignore, just prevent NPE.
          });
          asyncResult.result().frameHandler(frame -> {
            Buffer action = frame.binaryData();
            LOGGER.info("watching config recieved {}", action);
            Map<String, Object> mAction = action.toJsonObject().getMap();
            if ("CREATE".equals(mAction.get("action"))) {
              //event loop can not be blocked,we just keep nothing changed in push mode
              refreshConfig(configCenter, false);
            } else if ("MEMBER_CHANGE".equals(mAction.get("action"))) {
              refreshMembers(memberdis);
            } else {
              parseConfigUtils.refreshConfigItemsIncremental(mAction);
            }
          });
          startHeartBeatThread(asyncResult.result());
          isWatching = true;
          waiter.countDown();
        }
      }
    });
  });
  waiter.await();
}