Search in sources :

Example 21 with HttpRequest

use of java.net.http.HttpRequest 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)

Example 22 with HttpRequest

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

the class MollieWebhookPaymentManager method fetchAvailablePaymentMethods.

private Set<PaymentMethod> fetchAvailablePaymentMethods(MethodCacheKey key, Map<ConfigurationKeys, MaybeConfiguration> configuration, ConfigurationLevel configurationLevel) {
    var params = new ArrayList<String>();
    if (key.amount != null) {
        params.add("amount[value]=" + key.amount.getValue());
        params.add("amount[currency]=" + key.amount.getCurrency());
    }
    if (key.billingCountry != null) {
        params.add("billingCountry=" + key.billingCountry);
    }
    if (configuration.get(PLATFORM_MODE_ENABLED).getValueAsBooleanOrDefault()) {
        params.add("testmode=" + key.testMode);
        params.add("profileId=" + configuration.get(MOLLIE_CONNECT_PROFILE_ID).getRequiredValue());
    }
    HttpRequest request = requestFor(METHODS_ENDPOINT + "?" + String.join("&", params), configuration, configurationLevel).GET().build();
    try {
        var response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
        if (!HttpUtils.callSuccessful(response)) {
            throw new IllegalStateException("fetch was unsuccessful (HTTP " + response.statusCode() + ")");
        }
        try (var reader = new InputStreamReader(response.body(), UTF_8)) {
            var body = JsonParser.parseReader(reader).getAsJsonObject();
            int count = body.get("count").getAsInt();
            if (count == 0) {
                return EMPTY_METHODS;
            }
            var methodsObj = body.getAsJsonObject("_embedded").getAsJsonArray("methods");
            var rejectedMethods = new ArrayList<String>();
            var result = EnumSet.noneOf(PaymentMethod.class);
            for (int i = 0; i < count; i++) {
                var methodId = methodsObj.get(i).getAsJsonObject().get("id").getAsString();
                var parsed = SUPPORTED_METHODS.get(methodId);
                if (parsed != null) {
                    result.add(parsed);
                } else {
                    rejectedMethods.add(methodId);
                }
            }
            if (rejectedMethods.isEmpty()) {
                return result;
            } else {
                log.warn("Unsupported payment methods found: {}. Please check configuration", rejectedMethods);
                throw new IllegalStateException("unsupported methods found");
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IllegalStateException(e);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
Also used : HttpRequest(java.net.http.HttpRequest) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException)

Example 23 with HttpRequest

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

the class MailgunMailer method send.

@Override
public void send(Configurable configurable, String fromName, String to, List<String> cc, String subject, String text, Optional<String> html, Attachment... attachment) {
    var conf = configurationManager.getFor(Set.of(MAILGUN_KEY, MAILGUN_DOMAIN, MAILGUN_EU, MAILGUN_FROM, MAIL_REPLY_TO), configurable.getConfigurationLevel());
    String apiKey = conf.get(MAILGUN_KEY).getRequiredValue();
    String domain = conf.get(MAILGUN_DOMAIN).getRequiredValue();
    boolean useEU = conf.get(MAILGUN_EU).getValueAsBooleanOrDefault();
    String baseUrl = useEU ? "https://api.eu.mailgun.net/v3/" : "https://api.mailgun.net/v3/";
    try {
        var from = fromName + " <" + conf.get(MAILGUN_FROM).getRequiredValue() + ">";
        var replyTo = conf.get(MAIL_REPLY_TO).getValueOrDefault("");
        var emailData = getEmailData(from, to, replyTo, cc, subject, text, html);
        var requestBuilder = HttpRequest.newBuilder().uri(URI.create(baseUrl + domain + "/messages")).header(HttpUtils.AUTHORIZATION, HttpUtils.basicAuth("api", apiKey));
        if (ArrayUtils.isEmpty(attachment)) {
            requestBuilder.header(HttpUtils.CONTENT_TYPE, HttpUtils.APPLICATION_FORM_URLENCODED);
            requestBuilder.POST(HttpUtils.ofFormUrlEncodedBody(emailData));
        } else {
            var mpb = new HttpUtils.MultiPartBodyPublisher();
            requestBuilder.header(HttpUtils.CONTENT_TYPE, HttpUtils.MULTIPART_FORM_DATA + ";boundary=\"" + mpb.getBoundary() + "\"");
            emailData.forEach(mpb::addPart);
            Stream.of(attachment).forEach(a -> mpb.addPart("attachment", () -> new ByteArrayInputStream(a.getSource()), a.getFilename(), a.getContentType()));
            requestBuilder.POST(mpb.build());
        }
        HttpRequest request = requestBuilder.build();
        HttpResponse<?> response = client.send(request, HttpResponse.BodyHandlers.discarding());
        if (!HttpUtils.callSuccessful(response)) {
            log.warn("sending email was not successful:" + response);
            throw new IllegalStateException("Attempt to send a message failed. Result is: " + response.statusCode());
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        log.warn("Request interrupted while calling Mailgun API", e);
        throw new IllegalStateException(e);
    } catch (IOException e) {
        log.warn("error while sending email", e);
        throw new IllegalStateException(e);
    }
}
Also used : HttpRequest(java.net.http.HttpRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException)

Example 24 with HttpRequest

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

the class SimpleHttpClient method postFileAndSaveResponse.

public SimpleHttpClientCachedResponse postFileAndSaveResponse(String url, Map<String, String> headers, String file, String filename, String contentType) throws IOException {
    var mpb = new HttpUtils.MultiPartBodyPublisher();
    mpb.addPart("file", () -> {
        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new IllegalStateException(e);
        }
    }, filename, contentType);
    HttpRequest request = buildUrlAndHeader(url, headers, HttpUtils.MULTIPART_FORM_DATA + ";boundary=\"" + mpb.getBoundary() + "\"").POST(mpb.build()).build();
    return callRemoteAndSaveResponse(request);
}
Also used : HttpRequest(java.net.http.HttpRequest)

Example 25 with HttpRequest

use of java.net.http.HttpRequest in project jena by apache.

the class HttpLib method isFuseki.

/**
 * Test whether a URL identifies a Fuseki server. This operation can not guarantee to
 * detect a Fuseki server - for example, it may be behind a reverse proxy that masks
 * the signature.
 */
public static boolean isFuseki(String datasetURL) {
    HttpRequest.Builder builder = HttpRequest.newBuilder().uri(toRequestURI(datasetURL)).method(HttpNames.METHOD_HEAD, BodyPublishers.noBody());
    HttpRequest request = builder.build();
    HttpClient httpClient = HttpEnv.getDftHttpClient();
    HttpResponse<InputStream> response = execute(httpClient, request);
    handleResponseNoBody(response);
    Optional<String> value1 = response.headers().firstValue(FusekiRequestIdHeader);
    if (value1.isPresent())
        return true;
    Optional<String> value2 = response.headers().firstValue("Server");
    if (value2.isEmpty())
        return false;
    String headerValue = value2.get();
    boolean isFuseki = headerValue.startsWith("Apache Jena Fuseki") || headerValue.toLowerCase().contains("fuseki");
    return isFuseki;
}
Also used : HttpRequest(java.net.http.HttpRequest) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) TypedInputStream(org.apache.jena.atlas.web.TypedInputStream) InputStream(java.io.InputStream) HttpClient(java.net.http.HttpClient) Builder(java.net.http.HttpRequest.Builder)

Aggregations

HttpRequest (java.net.http.HttpRequest)38 InputStream (java.io.InputStream)15 HttpClient (java.net.http.HttpClient)10 TypedInputStream (org.apache.jena.atlas.web.TypedInputStream)10 URI (java.net.URI)9 IOException (java.io.IOException)7 HttpResponse (java.net.http.HttpResponse)7 Duration (java.time.Duration)6 Test (org.junit.Test)5 HttpException (org.apache.jena.atlas.web.HttpException)4 SerializedClassRunner (io.pravega.test.common.SerializedClassRunner)3 TestUtils (io.pravega.test.common.TestUtils)3 URISyntaxException (java.net.URISyntaxException)3 Pattern (java.util.regex.Pattern)3 Cleanup (lombok.Cleanup)3 Assert.assertTrue (org.junit.Assert.assertTrue)3 RunWith (org.junit.runner.RunWith)3 JsonParser (com.google.gson.JsonParser)2 Counter (io.pravega.shared.metrics.Counter)2 MetricsConfig (io.pravega.shared.metrics.MetricsConfig)2