Skip to content

Instantly share code, notes, and snippets.

@AtharvaWaghchoure
Created June 2, 2024 17:06
Show Gist options
  • Save AtharvaWaghchoure/6f39359937ebf417da4f09e46d94f167 to your computer and use it in GitHub Desktop.
Save AtharvaWaghchoure/6f39359937ebf417da4f09e46d94f167 to your computer and use it in GitHub Desktop.
[package]
name = "javasdk"
version = "0.1.0"
edition = "2021"
[dependencies]
reqwest = { version = "0.11", features = ["blocking", "json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }
indicatif = "0.16"
use indicatif::{ProgressBar, ProgressStyle};
use reqwest::blocking::Client;
use serde::Deserialize;
use std::fs::File;
use std::io::{copy, Read, Write};
use std::path::Path;
#[derive(Deserialize)]
struct Asset {
browser_download_url: String,
name: String,
}
#[derive(Deserialize)]
struct Release {
assets: Vec<Asset>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Specify the tag for the release
let tag = "jdk-11.0.22+7";
// Create the HTTP client
let client = Client::new();
// Construct the API URL to fetch releases by tag
let api_url = format!(
"https://api.github.com/repos/adoptium/temurin11-binaries/releases/tags/{}",
tag
);
// Perform the request to get the release data by tag
let response = client
.get(&api_url)
.header("Accept", "application/vnd.github.v3+json")
.header("User-Agent", "rust-client")
.send()?;
// Check if the request was successful
if !response.status().is_success() {
return Err(format!("Failed to fetch release info: {}", response.status()).into());
}
// Parse the response body as JSON
let release_data: Release = response.json()?;
// Find the correct asset for the desired platform
let desired_asset = release_data
.assets
.iter()
.find(|asset| asset.name.contains("OpenJDK11U-jre_x64_linux_hotspot"))
.ok_or("Desired asset not found")?;
// Get the download URL for the desired asset
let download_url = &desired_asset.browser_download_url;
// Perform the request to get the asset
let mut response = client
.get(download_url)
.header("User-Agent", "rust-client")
.send()?;
// Check if the request was successful
if !response.status().is_success() {
return Err(format!("Failed to download file: {}", response.status()).into());
}
// Get the content length for the progress bar
let total_size = response
.content_length()
.ok_or("Failed to get content length")?;
// Create the progress bar
let pb = ProgressBar::new(total_size);
pb.set_style(
ProgressStyle::default_bar()
.template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")
.progress_chars("#>-"),
);
// Specify the output file path
let output_file = Path::new("OpenJDK11U-jre_x64_linux_hotspot.tar.gz");
// Create the output file
let mut file = File::create(&output_file)?;
// Create a buffer to read the response
let mut buffer = vec![0; 8192];
let mut downloaded = 0;
// Read the response body and write to the file
while let Ok(n) = response.read(&mut buffer) {
if n == 0 {
break;
}
file.write_all(&buffer[..n])?;
downloaded += n as u64;
pb.set_position(downloaded);
}
// Finish the progress bar
pb.finish_with_message("Download completed successfully!");
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment