Search in sources :

Example 1 with HttpResponse

use of java.net.http.HttpResponse in project neo4j by neo4j.

the class HttpStructuredLoggingIT method shouldLogRequestsInStructuredFormat.

@Test
public void shouldLogRequestsInStructuredFormat() throws Exception {
    var bootstrapper = new CommunityBootstrapper();
    HttpResponse<String> response;
    Path httpLogPath;
    try {
        bootstrapper.start(folder.homePath(), Map.of(HttpConnector.listen_address.name(), "localhost:0", ServerSettings.http_log_format.name(), FormattedLogFormat.JSON.name(), ServerSettings.http_logging_enabled.name(), TRUE, HttpConnector.enabled.name(), TRUE));
        var dependencyResolver = getDependencyResolver(bootstrapper.getDatabaseManagementService());
        var baseUri = dependencyResolver.resolveDependency(AbstractNeoWebServer.class).getBaseUri();
        var config = dependencyResolver.resolveDependency(Config.class);
        var request = HttpRequest.newBuilder().uri(baseUri).timeout(Duration.ofSeconds(10)).header("Accept", "application/json").header("User-Agent", HttpStructuredLoggingIT.class.getSimpleName()).GET().build();
        // Just ask the discovery api for a response we don't actually care of
        httpLogPath = config.get(ServerSettings.http_log_path);
        response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
    } finally {
        bootstrapper.stop();
        // Make sure the log manager flushes everything.
        LogManager.shutdown();
    }
    assertThat(response.statusCode()).isEqualTo(200);
    var httpLogLines = Files.readAllLines(httpLogPath).stream().map(s -> {
        try {
            return OBJECT_MAPPER.readValue(s, MAP_TYPE);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }).collect(Collectors.toList());
    assertThat(httpLogLines).anyMatch(logEntry -> logEntry.getOrDefault("message", "").contains(HttpStructuredLoggingIT.class.getSimpleName()));
}
Also used : Path(java.nio.file.Path) ExclusiveWebContainerTestBase(org.neo4j.test.server.ExclusiveWebContainerTestBase) ServerSettings(org.neo4j.server.configuration.ServerSettings) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Config(org.neo4j.configuration.Config) HttpRequest(java.net.http.HttpRequest) DEFAULT_DATABASE_NAME(org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME) HttpConnector(org.neo4j.configuration.connectors.HttpConnector) Duration(java.time.Duration) Map(java.util.Map) HttpClient(java.net.http.HttpClient) AbstractNeoWebServer(org.neo4j.server.AbstractNeoWebServer) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Path(java.nio.file.Path) DependencyResolver(org.neo4j.common.DependencyResolver) HttpResponse(java.net.http.HttpResponse) Files(java.nio.file.Files) FormattedLogFormat(org.neo4j.logging.FormattedLogFormat) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Test(org.junit.Test) Collectors(java.util.stream.Collectors) GraphDatabaseAPI(org.neo4j.kernel.internal.GraphDatabaseAPI) CommunityBootstrapper(org.neo4j.server.CommunityBootstrapper) TRUE(org.neo4j.configuration.SettingValueParsers.TRUE) DatabaseManagementService(org.neo4j.dbms.api.DatabaseManagementService) LogManager(org.apache.logging.log4j.LogManager) AbstractNeoWebServer(org.neo4j.server.AbstractNeoWebServer) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) CommunityBootstrapper(org.neo4j.server.CommunityBootstrapper) Test(org.junit.Test)

Example 2 with HttpResponse

use of java.net.http.HttpResponse in project pravega by pravega.

the class ControllerPrometheusTest method testPrometheusMetrics.

@Test
public void testPrometheusMetrics() throws Exception {
    MetricsProvider.initialize(MetricsConfig.builder().with(MetricsConfig.ENABLE_STATISTICS, true).with(MetricsConfig.ENABLE_PROMETHEUS, true).with(MetricsConfig.METRICS_PREFIX, "promtestcontroller").build());
    @Cleanup StatsProvider statsProvider = MetricsProvider.getMetricsProvider();
    statsProvider.start();
    @Cleanup ControllerServiceStarter starter = new ControllerServiceStarter(createControllerServiceConfig(), storeClient, null);
    starter.startAsync();
    starter.awaitRunning();
    Counter c = statsProvider.createStatsLogger("promtest").createCounter("promtestcounter");
    c.add(1);
    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
    HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:" + this.restPort + "/prometheus")).build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    assertTrue(response.body().lines().anyMatch(x -> Pattern.matches("promtestcounter.*1\\.0", x)));
    starter.stopAsync();
    starter.awaitTerminated();
}
Also used : HttpRequest(java.net.http.HttpRequest) StoreClientConfig(io.pravega.controller.store.client.StoreClientConfig) RunWith(org.junit.runner.RunWith) Cleanup(lombok.Cleanup) GRPCServerConfigImpl(io.pravega.controller.server.rpc.grpc.impl.GRPCServerConfigImpl) StoreClient(io.pravega.controller.store.client.StoreClient) TimeoutServiceConfig(io.pravega.controller.timeout.TimeoutServiceConfig) HttpRequest(java.net.http.HttpRequest) RESTServerConfigImpl(io.pravega.shared.rest.impl.RESTServerConfigImpl) ControllerServiceConfigImpl(io.pravega.controller.server.impl.ControllerServiceConfigImpl) StoreClientConfigImpl(io.pravega.controller.store.client.impl.StoreClientConfigImpl) HostMonitorConfig(io.pravega.controller.store.host.HostMonitorConfig) Duration(java.time.Duration) Timeout(org.junit.rules.Timeout) HttpClient(java.net.http.HttpClient) URI(java.net.URI) HostMonitorConfigImpl(io.pravega.controller.store.host.impl.HostMonitorConfigImpl) HttpResponse(java.net.http.HttpResponse) StoreClientFactory(io.pravega.controller.store.client.StoreClientFactory) SerializedClassRunner(io.pravega.test.common.SerializedClassRunner) Assert.assertTrue(org.junit.Assert.assertTrue) StatsProvider(io.pravega.shared.metrics.StatsProvider) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) MetricsProvider(io.pravega.shared.metrics.MetricsProvider) Slf4j(lombok.extern.slf4j.Slf4j) Rule(org.junit.Rule) Config(io.pravega.controller.util.Config) Counter(io.pravega.shared.metrics.Counter) MetricsConfig(io.pravega.shared.metrics.MetricsConfig) Optional(java.util.Optional) TestUtils(io.pravega.test.common.TestUtils) Pattern(java.util.regex.Pattern) Counter(io.pravega.shared.metrics.Counter) StatsProvider(io.pravega.shared.metrics.StatsProvider) HttpClient(java.net.http.HttpClient) Cleanup(lombok.Cleanup) Test(org.junit.Test)

Example 3 with HttpResponse

use of java.net.http.HttpResponse in project pravega by pravega.

the class PrometheusTest method testPrometheusMetrics.

@Test
public void testPrometheusMetrics() throws Exception {
    @Cleanup StatsProvider statsProvider = MetricsProvider.getMetricsProvider();
    statsProvider.start();
    Counter c = statsProvider.createStatsLogger("promtest").createCounter("promtestcounter");
    c.add(1);
    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
    HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:" + this.restPort + "/prometheus")).build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    assertTrue(response.body().lines().anyMatch(x -> Pattern.matches("promtestcounter.*1\\.0", x)));
}
Also used : HttpRequest(java.net.http.HttpRequest) SerializedClassRunner(io.pravega.test.common.SerializedClassRunner) RunWith(org.junit.runner.RunWith) ServiceConfig(io.pravega.segmentstore.server.store.ServiceConfig) Cleanup(lombok.Cleanup) Assert.assertTrue(org.junit.Assert.assertTrue) StatsProvider(io.pravega.shared.metrics.StatsProvider) Test(org.junit.Test) ServiceBuilderConfig(io.pravega.segmentstore.server.store.ServiceBuilderConfig) HttpRequest(java.net.http.HttpRequest) MetricsProvider(io.pravega.shared.metrics.MetricsProvider) Counter(io.pravega.shared.metrics.Counter) TestingServerStarter(io.pravega.test.common.TestingServerStarter) After(org.junit.After) Duration(java.time.Duration) TestingServer(org.apache.curator.test.TestingServer) MetricsConfig(io.pravega.shared.metrics.MetricsConfig) HttpClient(java.net.http.HttpClient) TestUtils(io.pravega.test.common.TestUtils) URI(java.net.URI) Pattern(java.util.regex.Pattern) Before(org.junit.Before) HttpResponse(java.net.http.HttpResponse) Counter(io.pravega.shared.metrics.Counter) StatsProvider(io.pravega.shared.metrics.StatsProvider) HttpClient(java.net.http.HttpClient) Cleanup(lombok.Cleanup) Test(org.junit.Test)

Example 4 with HttpResponse

use of java.net.http.HttpResponse in project pravega by pravega.

the class PrometheusResourceTest method testScrape.

@Test
public void testScrape() throws Exception {
    MetricsConfig appConfig = MetricsConfig.builder().with(MetricsConfig.ENABLE_STATISTICS, true).with(MetricsConfig.ENABLE_PROMETHEUS, true).build();
    @Cleanup CompositeMeterRegistry localRegistry = new CompositeMeterRegistry();
    @Cleanup StatsProvider statsProvider = new StatsProviderImpl(appConfig, localRegistry);
    statsProvider.start();
    for (MeterRegistry registry : localRegistry.getRegistries()) {
        assertTrue(registry instanceof PrometheusMeterRegistry);
    }
    assertTrue(statsProvider.prometheusResource().isPresent());
    ResourceConfig rc = ResourceConfig.forApplication(new PrometheusApplication(statsProvider));
    URI baseUri = UriBuilder.fromUri("http://localhost/").port(TestUtils.getAvailableListenPort()).build();
    @Cleanup("shutdown") HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, rc);
    Counter c = statsProvider.createStatsLogger("promtest").createCounter("promtestcounter");
    c.add(1);
    HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
    HttpRequest request = HttpRequest.newBuilder().uri(URI.create(baseUri + "prometheus")).build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    assertTrue(response.body().lines().anyMatch(x -> Pattern.matches("promtestcounter.*1\\.0", x)));
    server.shutdown();
}
Also used : CompositeMeterRegistry(io.micrometer.core.instrument.composite.CompositeMeterRegistry) PrometheusMeterRegistry(io.micrometer.prometheus.PrometheusMeterRegistry) HttpRequest(java.net.http.HttpRequest) ImmutableSet(com.google.common.collect.ImmutableSet) CompositeMeterRegistry(io.micrometer.core.instrument.composite.CompositeMeterRegistry) SerializedClassRunner(io.pravega.test.common.SerializedClassRunner) RunWith(org.junit.runner.RunWith) Cleanup(lombok.Cleanup) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Application(javax.ws.rs.core.Application) HttpRequest(java.net.http.HttpRequest) Slf4j(lombok.extern.slf4j.Slf4j) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) Assert.assertFalse(org.junit.Assert.assertFalse) PrometheusMeterRegistry(io.micrometer.prometheus.PrometheusMeterRegistry) Duration(java.time.Duration) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) GrizzlyHttpServerFactory(org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory) HttpServer(org.glassfish.grizzly.http.server.HttpServer) UriBuilder(javax.ws.rs.core.UriBuilder) HttpClient(java.net.http.HttpClient) TestUtils(io.pravega.test.common.TestUtils) URI(java.net.URI) Pattern(java.util.regex.Pattern) HttpResponse(java.net.http.HttpResponse) Cleanup(lombok.Cleanup) URI(java.net.URI) CompositeMeterRegistry(io.micrometer.core.instrument.composite.CompositeMeterRegistry) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) PrometheusMeterRegistry(io.micrometer.prometheus.PrometheusMeterRegistry) HttpClient(java.net.http.HttpClient) HttpServer(org.glassfish.grizzly.http.server.HttpServer) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) Test(org.junit.Test)

Example 5 with HttpResponse

use of java.net.http.HttpResponse in project alf.io by alfio-event.

the class MollieWebhookPaymentManager method initPayment.

private PaymentResult initPayment(TicketReservation reservation, PaymentSpecification spec, String baseUrl, Map<ConfigurationKeys, ConfigurationManager.MaybeConfiguration> configuration) throws IOException, InterruptedException {
    var purchaseContext = spec.getPurchaseContext();
    var purchaseContextUrlComponent = purchaseContext.getType().getUrlComponent();
    var publicIdentifier = purchaseContext.getPublicIdentifier();
    var reservationId = reservation.getId();
    String bookUrl = baseUrl + "/" + purchaseContextUrlComponent + "/" + publicIdentifier + "/reservation/" + reservationId + "/book";
    final int items;
    if (spec.getPurchaseContext().getType() == PurchaseContext.PurchaseContextType.event) {
        items = ticketRepository.countTicketsInReservation(spec.getReservationId());
    } else {
        items = 1;
    }
    Map<String, Object> payload = new HashMap<>();
    payload.put(AMOUNT, Map.of(VALUE, spec.getOrderSummary().getTotalPrice(), CURRENCY, spec.getPurchaseContext().getCurrency()));
    var description = purchaseContext.ofType(PurchaseContext.PurchaseContextType.event) ? "ticket(s) for event" : "x subscription";
    payload.put("description", String.format("%s - %d %s %s", configurationManager.getShortReservationID(spec.getPurchaseContext(), reservation), items, description, spec.getPurchaseContext().getDisplayName()));
    payload.put("redirectUrl", bookUrl);
    payload.put("webhookUrl", baseUrl + UriComponentsBuilder.fromPath(WEBHOOK_URL_TEMPLATE).buildAndExpand(reservationId).toUriString());
    payload.put("metadata", MetadataBuilder.buildMetadata(spec, Map.of()));
    if (configuration.get(PLATFORM_MODE_ENABLED).getValueAsBooleanOrDefault()) {
        payload.put("profileId", configuration.get(MOLLIE_CONNECT_PROFILE_ID).getRequiredValue());
        payload.put("testmode", !configuration.get(MOLLIE_CONNECT_LIVE_MODE).getValueAsBooleanOrDefault());
        String currencyCode = spec.getCurrencyCode();
        FeeCalculator.getCalculator(spec.getPurchaseContext(), configurationManager, currencyCode).apply(items, (long) spec.getPriceWithVAT()).filter(// minimum fee for Mollie is 0.01
        fee -> fee > 1L).map(fee -> MonetaryUtil.formatCents(fee, currencyCode)).ifPresent(fee -> payload.put("applicationFee", Map.of(AMOUNT, Map.of(CURRENCY, currencyCode, VALUE, fee), "description", "Reservation" + reservationId)));
    }
    HttpRequest request = requestFor(PAYMENTS_ENDPOINT, configuration, spec.getPurchaseContext().getConfigurationLevel()).header(HttpUtils.CONTENT_TYPE, HttpUtils.APPLICATION_JSON).POST(HttpRequest.BodyPublishers.ofString(Json.GSON.toJson(payload))).build();
    HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
    if (HttpUtils.callSuccessful(response)) {
        try (var responseReader = new InputStreamReader(response.body(), UTF_8)) {
            var body = new MolliePaymentDetails(JsonParser.parseReader(responseReader).getAsJsonObject());
            var paymentId = body.getPaymentId();
            var checkoutLink = body.getCheckoutLink();
            // we give an additional slack to process the payment
            var expiration = body.getExpiresAt().orElseThrow().plusMinutes(5);
            ticketReservationRepository.updateReservationStatus(reservationId, EXTERNAL_PROCESSING_PAYMENT.toString());
            ticketReservationRepository.updateValidity(reservationId, Date.from(expiration.toInstant()));
            invalidateExistingTransactions(reservationId, transactionRepository);
            transactionRepository.insert(paymentId, paymentId, reservationId, ZonedDateTime.now(clockProvider.withZone(spec.getPurchaseContext().getZoneId())), spec.getPriceWithVAT(), spec.getPurchaseContext().getCurrency(), "Mollie Payment", PaymentProxy.MOLLIE.name(), 0L, 0L, Transaction.Status.PENDING, Map.of());
            return PaymentResult.redirect(checkoutLink);
        }
    } else {
        log.warn("was not able to create a payment for reservation id " + reservationId);
        return PaymentResult.failed(ErrorsCode.STEP_2_PAYMENT_REQUEST_CREATION);
    }
}
Also used : JsonObject(com.google.gson.JsonObject) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ZonedDateTime(java.time.ZonedDateTime) PaymentResult(alfio.manager.support.PaymentResult) PurchaseContext(alfio.model.PurchaseContext) StringUtils(org.apache.commons.lang3.StringUtils) PaymentInformation(alfio.model.PaymentInformation) MonetaryUtil.formatCents(alfio.util.MonetaryUtil.formatCents) PurchaseContextManager(alfio.manager.PurchaseContextManager) Duration(java.time.Duration) URI(java.net.URI) AccessTokenResponseDetails(alfio.util.oauth2.AccessTokenResponseDetails) RefundRequest(alfio.model.transaction.capabilities.RefundRequest) MollieToken(alfio.model.transaction.token.MollieToken) HttpResponse(java.net.http.HttpResponse) FeeCalculator(alfio.manager.support.FeeCalculator) EXTERNAL_PROCESSING_PAYMENT(alfio.model.TicketReservation.TicketReservationStatus.EXTERNAL_PROCESSING_PAYMENT) java.util(java.util) ConfigurationLevel(alfio.manager.system.ConfigurationLevel) MaybeConfiguration(alfio.manager.system.ConfigurationManager.MaybeConfiguration) TicketReservationRepository(alfio.repository.TicketReservationRepository) ConfigurationManager(alfio.manager.system.ConfigurationManager) Cache(com.github.benmanes.caffeine.cache.Cache) JsonParser(com.google.gson.JsonParser) alfio.util(alfio.util) HttpRequest(java.net.http.HttpRequest) MollieWebhookPayload(alfio.model.transaction.webhook.MollieWebhookPayload) alfio.model.transaction(alfio.model.transaction) TransactionRepository(alfio.repository.TransactionRepository) HttpClient(java.net.http.HttpClient) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) TicketRepository(alfio.repository.TicketRepository) UTF_8(java.nio.charset.StandardCharsets.UTF_8) IOException(java.io.IOException) PaymentInfo(alfio.model.transaction.capabilities.PaymentInfo) WebhookHandler(alfio.model.transaction.capabilities.WebhookHandler) InputStreamReader(java.io.InputStreamReader) Component(org.springframework.stereotype.Component) Validate(org.apache.commons.lang3.Validate) StringReader(java.io.StringReader) TicketReservation(alfio.model.TicketReservation) Data(lombok.Data) Log4j2(lombok.extern.log4j.Log4j2) PaymentWebhookResult(alfio.manager.support.PaymentWebhookResult) PaymentManagerUtils.invalidateExistingTransactions(alfio.manager.payment.PaymentManagerUtils.invalidateExistingTransactions) AllArgsConstructor(lombok.AllArgsConstructor) ConfigurationKeys(alfio.model.system.ConfigurationKeys) WAITING_EXTERNAL_CONFIRMATION(alfio.model.TicketReservation.TicketReservationStatus.WAITING_EXTERNAL_CONFIRMATION) InputStream(java.io.InputStream) HttpRequest(java.net.http.HttpRequest) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject)

Aggregations

HttpResponse (java.net.http.HttpResponse)10 HttpClient (java.net.http.HttpClient)9 HttpRequest (java.net.http.HttpRequest)8 URI (java.net.URI)6 Duration (java.time.Duration)4 Test (org.junit.Test)4 SerializedClassRunner (io.pravega.test.common.SerializedClassRunner)3 TestUtils (io.pravega.test.common.TestUtils)3 Pattern (java.util.regex.Pattern)3 Cleanup (lombok.Cleanup)3 Assert.assertTrue (org.junit.Assert.assertTrue)3 RunWith (org.junit.runner.RunWith)3 ConfigurationKeys (alfio.model.system.ConfigurationKeys)2 Counter (io.pravega.shared.metrics.Counter)2 MetricsConfig (io.pravega.shared.metrics.MetricsConfig)2 MetricsProvider (io.pravega.shared.metrics.MetricsProvider)2 StatsProvider (io.pravega.shared.metrics.StatsProvider)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 InputStreamReader (java.io.InputStreamReader)2