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()));
}
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();
}
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)));
}
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();
}
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);
}
}
Aggregations