org.apache.thrift.transport.THttpClient Java Examples

The following examples show how to use org.apache.thrift.transport.THttpClient. 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: ThriftOverHttp1Test.java    From armeria with Apache License 2.0 7 votes vote down vote up
@Override
protected TTransport newTransport(String uri, HttpHeaders headers) throws TTransportException {
    final SSLContext sslContext;
    try {
        sslContext = SSLContextBuilder.create()
                                      .loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
                                      .build();
    } catch (GeneralSecurityException e) {
        throw new TTransportException("failed to initialize an SSL context", e);
    }

    final THttpClient client = new THttpClient(
            uri, HttpClientBuilder.create()
                                  .setSSLHostnameVerifier((hostname, session) -> true)
                                  .setSSLContext(sslContext)
                                  .build());
    client.setCustomHeaders(
            headers.names().stream()
                   .collect(toImmutableMap(AsciiString::toString,
                                           name -> String.join(", ", headers.getAll(name)))));
    return client;
}
 
Example #2
Source File: TestThriftSpnegoHttpFallbackServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Override
protected void talkToThriftServer(String url, int customHeaderSize) throws Exception {
  // Close httpClient and THttpClient automatically on any failures
  try (
    CloseableHttpClient httpClient = createHttpClient();
    THttpClient tHttpClient = new THttpClient(url, httpClient)
  ) {
    tHttpClient.open();
    if (customHeaderSize > 0) {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < customHeaderSize; i++) {
        sb.append("a");
      }
      tHttpClient.setCustomHeader(HttpHeaders.USER_AGENT, sb.toString());
    }

    TProtocol prot = new TBinaryProtocol(tHttpClient);
    Hbase.Client client = new Hbase.Client(prot);
    TestThriftServer.createTestTables(client);
    TestThriftServer.checkTableList(client);
    TestThriftServer.dropTestTables(client);
  }
}
 
Example #3
Source File: Authenticator.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private boolean authenticate() throws EntitlementProxyException {
    boolean isAuthenticated;
    try {
        THttpClient client = new THttpClient(serverUrl);
        TProtocol protocol = new TCompactProtocol(client);
        AuthenticatorService.Client authClient = new AuthenticatorService.Client(protocol);
        client.open();
        sessionId = authClient.authenticate(userName, password);
        client.close();
        isAuthenticated = true;
    } catch (Exception e) {
        throw new EntitlementProxyException("Error while authenticating with ThriftAuthenticator", e);
    }
    return isAuthenticated;

}
 
Example #4
Source File: ThriftConnection.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Override
public Pair<THBaseService.Client, TTransport> getClient() throws IOException {
  Preconditions.checkArgument(connection.getHost().startsWith("http"),
      "http client host must start with http or https");
  String url = connection.getHost() + ":" + connection.getPort();
  try {
    THttpClient httpClient = new THttpClient(url, connection.getHttpClient());
    for (Map.Entry<String, String> header : customHeader.entrySet()) {
      httpClient.setCustomHeader(header.getKey(), header.getValue());
    }
    httpClient.open();
    TProtocol prot = new TBinaryProtocol(httpClient);
    THBaseService.Client client = new THBaseService.Client(prot);
    return new Pair<>(client, httpClient);
  } catch (TTransportException e) {
    throw new IOException(e);
  }

}
 
Example #5
Source File: Authenticator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private boolean authenticate() throws EntitlementProxyException {
    boolean isAuthenticated;
    try {
        THttpClient client = new THttpClient(serverUrl);
        TProtocol protocol = new TCompactProtocol(client);
        AuthenticatorService.Client authClient = new AuthenticatorService.Client(protocol);
        client.open();
        sessionId = authClient.authenticate(userName, password);
        client.close();
        isAuthenticated = true;
    } catch (Exception e) {
        throw new EntitlementProxyException("Error while authenticating with ThriftAuthenticator", e);
    }
    return isAuthenticated;

}
 
Example #6
Source File: ThriftClientPooledObjectFactory.java    From spring-thrift-starter with MIT License 6 votes vote down vote up
@Override
public void passivateObject(ThriftClientKey key, PooledObject<TServiceClient> p) throws Exception {
    ThriftClientPooledObject<TServiceClient> pooledObject = (ThriftClientPooledObject<TServiceClient>) p;
    TTransport transport = pooledObject.getObject().getOutputProtocol().getTransport();

    if (transport instanceof THttpClient) {
        ((THttpClient) transport).setCustomHeaders(null);
    } else {
        ((TLoadBalancerClient) transport).setCustomHeaders(null);
    }

    resetAndClose(p);

    super.passivateObject(key, pooledObject);

    if (pooledObject.getSpan() != null) {
        Span span = pooledObject.getSpan();
        span.finish();
    }
}
 
Example #7
Source File: HttpDoAsClient.java    From hbase with Apache License 2.0 5 votes vote down vote up
private Hbase.Client refresh(Hbase.Client client, THttpClient httpClient) {
  httpClient.setCustomHeader("doAs", doAsUser);
  if (secure) {
    try {
      httpClient.setCustomHeader("Authorization", generateTicket());
    } catch (GSSException e) {
      LOG.error("Kerberos authentication failed", e);
    }
  }
  return client;
}
 
Example #8
Source File: TestThriftSpnegoHttpServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Override
protected void talkToThriftServer(String url, int customHeaderSize) throws Exception {
  // Close httpClient and THttpClient automatically on any failures
  try (
      CloseableHttpClient httpClient = createHttpClient();
      THttpClient tHttpClient = new THttpClient(url, httpClient)
  ) {
    tHttpClient.open();
    if (customHeaderSize > 0) {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < customHeaderSize; i++) {
        sb.append("a");
      }
      tHttpClient.setCustomHeader(HttpHeaders.USER_AGENT, sb.toString());
    }

    TProtocol prot = new TBinaryProtocol(tHttpClient);
    Hbase.Client client = new Hbase.Client(prot);
    List<ByteBuffer> bbs = client.getTableNames();
    LOG.info("PRE-EXISTING {}", bbs.stream().
      map(b -> Bytes.toString(b.array())).collect(Collectors.joining(",")));
    if (!bbs.isEmpty()) {
      for (ByteBuffer bb: bbs) {
        client.disableTable(bb);
        client.deleteTable(bb);
      }
    }
    TestThriftServer.createTestTables(client);
    TestThriftServer.checkTableList(client);
    TestThriftServer.dropTestTables(client);
  }
}
 
Example #9
Source File: ThriftClient.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) 
        throws IOException, TException {
    THttpClient trans = new THttpClient("http://localhost:8080/thrift-servlet");
    TJSONProtocol proto = new TJSONProtocol(trans);
    TradeHistory.Client client = new TradeHistory.Client(proto);

    for (int i = 0; i < 1000000; i++) {
        trans.open();
        TradeReport tr = client.get_last_sale("AAPL");
        trans.close();
    }
}
 
Example #10
Source File: LineApiImpl.java    From LineAPI4J with MIT License 5 votes vote down vote up
public void loginWithAuthToken(String authToken) throws Exception {
  THttpClient transport = new THttpClient(LINE_HTTP_IN_URL, httpClient);
  transport.setCustomHeader(X_LINE_ACCESS, authToken);
  transport.open();

  TProtocol protocol = new TCompactProtocol(transport);
  setClient(new TalkService.Client(protocol));
  setAuthToken(authToken);
}
 
Example #11
Source File: ThriftClientPooledObjectFactory.java    From spring-thrift-starter with MIT License 5 votes vote down vote up
@Override
public TServiceClient create(ThriftClientKey key) throws Exception {
    String serviceName = key.getServiceName();

    String endpoint = propertyResolver.getProperty(serviceName + ".endpoint");

    int connectTimeout = propertyResolver.getProperty(serviceName + ".connectTimeout", Integer.class, DEFAULT_CONNECTION_TIMEOUT);
    int readTimeout = propertyResolver.getProperty(serviceName + ".readTimeout", Integer.class, DEFAULT_READ_TIMEOUT);
    int maxRetries = propertyResolver.getProperty(serviceName + ".maxRetries", Integer.class, DEFAULT_MAX_RETRIES);

    TProtocol protocol;

    if (StringUtils.isEmpty(endpoint)) {
        final TLoadBalancerClient loadBalancerClient = new TLoadBalancerClient(
                this.loadBalancerClient,
                serviceName,
                propertyResolver.getProperty(serviceName + ".path", "") + key.getPath()
        );
        loadBalancerClient.setConnectTimeout(connectTimeout);
        loadBalancerClient.setReadTimeout(readTimeout);
        loadBalancerClient.setMaxRetries(maxRetries);

        protocol = protocolFactory.getProtocol(loadBalancerClient);
    } else {
        final THttpClient httpClient = new THttpClient(endpoint);
        httpClient.setConnectTimeout(connectTimeout);
        httpClient.setReadTimeout(readTimeout);

        protocol = protocolFactory.getProtocol(httpClient);
    }

    return BeanUtils.instantiateClass(
            key.getClazz().getConstructor(TProtocol.class),
            (TProtocol) protocol
    );
}
 
Example #12
Source File: TGreetingServiceHandlerTests.java    From spring-thrift-starter with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    TTransport transport = new THttpClient("http://localhost:" + port + "/api");

    TProtocol protocol = protocolFactory.getProtocol(transport);

    client = new TGreetingService.Client(protocol);
}
 
Example #13
Source File: TGreetingServiceHandlerTests.java    From spring-thrift-api-gateway with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    TTransport transport = new THttpClient("http://localhost:" + port + "/api");

    TProtocol protocol = protocolFactory.getProtocol(transport);

    client = new TGreetingService.Client(protocol);
}
 
Example #14
Source File: TServiceClientSendBaseInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private String getRemoteAddressForTHttpClient(THttpClient tHttpClient) {
    if (tHttpClient instanceof UrlFieldGetter) {
        URL url = ((UrlFieldGetter) tHttpClient)._$PINPOINT$_getUrl();
        if (url == null) {
            return ThriftConstants.UNKNOWN_ADDRESS;
        }
        return HostAndPort.toHostAndPortString(url.getHost(), url.getPort());
    }
    if (isDebug) {
        logger.debug("Invalid oprot transport object. Need field getter({}).", UrlFieldGetter.class.getName());
    }
    return ThriftConstants.UNKNOWN_ADDRESS;
}
 
Example #15
Source File: CrossflowWebTests.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	transport = new THttpClient("http://localhost:8080/org.eclipse.scava.crossflow.web/thrift");
	transport.open();
	TProtocol protocol = new TJSONProtocol(transport); // JSON transport forma
	client = new Crossflow.Client(protocol);
}
 
Example #16
Source File: RemoteShaderDispatcher.java    From graphicsfuzz with Apache License 2.0 5 votes vote down vote up
private Iface getFuzzerServiceManagerProxy(CloseableHttpClient httpClient)
    throws TTransportException {
  TTransport transport = new THttpClient(url, httpClient);
  transport.open();
  TProtocol protocol = new TBinaryProtocol(transport);
  return new FuzzerServiceManager.Client(
      protocol);
}
 
Example #17
Source File: HttpEchoTestClient.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
private HttpEchoTestClient(TestEnvironment environment, THttpClient httpClient) throws TTransportException {
    this.environment = environment;
    this.httpClient = httpClient;
}
 
Example #18
Source File: HttpEchoTestClient.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
public static HttpEchoTestClient create(TestEnvironment environment) throws TTransportException {
    return new HttpEchoTestClient(environment, new THttpClient(environment.getHttpUrl()));
}
 
Example #19
Source File: HttpSecurityIT.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
private AuroraAdmin.Client getClient(HttpClient httpClient) throws TTransportException {
  final TTransport httpClientTransport = new THttpClient(formatUrl(API_PATH), httpClient);
  addTearDown(httpClientTransport::close);
  return new AuroraAdmin.Client(new TJSONProtocol(httpClientTransport));
}
 
Example #20
Source File: HttpDoAsClient.java    From hbase with Apache License 2.0 4 votes vote down vote up
private void run() throws Exception {
  TTransport transport = new TSocket(host, port);

  transport.open();
  String url = "http://" + host + ":" + port;
  THttpClient httpClient = new THttpClient(url);
  httpClient.open();
  TProtocol protocol = new TBinaryProtocol(httpClient);
  Hbase.Client client = new Hbase.Client(protocol);

  byte[] t = bytes("demo_table");

  //
  // Scan all tables, look for the demo table and delete it.
  //
  System.out.println("scanning tables...");
  for (ByteBuffer name : refresh(client, httpClient).getTableNames()) {
    System.out.println("  found: " + ClientUtils.utf8(name.array()));
    if (ClientUtils.utf8(name.array()).equals(ClientUtils.utf8(t))) {
      if (refresh(client, httpClient).isTableEnabled(name)) {
        System.out.println("    disabling table: " + ClientUtils.utf8(name.array()));
        refresh(client, httpClient).disableTable(name);
      }
      System.out.println("    deleting table: " + ClientUtils.utf8(name.array()));
      refresh(client, httpClient).deleteTable(name);
    }
  }

  //
  // Create the demo table with two column families, entry: and unused:
  //
  ArrayList<ColumnDescriptor> columns = new ArrayList<>(2);
  ColumnDescriptor col;
  col = new ColumnDescriptor();
  col.name = ByteBuffer.wrap(bytes("entry:"));
  col.timeToLive = Integer.MAX_VALUE;
  col.maxVersions = 10;
  columns.add(col);
  col = new ColumnDescriptor();
  col.name = ByteBuffer.wrap(bytes("unused:"));
  col.timeToLive = Integer.MAX_VALUE;
  columns.add(col);

  System.out.println("creating table: " + ClientUtils.utf8(t));
  try {

    refresh(client, httpClient).createTable(ByteBuffer.wrap(t), columns);
  } catch (AlreadyExists ae) {
    System.out.println("WARN: " + ae.message);
  }

  System.out.println("column families in " + ClientUtils.utf8(t) + ": ");
  Map<ByteBuffer, ColumnDescriptor> columnMap = refresh(client, httpClient)
      .getColumnDescriptors(ByteBuffer.wrap(t));
  for (ColumnDescriptor col2 : columnMap.values()) {
    System.out.println("  column: " + ClientUtils.utf8(col2.name.array()) + ", maxVer: "
        + col2.maxVersions);
  }

  transport.close();
  httpClient.close();
}
 
Example #21
Source File: LineApiImpl.java    From LineAPI4J with MIT License 4 votes vote down vote up
public AuthQrcode loginWithQrCode() throws Exception {
  // Request QrCode from LINE server.

  // Map<String, String> json = null;
  boolean keepLoggedIn = false;

  THttpClient transport = new THttpClient(LINE_HTTP_URL, httpClient);
  transport.open();

  TProtocol protocol = new TCompactProtocol(transport);

  this.client = new TalkService.Client(protocol);

  AuthQrcode result = this.client.getAuthQrcode(keepLoggedIn, systemName);

  setAuthToken(result.getVerifier());

  System.out.println("Retrieved QR Code.");

  return result;
  // await for QR code to be certified, it will return a verifier afterward.
  // loginWithVerifier();
}
 
Example #22
Source File: LineApiImpl.java    From LineAPI4J with MIT License 4 votes vote down vote up
@Override
public LoginResult login(@Nonnull String id,
                         @Nonnull String password,
                         @Nullable String certificate,
                         @Nullable LoginCallback loginCallback)
        throws Exception {
  this.id = id;
  this.password = password;
  this.certificate = certificate;
  IdentityProvider provider;
  JsonNode sessionInfo;
  String sessionKey;
  boolean keepLoggedIn = true;
  String accessLocation = this.ip;

  // Login to LINE server.
  if (id.matches(EMAIL_REGEX)) {
    provider = IdentityProvider.LINE; // LINE
    sessionInfo = getJsonResult(LINE_SESSION_LINE_URL);
  } else {
    provider = IdentityProvider.NAVER_KR; // NAVER
    sessionInfo = getJsonResult(LINE_SESSION_NAVER_URL);
  }

  sessionKey = sessionInfo.get("session_key").asText();
  String message =
      (char) (sessionKey.length()) + sessionKey + (char) (id.length()) + id
          + (char) (password.length()) + password;
  String[] keyArr = sessionInfo.get("rsa_key").asText().split(",");
  String keyName = keyArr[0];
  String n = keyArr[1];
  String e = keyArr[2];

  BigInteger modulus = new BigInteger(n, 16);
  BigInteger pubExp = new BigInteger(e, 16);

  KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, pubExp);
  RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
  Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  byte[] enBytes = cipher.doFinal(message.getBytes(StandardCharsets.UTF_8));
  String encryptString = Hex.encodeHexString(enBytes);

  THttpClient transport = new THttpClient(LINE_HTTP_URL, httpClient);
  transport.open();
  LoginResult result;
  TProtocol protocol = new TCompactProtocol(transport);
  this.client = new TalkService.Client(protocol);

  result = this.client.loginWithIdentityCredentialForCertificate(provider, keyName, encryptString,
                  keepLoggedIn, accessLocation, this.systemName, this.certificate);

  if (result.getType() == LoginResultType.REQUIRE_DEVICE_CONFIRM) {

    setAuthToken(result.getVerifier());

    if (loginCallback != null) {
      loginCallback.onDeviceConfirmRequired(result.getPinCode());
    } else {
      throw new Exception("Device confirmation is required. Please set " +
              LoginCallback.class.getSimpleName() + " to get the pin code");
    }

    // await for pinCode to be certified, it will return a verifier afterward.
    loginWithVerifierForCertificate();
  } else if (result.getType() == LoginResultType.SUCCESS) {
    // if param certificate has passed certification
    setAuthToken(result.getAuthToken());
  }

  // Once the client passed the verification, switch connection to HTTP_IN_URL
  loginWithAuthToken(getAuthToken());
  return result;
}
 
Example #23
Source File: HttpThriftClientImpl.java    From ikasoa with MIT License 4 votes vote down vote up
@Override
@SneakyThrows
protected TTransport getTransport(ServerInfo serverInfo) {
	return new THttpClient(serverInfo.getHost());
}
 
Example #24
Source File: TGreetingServiceHandlerTests.java    From spring-thrift-api-gateway with MIT License 3 votes vote down vote up
public void setUp() throws Exception {
    TTransport transport = new THttpClient("http://localhost:" + port + "/greetings/api");

    TProtocol protocol = protocolFactory.getProtocol(transport);

    client = new TGreetingExternalService.Client(protocol);
}
 
Example #25
Source File: CrossflowWorkbench.java    From scava with Eclipse Public License 2.0 3 votes vote down vote up
public static void main(String[] args) throws Exception {
	TTransport transport = new THttpClient("http://localhost:8080/org.eclipse.scava.crossflow.web/crossflow");
	transport.open();
	TProtocol protocol = new TJSONProtocol(transport); // JSON transport format
	
	Crossflow.Client client = new Crossflow.Client(protocol);
	
	client.resetExperiment("calculator");
	
	transport.close();
	
	
	
}