Search in sources :

Example 36 with HttpClient

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

the class AbstractTestAuth_JDK method withAuthJDK.

public static UpdateExecutionHTTP withAuthJDK(UpdateExecutionHTTPBuilder builder, String user, String passwd) {
    Authenticator authenticator = AuthLib.authenticator(user, passwd);
    HttpClient hc = HttpClient.newBuilder().authenticator(authenticator).build();
    return builder.httpClient(hc).build();
}
Also used : HttpClient(java.net.http.HttpClient) Authenticator(java.net.Authenticator)

Example 37 with HttpClient

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

the class AbstractTestAuth_JDK method withAuthJDK.

public static QueryExecutionHTTP withAuthJDK(QueryExecutionHTTPBuilder builder, String user, String passwd) {
    Authenticator authenticator = AuthLib.authenticator(user, passwd);
    HttpClient hc = HttpClient.newBuilder().authenticator(authenticator).build();
    return builder.httpClient(hc).build();
}
Also used : HttpClient(java.net.http.HttpClient) Authenticator(java.net.Authenticator)

Example 38 with HttpClient

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

use of java.net.http.HttpClient in project redkale by redkale.

the class Utility method remoteHttpContentAsync.

public static CompletableFuture<ByteArrayOutputStream> remoteHttpContentAsync(java.net.http.HttpClient client, String method, String url, int timeout, Map<String, String> headers, String body) {
    java.net.http.HttpRequest.Builder builder = java.net.http.HttpRequest.newBuilder().uri(URI.create(url)).timeout(Duration.ofMillis(timeout > 0 ? timeout : 6000)).method(method, body == null ? java.net.http.HttpRequest.BodyPublishers.noBody() : java.net.http.HttpRequest.BodyPublishers.ofString(body));
    if (headers != null)
        headers.forEach((n, v) -> builder.header(n, v));
    java.net.http.HttpClient c = client == null ? httpClient : client;
    if (c == null) {
        synchronized (clientLock) {
            if (httpClient == null) {
                httpClient = java.net.http.HttpClient.newHttpClient();
            }
        }
        c = httpClient;
    }
    return c.sendAsync(builder.build(), java.net.http.HttpResponse.BodyHandlers.ofByteArray()).thenCompose((java.net.http.HttpResponse<byte[]> resp) -> {
        final int rs = resp.statusCode();
        if (rs == 301 || rs == 302) {
            Optional<String> opt = resp.headers().firstValue("Location");
            if (opt.isPresent()) {
                return remoteHttpContentAsync(client, method, opt.get(), timeout, headers, body);
            } else {
                return CompletableFuture.failedFuture(new IOException(url + " httpcode = " + rs + ", but not found Localtion"));
            }
        }
        byte[] result = resp.body();
        if (rs == 200 || result != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            if (result != null) {
                if ("gzip".equalsIgnoreCase(resp.headers().firstValue("content-encoding").orElse(null))) {
                    try {
                        GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(result));
                        in.transferTo(out);
                    } catch (IOException e) {
                        return CompletableFuture.failedFuture(e);
                    }
                } else {
                    out.writeBytes(result);
                }
            }
            return CompletableFuture.completedFuture(out);
        }
        return CompletableFuture.failedFuture(new IOException(url + " httpcode = " + rs));
    });
}
Also used : java.lang.reflect(java.lang.reflect) java.security(java.security) java.util(java.util) GZIPInputStream(java.util.zip.GZIPInputStream) UTF_8(java.nio.charset.StandardCharsets.UTF_8) java.util.concurrent(java.util.concurrent) CompletionHandler(java.nio.channels.CompletionHandler) java.nio(java.nio) java.nio.charset(java.nio.charset) java.time(java.time) java.net(java.net) Stream(java.util.stream.Stream) java.io(java.io) HttpClient(java.net.http.HttpClient) java.util.function(java.util.function) GZIPInputStream(java.util.zip.GZIPInputStream) HttpClient(java.net.http.HttpClient) java.net(java.net)

Example 40 with HttpClient

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

the class Http2Client method execute.

@Override
public Response execute(Request request, Options options) throws IOException {
    final HttpRequest httpRequest;
    try {
        httpRequest = newRequestBuilder(request, options).version(client.version()).build();
    } catch (URISyntaxException e) {
        throw new IOException("Invalid uri " + request.url(), e);
    }
    HttpClient clientForRequest = getOrCreateClient(options);
    HttpResponse<byte[]> httpResponse;
    try {
        httpResponse = clientForRequest.send(httpRequest, BodyHandlers.ofByteArray());
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException("Invalid uri " + request.url(), e);
    }
    return toFeignResponse(request, httpResponse);
}
Also used : HttpRequest(java.net.http.HttpRequest) HttpClient(java.net.http.HttpClient) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

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