use of java.net.http.HttpClient in project alf.io by alfio-event.
the class MailjetMailerTest method send.
@Test
void send() throws Exception {
var attachment = new Mailer.Attachment("filename", "test".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of("model", "model"), Mailer.AttachmentIdentifier.CALENDAR_ICS);
@SuppressWarnings("unchecked") var response = (HttpResponse<Object>) mock(HttpResponse.class);
when(response.statusCode()).thenReturn(200);
when(httpClient.send(any(), any())).thenReturn(response);
mailjetMailer.send(configurable, "from_name", "to", List.of("cc"), "subject", "text", Optional.of("html"), attachment);
verify(httpClient).send(requestCaptor.capture(), eq(HttpResponse.BodyHandlers.discarding()));
// verify request
var request = requestCaptor.getValue();
assertNotNull(request);
var body = request.bodyPublisher().orElseThrow();
var semaphore = new Semaphore(1);
// acquire lock so that the async processing can complete before exiting the test
assertTrue(semaphore.tryAcquire());
body.subscribe(new Flow.Subscriber<>() {
private final StringBuffer buffer = new StringBuffer();
@Override
public void onSubscribe(Flow.Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(ByteBuffer item) {
buffer.append(new String(item.array(), StandardCharsets.UTF_8));
}
@Override
public void onError(Throwable throwable) {
fail(throwable);
}
@Override
public void onComplete() {
assertTrue(buffer.length() > 0);
var payload = Json.fromJson(buffer.toString(), new TypeReference<Map<String, JsonNode>>() {
});
assertNotNull(payload);
assertFalse(payload.isEmpty());
assertEquals("mail_from", getValue(payload.get("FromEmail")));
assertEquals("from_name", getValue(payload.get("FromName")));
assertEquals("subject", getValue(payload.get("Subject")));
assertEquals("text", getValue(payload.get("Text-part")));
assertEquals("html", getValue(payload.get("Html-part")));
var recipients = payload.get("Recipients");
var counter = new AtomicInteger(0);
var emails = List.of("to", "cc");
recipients.forEach(node -> {
if (emails.contains(node.get("Email").asText())) {
counter.incrementAndGet();
}
});
// we expect to find both addresses
assertEquals(2, counter.get());
assertEquals("mail_to", payload.get("Headers").get("Reply-To").asText());
assertEquals(1, payload.get("Attachments").size());
var attachment = payload.get("Attachments").get(0);
assertEquals("filename", attachment.get("Filename").asText());
assertEquals("text/plain", attachment.get("Content-type").asText());
assertEquals(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)), attachment.get("content").asText());
var headers = request.headers();
assertEquals(HttpUtils.APPLICATION_JSON, headers.firstValue(HttpUtils.CONTENT_TYPE).orElseThrow());
assertEquals(HttpUtils.basicAuth("public", "private"), headers.firstValue(HttpUtils.AUTHORIZATION).orElseThrow());
semaphore.release();
}
});
assertTrue(semaphore.tryAcquire(1, TimeUnit.SECONDS));
}
use of java.net.http.HttpClient in project jena by apache.
the class RemoteEndpointDriver method configureClient.
protected HttpClient configureClient(Properties props) throws SQLException {
// Try to get credentials to use
String user = props.getProperty(PARAM_USERNAME, null);
if (user != null && user.trim().isEmpty())
user = null;
String password = props.getProperty(PARAM_PASSWORD, null);
if (password != null && password.trim().isEmpty())
password = null;
// If credentials then we use them
if (user != null && password != null) {
return HttpClient.newBuilder().authenticator(AuthLib.authenticator(user, password)).build();
}
// else use a supplied or default client
Object client = props.get(PARAM_CLIENT);
if (client != null) {
if (client.getClass().getName().equals("org.apache.http.client.HttpClient")) {
Log.warn(this, "Found Apache HttpClient for context symbol " + PARAM_CLIENT + ". Jena now uses java.net.http.HttpClient");
return null;
}
if (!(client instanceof HttpClient))
throw new SQLException("The " + PARAM_CLIENT + " parameter is specified but the value is not an object implementing the required HttpClient interface");
return (HttpClient) client;
}
return null;
}
use of java.net.http.HttpClient in project jena by apache.
the class RDFConnection method connectPW.
/**
* Make a remote RDFConnection to the URL, with user and password for the client access using basic auth.
* Use with care – basic auth over plain HTTP reveals the password on the network.
* @param URL
* @param user
* @param password
* @return RDFConnection
*/
public static RDFConnection connectPW(String URL, String user, String password) {
Objects.requireNonNull(URL);
Objects.requireNonNull(user);
Objects.requireNonNull(password);
// Authenticator to hold user and password.
Authenticator authenticator = LibSec.authenticator(user, password);
HttpClient client = HttpEnv.httpClientBuilder().authenticator(authenticator).build();
return RDFConnectionRemote.newBuilder().destination(URL).httpClient(client).build();
}
use of java.net.http.HttpClient 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;
}
use of java.net.http.HttpClient in project jena by apache.
the class ExAuth01_RDFConnectionPW method exampleConnectionAuthWithHttpClient.
// HttpClient
public static void exampleConnectionAuthWithHttpClient() {
System.out.println();
System.out.println("HttpClient + RDFConnectionRemote");
// Custom HttpClient
Authenticator authenticator = AuthLib.authenticator("u", "p");
HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).authenticator(authenticator).build();
try (RDFConnection conn = RDFConnectionRemote.service(dataURL).httpClient(// Custom HttpClient
httpClient).build()) {
conn.update("INSERT DATA{}");
conn.queryAsk("ASK{}");
}
}
Aggregations