2727import java .util .concurrent .Executors ;
2828import java .util .concurrent .Semaphore ;
2929
30+ /**
31+ * Retrieves and caches XKCD comic posts from the official XKCD JSON API.
32+ * <p>
33+ * This class handles fetching XKCD comics (1-{@value #XKCD_POSTS_AMOUNT}, excluding the joke comic
34+ * #404) using concurrent HTTP requests with rate limiting via semaphore and thread pool.
35+ * <p>
36+ * Posts are cached locally in {@value #SAVED_XKCD_PATH} as JSON and uploaded to OpenAI using the
37+ * provided {@link ChatGptService} if not already present.
38+ */
3039public class XkcdRetriever {
3140
3241 private static final Logger logger = LoggerFactory .getLogger (XkcdRetriever .class );
@@ -74,6 +83,18 @@ public XkcdRetriever(ChatGptService chatGptService) {
7483 fetchAllXkcdPosts (savedXckdsPath );
7584 }
7685
86+ public Optional <XkcdPost > getXkcdPost (int id ) {
87+ return Optional .ofNullable (xkcdPosts .get (id ));
88+ }
89+
90+ public String getXkcdUploadedFileId () {
91+ return xkcdUploadedFileId ;
92+ }
93+
94+ public Map <Integer , XkcdPost > getXkcdPosts () {
95+ return xkcdPosts ;
96+ }
97+
7798 private void fetchAllXkcdPosts (Path savedXckdsPath ) {
7899 objectMapper .enable (SerializationFeature .INDENT_OUTPUT );
79100 Semaphore semaphore = new Semaphore (FETCH_XKCD_POSTS_SEMAPHORE_SIZE );
@@ -105,11 +126,7 @@ private void fetchAllXkcdPosts(Path savedXckdsPath) {
105126 SAVED_XKCD_PATH );
106127 }
107128
108- public Optional <XkcdPost > getXkcdPost (int id ) {
109- return Optional .ofNullable (xkcdPosts .get (id ));
110- }
111-
112- public CompletableFuture <Optional <XkcdPost >> retrieveXkcdPost (int id ) {
129+ private CompletableFuture <Optional <XkcdPost >> retrieveXkcdPost (int id ) {
113130 HttpRequest request =
114131 HttpRequest .newBuilder (URI .create (String .format (XKCD_GET_URL , id ))).build ();
115132
@@ -150,7 +167,7 @@ private void uploadXkcdFile(Path savedXckdsPath) {
150167
151168 }
152169
153- public void saveToFile (Path path , Map <Integer , XkcdPost > posts ) {
170+ private void saveToFile (Path path , Map <Integer , XkcdPost > posts ) {
154171 try {
155172 objectMapper .writeValue (path .toFile (), posts );
156173 logger .info ("Saved XKCD posts to '{}'" , path );
@@ -174,12 +191,4 @@ private void populateXkcdPostsFromFile(Path path) {
174191 logger .error ("Failed to load XKCD posts from {}" , path , e );
175192 }
176193 }
177-
178- public String getXkcdUploadedFileId () {
179- return xkcdUploadedFileId ;
180- }
181-
182- public Map <Integer , XkcdPost > getXkcdPosts () {
183- return xkcdPosts ;
184- }
185194}
0 commit comments