1 | import com.fasterxml.jackson.databind.JsonNode;
|
---|
2 | import com.fasterxml.jackson.databind.ObjectMapper;
|
---|
3 |
|
---|
4 | import java.io.File;
|
---|
5 | import java.io.IOException;
|
---|
6 | import java.util.ArrayList;
|
---|
7 | import java.util.Iterator;
|
---|
8 | import java.util.List;
|
---|
9 | import java.util.concurrent.ConcurrentLinkedQueue;
|
---|
10 | import java.util.concurrent.CountDownLatch;
|
---|
11 |
|
---|
12 | public class Scraper extends Thread {
|
---|
13 | private List<String> urls;
|
---|
14 | private String destination;
|
---|
15 | private String departureDate;
|
---|
16 | private int numberOfPeople;
|
---|
17 | private ConcurrentLinkedQueue<Option> optionsQueue;
|
---|
18 | private CountDownLatch latch;
|
---|
19 |
|
---|
20 | public Scraper(String destination, String departureDate, int numberOfPeople) {
|
---|
21 | urls = new ArrayList<>();
|
---|
22 | this.optionsQueue = new ConcurrentLinkedQueue<>();
|
---|
23 | ObjectMapper mapper = new ObjectMapper();
|
---|
24 | try {
|
---|
25 | JsonNode root = mapper.readTree(new File("src/main/java/URLsJSON.json"));
|
---|
26 | JsonNode urlNode = root.get("agencyurls");
|
---|
27 | if (urlNode.isArray()) {
|
---|
28 | Iterator<JsonNode> elements = urlNode.elements();
|
---|
29 | while (elements.hasNext()) {
|
---|
30 | JsonNode next = elements.next();
|
---|
31 | urls.add(next.asText());
|
---|
32 | }
|
---|
33 | }
|
---|
34 | System.out.println("Loaded " + urls.size() + " urls");
|
---|
35 | } catch (IOException e) {
|
---|
36 | throw new RuntimeException(e);
|
---|
37 | }
|
---|
38 | this.destination = destination;
|
---|
39 | this.departureDate = departureDate;
|
---|
40 | this.numberOfPeople = numberOfPeople;
|
---|
41 | this.latch = new CountDownLatch(urls.size());
|
---|
42 | }
|
---|
43 |
|
---|
44 | @Override
|
---|
45 | public void run() {
|
---|
46 | System.out.println("Scraper has started ");
|
---|
47 | for (String url : urls) {
|
---|
48 | new ScraperThread(url, destination, departureDate, numberOfPeople, optionsQueue, latch).start();
|
---|
49 | }
|
---|
50 | }
|
---|
51 | public List<Option> getOptions() {
|
---|
52 | try {
|
---|
53 | latch.await(); // Wait for all threads to finish
|
---|
54 | } catch (InterruptedException e) {
|
---|
55 | e.printStackTrace();
|
---|
56 | }
|
---|
57 | return new ArrayList<>(optionsQueue);
|
---|
58 | }
|
---|
59 | }
|
---|