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