Created
April 13, 2020 17:13
-
-
Save ibaca/d5a76f24821612913550f27a9b23203b to your computer and use it in GitHub Desktop.
Intendia - Driver files download example - Java 11 no dependencies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.nio.charset.StandardCharsets.ISO_8859_1; | |
import static java.nio.file.StandardOpenOption.CREATE; | |
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; | |
import static java.nio.file.StandardOpenOption.WRITE; | |
import static java.util.stream.Collectors.toList; | |
import java.net.URI; | |
import java.net.http.HttpClient; | |
import java.net.http.HttpRequest; | |
import java.net.http.HttpResponse.BodyHandlers; | |
import java.nio.file.Path; | |
import java.util.Base64; | |
import java.util.concurrent.TimeUnit; | |
import java.util.function.BiFunction; | |
import java.util.prefs.Preferences; | |
/** {@code Usage: java DriverDownloadService.java <API_KEY>} */ | |
public class DriverDownloadService { | |
public static final String INTENDIA_API = "https://igp.intendia.com/api"; | |
public static final String LAST_DFILE_KEY = "intendia.lastDriverFileId"; | |
public static void main(String[] args) throws Exception { | |
if (args.length == 0 || args[0].isEmpty()) throw new IllegalAccessException("api-key required"); | |
var client = HttpClient.newHttpClient(); // basic auth using the api-key… | |
var credentials = "Basic " + Base64.getEncoder().encodeToString((args[0] + ":X").getBytes(ISO_8859_1)); | |
BiFunction<String, String, HttpRequest.Builder> REQ = (path, accept) -> HttpRequest | |
.newBuilder(URI.create(INTENDIA_API + "/" + path)) | |
.header("Authorization", credentials).header("Accept", accept); | |
var donwloadTo = BodyHandlers.ofFileDownload(Path.of(".")/*current folder*/, CREATE, TRUNCATE_EXISTING, WRITE); | |
int lastDrvId = Preferences.userRoot().getInt(LAST_DFILE_KEY/* last processed driver file Id */, 0); | |
while (true) { | |
System.out.println("requesting file list since " + lastDrvId + "…"); | |
var files = client.send(REQ.apply("dtco/driverFiles?fileIdSince=" + lastDrvId + "&max=3&fields=fileId", | |
"text/csv").build(), BodyHandlers.ofLines()).body().collect(toList()); | |
for (var fileId : files) { | |
System.out.println("downloading file " + fileId + "…"); | |
client.send(REQ.apply("dtco/driverFiles/" + fileId, "application/octet-stream").build(), donwloadTo); | |
lastDrvId = Integer.parseInt(fileId); | |
Preferences.userRoot().putInt(LAST_DFILE_KEY, lastDrvId); | |
} | |
if (files.isEmpty()) { | |
System.out.println("all files download, retrying in 5minutes… "); | |
Thread.sleep(TimeUnit.MINUTES.toMillis(5)); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment