Search in sources :

Example 6 with HttpResponse

use of java.net.http.HttpResponse 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 7 with HttpResponse

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

the class AsyncHttpRDF method asyncGetToStream.

private static CompletableFuture<Void> asyncGetToStream(HttpClient httpClient, String url, Consumer<HttpRequest.Builder> modifier, StreamRDF dest, Transactional _transactional) {
    CompletableFuture<HttpResponse<InputStream>> cf = asyncGetToInput(httpClient, url, modifier);
    Transactional transact = (_transactional == null) ? TransactionalNull.create() : _transactional;
    return cf.thenApply(httpResponse -> {
        transact.executeWrite(() -> HttpRDF.httpResponseToStreamRDF(url, httpResponse, dest));
        return null;
    });
}
Also used : HttpResponse(java.net.http.HttpResponse) Transactional(org.apache.jena.sparql.core.Transactional)

Example 8 with HttpResponse

use of java.net.http.HttpResponse in project MinecraftForge by MinecraftForge.

the class VersionChecker method startVersionCheck.

public static void startVersionCheck() {
    new Thread("Forge Version Check") {

        private HttpClient client;

        @Override
        public void run() {
            if (!FMLConfig.runVersionCheck()) {
                LOGGER.info("Global Forge version check system disabled, no further processing.");
                return;
            }
            client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(HTTP_TIMEOUT_SECS)).build();
            gatherMods().forEach(this::process);
        }

        /**
         * Returns the response body as a String for the given URL while following redirects
         */
        private String openUrlString(URL url) throws IOException, URISyntaxException, InterruptedException {
            URL currentUrl = url;
            for (int redirects = 0; redirects < MAX_HTTP_REDIRECTS; redirects++) {
                var request = HttpRequest.newBuilder().uri(currentUrl.toURI()).timeout(Duration.ofSeconds(HTTP_TIMEOUT_SECS)).setHeader("Accept-Encoding", "gzip").GET().build();
                final HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
                int responseCode = response.statusCode();
                if (responseCode >= 300 && responseCode <= 399) {
                    String newLocation = response.headers().firstValue("Location").orElseThrow(() -> new IOException("Got a 3xx response code but Location header was null while trying to fetch " + url));
                    currentUrl = new URL(currentUrl, newLocation);
                    continue;
                }
                final boolean isGzipEncoded = response.headers().firstValue("Content-Encoding").orElse("").equals("gzip");
                final String bodyStr;
                try (InputStream inStream = isGzipEncoded ? new GZIPInputStream(response.body()) : response.body()) {
                    try (var bufferedReader = new BufferedReader(new InputStreamReader(inStream))) {
                        bodyStr = bufferedReader.lines().collect(Collectors.joining("\n"));
                    }
                }
                return bodyStr;
            }
            throw new IOException("Too many redirects while trying to fetch " + url);
        }

        private void process(IModInfo mod) {
            Status status = PENDING;
            ComparableVersion target = null;
            Map<ComparableVersion, String> changes = null;
            String display_url = null;
            try {
                if (mod.getUpdateURL().isEmpty())
                    return;
                URL url = mod.getUpdateURL().get();
                LOGGER.info("[{}] Starting version check at {}", mod.getModId(), url.toString());
                String data = openUrlString(url);
                LOGGER.debug("[{}] Received version check data:\n{}", mod.getModId(), data);
                @SuppressWarnings("unchecked") Map<String, Object> json = new Gson().fromJson(data, Map.class);
                @SuppressWarnings("unchecked") Map<String, String> promos = (Map<String, String>) json.get("promos");
                display_url = (String) json.get("homepage");
                var mcVersion = FMLLoader.versionInfo().mcVersion();
                String rec = promos.get(mcVersion + "-recommended");
                String lat = promos.get(mcVersion + "-latest");
                ComparableVersion current = new ComparableVersion(mod.getVersion().toString());
                if (rec != null) {
                    ComparableVersion recommended = new ComparableVersion(rec);
                    int diff = recommended.compareTo(current);
                    if (diff == 0)
                        status = UP_TO_DATE;
                    else if (diff < 0) {
                        status = AHEAD;
                        if (lat != null) {
                            ComparableVersion latest = new ComparableVersion(lat);
                            if (current.compareTo(latest) < 0) {
                                status = OUTDATED;
                                target = latest;
                            }
                        }
                    } else {
                        status = OUTDATED;
                        target = recommended;
                    }
                } else if (lat != null) {
                    ComparableVersion latest = new ComparableVersion(lat);
                    if (current.compareTo(latest) < 0)
                        status = BETA_OUTDATED;
                    else
                        status = BETA;
                    target = latest;
                } else
                    status = BETA;
                LOGGER.info("[{}] Found status: {} Current: {} Target: {}", mod.getModId(), status, current, target);
                changes = new LinkedHashMap<>();
                @SuppressWarnings("unchecked") Map<String, String> tmp = (Map<String, String>) json.get(mcVersion);
                if (tmp != null) {
                    List<ComparableVersion> ordered = new ArrayList<>();
                    for (String key : tmp.keySet()) {
                        ComparableVersion ver = new ComparableVersion(key);
                        if (ver.compareTo(current) > 0 && (target == null || ver.compareTo(target) < 1)) {
                            ordered.add(ver);
                        }
                    }
                    Collections.sort(ordered);
                    for (ComparableVersion ver : ordered) {
                        changes.put(ver, tmp.get(ver.toString()));
                    }
                }
            } catch (Exception e) {
                LOGGER.warn("Failed to process update information", e);
                status = FAILED;
            }
            results.put(mod, new CheckResult(status, target, changes, display_url));
        }
    }.start();
}
Also used : Status(net.minecraftforge.fml.VersionChecker.Status) InputStreamReader(java.io.InputStreamReader) IModInfo(net.minecraftforge.forgespi.language.IModInfo) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) HttpResponse(java.net.http.HttpResponse) Gson(com.google.gson.Gson) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) ComparableVersion(org.apache.maven.artifact.versioning.ComparableVersion) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) GZIPInputStream(java.util.zip.GZIPInputStream) HttpClient(java.net.http.HttpClient) BufferedReader(java.io.BufferedReader) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 9 with HttpResponse

use of java.net.http.HttpResponse in project feign by OpenFeign.

the class Http2Client method execute.

@Override
public CompletableFuture<Response> execute(Request request, Options options, Optional<Object> requestContext) {
    HttpRequest httpRequest;
    try {
        httpRequest = newRequestBuilder(request, options).build();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid uri " + request.url(), e);
    }
    HttpClient clientForRequest = getOrCreateClient(options);
    CompletableFuture<HttpResponse<byte[]>> future = clientForRequest.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofByteArray());
    return future.thenApply(httpResponse -> toFeignResponse(request, httpResponse));
}
Also used : HttpRequest(java.net.http.HttpRequest) HttpClient(java.net.http.HttpClient) HttpResponse(java.net.http.HttpResponse) URISyntaxException(java.net.URISyntaxException)

Example 10 with HttpResponse

use of java.net.http.HttpResponse in project weicoder by wdcode.

the class Jdk11Http method post.

@Override
public String post(String url, Map<String, Object> data, Map<String, Object> header) {
    try {
        // 请求body
        String body = S.add("?", S.toParameters(data));
        // // 判断有参数提交
        // if (U.E.isNotEmpty(data)) {
        // // 声明字符串缓存
        // StringBuilder sb = new StringBuilder("?");
        // // 循环参数
        // data.entrySet().forEach(e -> sb.append(e.getKey()).append("=").append(e.getValue()).append("&"));
        // body = sb.substring(0, sb.length() - 1);
        // }
        // 获得HttpRequest构建器
        HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(url + body));
        // 头不为空,添加头
        if (U.E.isNotEmpty(header))
            header.forEach((k, v) -> builder.setHeader(k, W.C.toString(v)));
        // HttpRequest
        HttpRequest request = builder.POST(BodyPublishers.noBody()).build();
        // 请求
        HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
        // Logs.debug("Jdk11Http post url={} data={} header={} res={}", url, data, header, res);
        return response.body();
    } catch (Exception e) {
        Logs.error(e, "Jdk11Http post url={} data={} header={}", url, data, header);
    }
    return C.S.EMPTY;
}
Also used : HttpRequest(java.net.http.HttpRequest) BaseHttp(com.weicoder.common.http.base.BaseHttp) Version(java.net.http.HttpClient.Version) BodyPublishers(java.net.http.HttpRequest.BodyPublishers) S(com.weicoder.common.U.S) W(com.weicoder.common.W) U(com.weicoder.common.U) HttpRequest(java.net.http.HttpRequest) C(com.weicoder.common.C) Map(java.util.Map) HttpClient(java.net.http.HttpClient) URI(java.net.URI) Logs(com.weicoder.common.log.Logs) HttpResponse(java.net.http.HttpResponse)

Aggregations

HttpResponse (java.net.http.HttpResponse)10 HttpClient (java.net.http.HttpClient)9 HttpRequest (java.net.http.HttpRequest)8 URI (java.net.URI)6 Duration (java.time.Duration)4 Test (org.junit.Test)4 SerializedClassRunner (io.pravega.test.common.SerializedClassRunner)3 TestUtils (io.pravega.test.common.TestUtils)3 Pattern (java.util.regex.Pattern)3 Cleanup (lombok.Cleanup)3 Assert.assertTrue (org.junit.Assert.assertTrue)3 RunWith (org.junit.runner.RunWith)3 ConfigurationKeys (alfio.model.system.ConfigurationKeys)2 Counter (io.pravega.shared.metrics.Counter)2 MetricsConfig (io.pravega.shared.metrics.MetricsConfig)2 MetricsProvider (io.pravega.shared.metrics.MetricsProvider)2 StatsProvider (io.pravega.shared.metrics.StatsProvider)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 InputStreamReader (java.io.InputStreamReader)2