Search in sources :

Example 21 with HttpRequest

use of com.azure.core.http.HttpRequest in project camel-quarkus by apache.

the class VertxHttpClientTests method testServerShutsDownSocketShouldPushErrorToContentFlowable.

@Test
public void testServerShutsDownSocketShouldPushErrorToContentFlowable() {
    Assertions.assertTimeout(Duration.ofMillis(5000), () -> {
        CountDownLatch latch = new CountDownLatch(1);
        try (ServerSocket ss = new ServerSocket(0)) {
            Mono.fromCallable(() -> {
                latch.countDown();
                Socket socket = ss.accept();
                // give the client time to get request across
                Thread.sleep(500);
                // respond but don't send the complete response
                byte[] bytes = new byte[1024];
                int n = socket.getInputStream().read(bytes);
                System.out.println(new String(bytes, 0, n, StandardCharsets.UTF_8));
                String response = // 
                "HTTP/1.1 200 OK\r\n" + // 
                "Content-Type: text/plain\r\n" + // 
                "Content-Length: 10\r\n" + // 
                "\r\n" + "zi";
                OutputStream out = socket.getOutputStream();
                out.write(response.getBytes());
                out.flush();
                // kill the socket with HTTP response body incomplete
                socket.close();
                return 1;
            }).subscribeOn(Schedulers.boundedElastic()).subscribe();
            // 
            latch.await();
            HttpClient client = new VertxHttpClientBuilder(vertx).build();
            HttpRequest request = new HttpRequest(HttpMethod.GET, new URL("http://localhost:" + ss.getLocalPort() + "/ioException"));
            StepVerifier.create(client.send(request)).verifyError(VertxException.class);
        }
    });
}
Also used : HttpRequest(com.azure.core.http.HttpRequest) OutputStream(java.io.OutputStream) HttpClient(com.azure.core.http.HttpClient) ServerSocket(java.net.ServerSocket) CountDownLatch(java.util.concurrent.CountDownLatch) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) URL(java.net.URL) QuarkusUnitTest(io.quarkus.test.QuarkusUnitTest) Test(org.junit.jupiter.api.Test)

Example 22 with HttpRequest

use of com.azure.core.http.HttpRequest in project vividus by vividus-framework.

the class AbstractAzureResourceManagementSteps method saveHttpResponseAsVariable.

protected void saveHttpResponseAsVariable(String urlPath, String apiVersion, Set<VariableScope> scopes, String variableName) {
    // Workaround for https://github.com/Azure/azure-sdk-for-java/issues/27268
    String url = resourceManagerEndpoint + urlPath + "?api-version=" + apiVersion;
    HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, url);
    try (HttpResponse httpResponse = httpPipeline.send(httpRequest).block()) {
        String responseBody = httpResponse.getBodyAsString().block();
        if (httpResponse.getStatusCode() == HttpResponseStatus.OK.code()) {
            variableContext.putVariable(scopes, variableName, responseBody);
        } else {
            softAssert.recordFailedAssertion("Azure REST API HTTP request execution is failed: " + responseBody);
        }
    }
}
Also used : HttpRequest(com.azure.core.http.HttpRequest) HttpResponse(com.azure.core.http.HttpResponse)

Example 23 with HttpRequest

use of com.azure.core.http.HttpRequest in project ApplicationInsights-Java by microsoft.

the class ProfilerFrontendClientV2Test method uploadFinishedHitsCorrectUrl.

@Test
void uploadFinishedHitsCorrectUrl() throws IOException {
    AtomicReference<HttpRequest> requestHolder = new AtomicReference<>();
    HttpPipeline httpPipeline = new HttpPipelineBuilder().httpClient(request -> {
        requestHolder.set(request);
        return Mono.just(mockResponse(request, 201, "{\"acceptedTime\":\"a-time\",\"blobUri\":\"a-blob-uri\",\"correlationId\":\"a-correlation-id\",\"stampId\":\"a-stamp\"}"));
    }).build();
    ProfilerFrontendClientV2 profilerFrontendClientV2 = new ProfilerFrontendClientV2(new URL("http://a-host"), "a-instrumentation-key", httpPipeline);
    UUID id = UUID.randomUUID();
    ArtifactAcceptedResponse artifactAcceptedResponse = profilerFrontendClientV2.reportUploadFinish(id, "an-etag").block();
    HttpRequest request = requestHolder.get();
    String url = request.getUrl().toString();
    assertThat(request.getHttpMethod()).isEqualTo(HttpMethod.POST);
    assertThat(url.contains("/api/apps/a-instrumentation-key/artifactkinds/profile/artifacts/" + id)).isTrue();
    assertThat(url.contains("action=commit")).isTrue();
    assertThat(artifactAcceptedResponse.getAcceptedTime()).isEqualTo("a-time");
    assertThat(artifactAcceptedResponse.getBlobUri()).isEqualTo("a-blob-uri");
    assertThat(artifactAcceptedResponse.getCorrelationId()).isEqualTo("a-correlation-id");
    assertThat(artifactAcceptedResponse.getStampId()).isEqualTo("a-stamp");
}
Also used : HttpRequest(com.azure.core.http.HttpRequest) ArtifactAcceptedResponse(com.microsoft.applicationinsights.serviceprofilerapi.client.contract.ArtifactAcceptedResponse) BlobAccessPass(com.microsoft.applicationinsights.serviceprofilerapi.client.contract.BlobAccessPass) URL(java.net.URL) Date(java.util.Date) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HttpPipeline(com.azure.core.http.HttpPipeline) IOException(java.io.IOException) HashMap(java.util.HashMap) Mono(reactor.core.publisher.Mono) HttpHeaders(com.azure.core.http.HttpHeaders) UUID(java.util.UUID) Instant(java.time.Instant) AtomicReference(java.util.concurrent.atomic.AtomicReference) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) HttpRequest(com.azure.core.http.HttpRequest) HttpMethod(com.azure.core.http.HttpMethod) HttpPipelineBuilder(com.azure.core.http.HttpPipelineBuilder) ProfilerFrontendClientV2(com.microsoft.applicationinsights.serviceprofilerapi.client.ProfilerFrontendClientV2) ArtifactAcceptedResponse(com.microsoft.applicationinsights.serviceprofilerapi.client.contract.ArtifactAcceptedResponse) HttpPipeline(com.azure.core.http.HttpPipeline) HttpPipelineBuilder(com.azure.core.http.HttpPipelineBuilder) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProfilerFrontendClientV2(com.microsoft.applicationinsights.serviceprofilerapi.client.ProfilerFrontendClientV2) UUID(java.util.UUID) URL(java.net.URL) Test(org.junit.jupiter.api.Test)

Example 24 with HttpRequest

use of com.azure.core.http.HttpRequest in project ApplicationInsights-Java by microsoft.

the class ProfilerFrontendClientV2 method getSettings.

/**
 * Obtain current settings that have been configured within the UI.
 */
@Override
public Mono<String> getSettings(Date oldTimeStamp) {
    URL requestUrl = getSettingsPath(oldTimeStamp);
    LOGGER.debug("Settings pull request: {}", requestUrl);
    HttpRequest request = new HttpRequest(HttpMethod.GET, requestUrl);
    return httpPipeline.send(request).flatMap(response -> {
        if (response == null) {
            // this shouldn't happen, the mono should complete with a response or a failure
            return Mono.error(new AssertionError("http response mono returned empty"));
        }
        if (response.getStatusCode() >= 300) {
            consumeResponseBody(response);
            return Mono.error(new HttpResponseException(response));
        }
        return response.getBodyAsString();
    });
}
Also used : HttpRequest(com.azure.core.http.HttpRequest) HttpResponseException(com.azure.core.exception.HttpResponseException) URL(java.net.URL)

Example 25 with HttpRequest

use of com.azure.core.http.HttpRequest in project ApplicationInsights-Java by microsoft.

the class QuickPulseIntegrationTests method testPostRequest.

@Test
public void testPostRequest() throws InterruptedException {
    ArrayBlockingQueue<HttpRequest> sendQueue = new ArrayBlockingQueue<>(256, true);
    CountDownLatch pingCountDown = new CountDownLatch(1);
    CountDownLatch postCountDown = new CountDownLatch(1);
    Date currDate = new Date();
    String expectedPingRequestBody = "\\{\"Documents\":null,\"InstrumentationKey\":null,\"Metrics\":null,\"InvariantVersion\":1,\"Timestamp\":\"\\\\/Date\\(\\d+\\)\\\\/\",\"Version\":\"\\(unknown\\)\",\"StreamId\":\"qpid123\",\"MachineName\":\"machine1\",\"Instance\":\"instance1\",\"RoleName\":null\\}";
    String expectedPostRequestBody = "\\[\\{\"Documents\":\\[\\{\"__type\":\"RequestTelemetryDocument\",\"DocumentType\":\"Request\",\"Version\":\"1.0\",\"OperationId\":null,\"Properties\":\\{\"customProperty\":\"customValue\"\\},\"Name\":\"request-test\",\"Success\":true,\"Duration\":\"PT.*S\",\"ResponseCode\":\"200\",\"OperationName\":null,\"Url\":\"foo\"\\},\\{\"__type\":\"DependencyTelemetryDocument\",\"DocumentType\":\"RemoteDependency\",\"Version\":\"1.0\",\"OperationId\":null,\"Properties\":\\{\"customProperty\":\"customValue\"\\},\"Name\":\"dep-test\",\"Target\":null,\"Success\":true,\"Duration\":\"PT.*S\",\"ResultCode\":null,\"CommandName\":\"dep-test-cmd\",\"DependencyTypeName\":null,\"OperationName\":null\\},\\{\"__type\":\"ExceptionTelemetryDocument\",\"DocumentType\":\"Exception\",\"Version\":\"1.0\",\"OperationId\":null,\"Properties\":null,\"Exception\":\"\",\"ExceptionMessage\":\"test\",\"ExceptionType\":\"java.lang.Exception\"\\}\\],\"InstrumentationKey\":\"" + instrumentationKey + "\",\"Metrics\":\\[\\{\"Name\":\"\\\\\\\\ApplicationInsights\\\\\\\\Requests\\\\\\/Sec\",\"Value\":\\d+,\"Weight\":\\d+\\},\\{\"Name\":\"\\\\\\\\ApplicationInsights\\\\\\\\Request Duration\",\"Value\":\\d+,\"Weight\":\\d+\\},\\{\"Name\":\"\\\\\\\\ApplicationInsights\\\\\\\\Requests Failed\\\\\\/Sec\",\"Value\":\\d+,\"Weight\":\\d+\\},\\{\"Name\":\"\\\\\\\\ApplicationInsights\\\\\\\\Requests Succeeded\\\\\\/Sec\",\"Value\":\\d+,\"Weight\":\\d+\\},\\{\"Name\":\"\\\\\\\\ApplicationInsights\\\\\\\\Dependency Calls\\\\\\/Sec\",\"Value\":\\d+,\"Weight\":\\d+\\},\\{\"Name\":\"\\\\\\\\ApplicationInsights\\\\\\\\Dependency Call Duration\",\"Value\":\\d+,\"Weight\":\\d+\\},\\{\"Name\":\"\\\\\\\\ApplicationInsights\\\\\\\\Dependency Calls Failed\\\\\\/Sec\",\"Value\":\\d+,\"Weight\":\\d+\\},\\{\"Name\":\"\\\\\\\\ApplicationInsights\\\\\\\\Dependency Calls Succeeded\\\\\\/Sec\",\"Value\":\\d+,\"Weight\":\\d+\\},\\{\"Name\":\"\\\\\\\\ApplicationInsights\\\\\\\\Exceptions\\\\\\/Sec\",\"Value\":\\d+,\"Weight\":\\d+\\},\\{\"Name\":\"\\\\\\\\Memory\\\\\\\\Committed Bytes\",\"Value\":\\d+,\"Weight\":\\d+\\},\\{\"Name\":\"\\\\\\\\Processor\\(_Total\\)\\\\\\\\% Processor Time\",\"Value\":-?\\d+,\"Weight\":\\d+\\}\\],\"InvariantVersion\":1,\"Timestamp\":\"\\\\\\/Date\\(\\d+\\)\\\\\\/\",\"Version\":\"[^\"]*\",\"StreamId\":null,\"MachineName\":\"machine1\",\"Instance\":\"instance1\",\"RoleName\":null\\}\\]";
    QuickPulsePingSender pingSender = getQuickPulsePingSenderWithValidator(new ValidationPolicy(pingCountDown, expectedPingRequestBody));
    QuickPulseHeaderInfo quickPulseHeaderInfo = pingSender.ping(null);
    QuickPulseDataSender dataSender = new QuickPulseDataSender(getHttpPipeline(new ValidationPolicy(postCountDown, expectedPostRequestBody)), sendQueue);
    TelemetryClient telemetryClient = TelemetryClient.createForTest();
    telemetryClient.setConnectionString(connectionString);
    QuickPulseDataFetcher dataFetcher = new QuickPulseDataFetcher(sendQueue, telemetryClient, "machine1", "instance1", null);
    QuickPulseDataCollector.INSTANCE.setQuickPulseStatus(QuickPulseStatus.QP_IS_ON);
    QuickPulseDataCollector.INSTANCE.enable(telemetryClient);
    final long duration = 112233L;
    // Request Telemetry
    TelemetryItem requestTelemetry = createRequestTelemetry("request-test", currDate, duration, "200", true);
    requestTelemetry.setInstrumentationKey(instrumentationKey);
    QuickPulseDataCollector.INSTANCE.add(requestTelemetry);
    // Dependency Telemetry
    TelemetryItem dependencyTelemetry = createRemoteDependencyTelemetry("dep-test", "dep-test-cmd", duration, true);
    dependencyTelemetry.setInstrumentationKey(instrumentationKey);
    QuickPulseDataCollector.INSTANCE.add(dependencyTelemetry);
    // Exception Telemetry
    TelemetryItem exceptionTelemetry = createExceptionTelemetry(new Exception("test"));
    exceptionTelemetry.setInstrumentationKey(instrumentationKey);
    QuickPulseDataCollector.INSTANCE.add(exceptionTelemetry);
    QuickPulseCoordinatorInitData initData = new QuickPulseCoordinatorInitDataBuilder().withDataFetcher(dataFetcher).withDataSender(dataSender).withPingSender(pingSender).withWaitBetweenPingsInMillis(10L).withWaitBetweenPostsInMillis(10L).withWaitOnErrorInMillis(10L).build();
    QuickPulseCoordinator coordinator = new QuickPulseCoordinator(initData);
    Thread coordinatorThread = new Thread(coordinator, QuickPulseCoordinator.class.getSimpleName());
    coordinatorThread.setDaemon(true);
    coordinatorThread.start();
    Thread senderThread = new Thread(dataSender, QuickPulseDataSender.class.getSimpleName());
    senderThread.setDaemon(true);
    senderThread.start();
    Thread.sleep(50);
    assertTrue(pingCountDown.await(1, TimeUnit.SECONDS));
    assertThat(quickPulseHeaderInfo.getQuickPulseStatus()).isEqualTo(QuickPulseStatus.QP_IS_ON);
    assertThat(QuickPulseDataCollector.INSTANCE.getQuickPulseStatus()).isEqualTo(QuickPulseStatus.QP_IS_ON);
    assertTrue(postCountDown.await(1, TimeUnit.SECONDS));
    senderThread.interrupt();
    coordinatorThread.interrupt();
}
Also used : HttpRequest(com.azure.core.http.HttpRequest) TelemetryItem(com.microsoft.applicationinsights.agent.internal.exporter.models.TelemetryItem) CountDownLatch(java.util.concurrent.CountDownLatch) TelemetryClient(com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient) Date(java.util.Date) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Test(org.junit.jupiter.api.Test)

Aggregations

HttpRequest (com.azure.core.http.HttpRequest)31 Test (org.junit.jupiter.api.Test)13 HttpMethod (com.azure.core.http.HttpMethod)9 HttpResponse (com.azure.core.http.HttpResponse)9 HttpClient (com.azure.core.http.HttpClient)8 URI (java.net.URI)8 URL (java.net.URL)8 HttpHeaders (com.azure.core.http.HttpHeaders)7 IOException (java.io.IOException)7 Mono (reactor.core.publisher.Mono)7 Date (java.util.Date)6 QuarkusUnitTest (io.quarkus.test.QuarkusUnitTest)5 StandardCharsets (java.nio.charset.StandardCharsets)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 HttpPipeline (com.azure.core.http.HttpPipeline)3 WireMockServer (com.github.tomakehurst.wiremock.WireMockServer)3 WireMock (com.github.tomakehurst.wiremock.client.WireMock)3 WireMockConfiguration (com.github.tomakehurst.wiremock.core.WireMockConfiguration)3 Duration (java.time.Duration)3 HashMap (java.util.HashMap)3