Search in sources :

Example 21 with HttpClient

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));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) MAIL_REPLY_TO(alfio.model.system.ConfigurationKeys.MAIL_REPLY_TO) java.util(java.util) HttpUtils(alfio.util.HttpUtils) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) CompletableFuture(java.util.concurrent.CompletableFuture) ByteBuffer(java.nio.ByteBuffer) HttpRequest(java.net.http.HttpRequest) Json(alfio.util.Json) ArgumentCaptor(org.mockito.ArgumentCaptor) SSLSession(javax.net.ssl.SSLSession) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Flow(java.util.concurrent.Flow) Configurable(alfio.model.Configurable) JsonNode(com.fasterxml.jackson.databind.JsonNode) HttpClient(java.net.http.HttpClient) URI(java.net.URI) TypeReference(com.fasterxml.jackson.core.type.TypeReference) HttpResponse(java.net.http.HttpResponse) Semaphore(java.util.concurrent.Semaphore) StandardCharsets(java.nio.charset.StandardCharsets) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) Test(org.junit.jupiter.api.Test) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) MaybeConfigurationBuilder.existing(alfio.manager.testSupport.MaybeConfigurationBuilder.existing) Assertions(org.junit.jupiter.api.Assertions) ConfigurationKeys(alfio.model.system.ConfigurationKeys) MaybeConfigurationBuilder(alfio.manager.testSupport.MaybeConfigurationBuilder) HttpHeaders(java.net.http.HttpHeaders) HttpResponse(java.net.http.HttpResponse) JsonNode(com.fasterxml.jackson.databind.JsonNode) Semaphore(java.util.concurrent.Semaphore) ByteBuffer(java.nio.ByteBuffer) Flow(java.util.concurrent.Flow) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Test(org.junit.jupiter.api.Test)

Example 22 with HttpClient

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;
}
Also used : SQLException(java.sql.SQLException) HttpClient(java.net.http.HttpClient)

Example 23 with HttpClient

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 &ndash; 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();
}
Also used : HttpClient(java.net.http.HttpClient) Authenticator(java.net.Authenticator)

Example 24 with HttpClient

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

Example 25 with HttpClient

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{}");
    }
}
Also used : RDFConnection(org.apache.jena.rdfconnection.RDFConnection) HttpClient(java.net.http.HttpClient) Authenticator(java.net.Authenticator)

Aggregations

HttpClient (java.net.http.HttpClient)42 Authenticator (java.net.Authenticator)11 HttpRequest (java.net.http.HttpRequest)8 HttpResponse (java.net.http.HttpResponse)6 URI (java.net.URI)4 RDFConnection (org.apache.jena.rdfconnection.RDFConnection)4 RDFFormat (org.apache.jena.riot.RDFFormat)4 Context (org.apache.jena.sparql.util.Context)4 SerializedClassRunner (io.pravega.test.common.SerializedClassRunner)3 TestUtils (io.pravega.test.common.TestUtils)3 URISyntaxException (java.net.URISyntaxException)3 Duration (java.time.Duration)3 Pattern (java.util.regex.Pattern)3 GZIPInputStream (java.util.zip.GZIPInputStream)3 Cleanup (lombok.Cleanup)3 DatasetGraph (org.apache.jena.sparql.core.DatasetGraph)3 Assert.assertTrue (org.junit.Assert.assertTrue)3 Test (org.junit.Test)3 RunWith (org.junit.runner.RunWith)3 Counter (io.pravega.shared.metrics.Counter)2