Java Code Examples for io.reactivex.netty.client.RxClient#ServerInfo

The following examples show how to use io.reactivex.netty.client.RxClient#ServerInfo . 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: RxGatewayStoreModel.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
/**
 * Given the request it creates an observable which upon subscription issues HTTP call and emits one RxDocumentServiceResponse.
 *
 * @param request
 * @param method
 * @return Observable<RxDocumentServiceResponse>
 */
public Observable<RxDocumentServiceResponse> performRequest(RxDocumentServiceRequest request, HttpMethod method) {

    try {
        URI uri = getUri(request);
        HttpClientRequest<ByteBuf> httpRequest = HttpClientRequest.create(method, uri.toString());

        this.fillHttpRequestBaseWithHeaders(request.getHeaders(), httpRequest);

        if (request.getContentObservable() != null) {

            // TODO validate this
            // convert byte[] to ByteBuf
            // why not use Observable<byte[]> directly?
            Observable<ByteBuf> byteBufObservable = request.getContentObservable()
                    .map(bytes ->  Unpooled.wrappedBuffer(bytes));

            httpRequest.withContentSource(byteBufObservable);
        } else if (request.getContent() != null){
            httpRequest.withContent(request.getContent());
        }

        RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(uri.getHost(), uri.getPort());

        Observable<HttpClientResponse<ByteBuf>> clientResponseObservable = this.httpClient.submit(serverInfo, httpRequest);

        return toDocumentServiceResponse(clientResponseObservable, request).observeOn(Schedulers.computation());

    } catch (Exception e) {
        return Observable.error(e);
    }
}
 
Example 2
Source File: GatewayServiceConfigurationReader.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
private Single<DatabaseAccount> getDatabaseAccountAsync(URI serviceEndpoint) {
    HttpClientRequest<ByteBuf> httpRequest = HttpClientRequest.create(HttpMethod.GET,
            this.serviceEndpoint.toString());

    httpRequest.withHeader(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION);

    UserAgentContainer userAgentContainer = new UserAgentContainer();
    String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix();
    if (userAgentSuffix != null && userAgentSuffix.length() > 0) {
        userAgentContainer.setSuffix(userAgentSuffix);
    }

    httpRequest.withHeader(HttpConstants.HttpHeaders.USER_AGENT, userAgentContainer.getUserAgent());
    httpRequest.withHeader(HttpConstants.HttpHeaders.API_TYPE, Constants.Properties.SQL_API_TYPE);
    String authorizationToken = StringUtils.EMPTY;
    if (this.hasAuthKeyResourceToken || baseAuthorizationTokenProvider == null) {
        authorizationToken = HttpUtils.urlEncode(this.authKeyResourceToken);
    } else {
        // Retrieve the document service properties.
        String xDate = Utils.nowAsRFC1123();
        httpRequest.withHeader(HttpConstants.HttpHeaders.X_DATE, xDate);
        Map<String, String> header = new HashMap<>();
        header.put(HttpConstants.HttpHeaders.X_DATE, xDate);
        authorizationToken = baseAuthorizationTokenProvider
                .generateKeyAuthorizationSignature(HttpConstants.HttpMethods.GET, serviceEndpoint, header);
    }

    httpRequest.withHeader(HttpConstants.HttpHeaders.AUTHORIZATION, authorizationToken);
    RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(serviceEndpoint.getHost(), serviceEndpoint.getPort());

    Observable<HttpClientResponse<ByteBuf>> clientResponseObservable = this.httpClient.submit(serverInfo,
            httpRequest);
    return toDatabaseAccountObservable(clientResponseObservable.toSingle());
}
 
Example 3
Source File: HttpTransportClientTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@Test(groups = "unit")
public void validateDefaultHeaders() {
    HttpClientResponse<ByteBuf> mockedResponse = new HttpClientMockWrapper.HttpClientBehaviourBuilder()
            .withContent("").withStatus(200)
            .withHeaders(EmptyHttpHeaders.INSTANCE)
            .asHttpClientResponse();
    HttpClientMockWrapper httpClientMockWrapper = new HttpClientMockWrapper(mockedResponse);

    UserAgentContainer userAgentContainer = new UserAgentContainer();
    userAgentContainer.setSuffix("i am suffix");

    HttpTransportClient transportClient = getHttpTransportClientUnderTest(100,
            userAgentContainer,
            httpClientMockWrapper.getClient());

    RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName(
            OperationType.Create, "dbs/db/colls/col", ResourceType.Document);
    request.setContentBytes(new byte[0]);

    transportClient.invokeStoreAsync(Uri.create(physicalAddress),
            new ResourceOperation(OperationType.Create, ResourceType.Document),
            request).toBlocking().value();

    assertThat(httpClientMockWrapper.getCapturedInvocation()).asList().hasSize(1);
    ImmutablePair<HttpClientRequest<ByteBuf>, RxClient.ServerInfo> httpClientInvocation = httpClientMockWrapper.getCapturedInvocation().get(0);

    assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.USER_AGENT)).endsWith("i am suffix");
    assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.CACHE_CONTROL)).isEqualTo("no-cache");
    assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.ACCEPT)).isEqualTo("application/json");
    assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.VERSION)).isEqualTo(HttpConstants.Versions.CURRENT_VERSION);

}
 
Example 4
Source File: GatewayAddressCache.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
Single<List<Address>> getServerAddressesViaGatewayAsync(
        RxDocumentServiceRequest request,
        String collectionRid,
        List<String> partitionKeyRangeIds,
        boolean forceRefresh) {
    if (logger.isDebugEnabled()) {
        logger.debug("getServerAddressesViaGatewayAsync collectionRid {}, partitionKeyRangeIds {}", collectionRid,
                     JavaStreamUtils.toString(partitionKeyRangeIds, ","));
    }
    String entryUrl = PathsHelper.generatePath(ResourceType.Document, collectionRid, true);
    HashMap<String, String> addressQuery = new HashMap<>();

    addressQuery.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl));

    HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders);
    if (forceRefresh) {
        headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, Boolean.TRUE.toString());
    }

    if (request.forceCollectionRoutingMapRefresh) {
        headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, Boolean.TRUE.toString());
    }

    addressQuery.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter));

    addressQuery.put(HttpConstants.QueryStrings.PARTITION_KEY_RANGE_IDS, String.join(",", partitionKeyRangeIds));
    headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
    String token = null;

    token = this.tokenProvider.getUserAuthorizationToken(
            collectionRid,
            ResourceType.Document,
            HttpConstants.HttpMethods.GET,
            headers,
            AuthorizationTokenType.PrimaryMasterKey,
            request.properties);

    if (token == null && request.getIsNameBased()) {
        // User doesn't have rid based resource token. Maybe user has name based.
        String collectionAltLink = PathsHelper.getCollectionPath(request.getResourceAddress());
        token = this.tokenProvider.getUserAuthorizationToken(
                collectionAltLink,
                ResourceType.Document,
                HttpConstants.HttpMethods.GET,
                headers,
                AuthorizationTokenType.PrimaryMasterKey,
                request.properties);
    }

    token = HttpUtils.urlEncode(token);
    headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, token);
    URL targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(addressQuery));
    String identifier = logAddressResolutionStart(request, targetEndpoint);
    HttpClientRequest<ByteBuf> httpGet = HttpClientRequest.createGet(targetEndpoint.toString());

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpGet.withHeader(entry.getKey(), entry.getValue());
    }

    RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(targetEndpoint.getHost(), targetEndpoint.getPort());
    Observable<HttpClientResponse<ByteBuf>> responseObs = this.httpClient.submit(serverInfo, httpGet);

    Single<RxDocumentServiceResponse> dsrObs = responseObs.toSingle().flatMap(rsp ->
            HttpClientUtils.parseResponseAsync(rsp));
    return dsrObs.map(
            dsr -> {
                if (logger.isDebugEnabled()) {
                    logger.debug("getServerAddressesViaGatewayAsync deserializes result");
                }
                logAddressResolutionEnd(request, identifier);
                List<Address> addresses = dsr.getQueryResponse(Address.class);
                return addresses;
            });
}
 
Example 5
Source File: GatewayAddressCache.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
Single<List<Address>> getMasterAddressesViaGatewayAsync(
        RxDocumentServiceRequest request,
        ResourceType resourceType,
        String resourceAddress,
        String entryUrl,
        boolean forceRefresh,
        boolean useMasterCollectionResolver,
        Map<String, Object> properties) {

    logger.debug("getMasterAddressesViaGatewayAsync " +
                         "resourceType {}, " +
                         "resourceAddress {}, " +
                         "entryUrl {}, " +
                         "forceRefresh {}, " +
                         "useMasterCollectionResolver {}",
                 resourceType,
                 resourceAddress,
                 entryUrl,
                 forceRefresh,
                 useMasterCollectionResolver
    );

    HashMap<String, String> queryParameters = new HashMap<>();
    queryParameters.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl));
    HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders);

    if (forceRefresh) {
        headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, Boolean.TRUE.toString());
    }

    if (useMasterCollectionResolver) {
        headers.put(HttpConstants.HttpHeaders.USE_MASTER_COLLECTION_RESOLVER, Boolean.TRUE.toString());
    }

    if (request.forceCollectionRoutingMapRefresh) {
        headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, Boolean.TRUE.toString());
    }

    queryParameters.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter));
    headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123());
    String token = this.tokenProvider.getUserAuthorizationToken(
            resourceAddress,
            resourceType,
            HttpConstants.HttpMethods.GET,
            headers,
            AuthorizationTokenType.PrimaryMasterKey,
            properties);

    headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, HttpUtils.urlEncode(token));
    URL targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(queryParameters));
    String identifier = logAddressResolutionStart(request, targetEndpoint);
    HttpClientRequest<ByteBuf> httpGet = HttpClientRequest.createGet(targetEndpoint.toString());

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpGet.withHeader(entry.getKey(), entry.getValue());
    }

    RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(targetEndpoint.getHost(), targetEndpoint.getPort());
    Observable<HttpClientResponse<ByteBuf>> responseObs = this.httpClient.submit(serverInfo, httpGet);

    Single<RxDocumentServiceResponse> dsrObs = responseObs.toSingle().flatMap(rsp ->
            HttpClientUtils.parseResponseAsync(rsp));
    return dsrObs.map(
            dsr -> {
                logAddressResolutionEnd(request, identifier);
                List<Address> addresses = dsr.getQueryResponse(Address.class);
                return addresses;
            });
}
 
Example 6
Source File: HttpClientMockWrapper.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
public List<ImmutablePair<HttpClientRequest<ByteBuf>, RxClient.ServerInfo>> getCapturedInvocation() {
    return requests;
}