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