-
-
Notifications
You must be signed in to change notification settings - Fork 669
/
WebDriverManager.java
1171 lines (1002 loc) · 42.8 KB
/
WebDriverManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.bonigarcia.wdm;
import static io.github.bonigarcia.wdm.config.Architecture.ARM64;
import static io.github.bonigarcia.wdm.config.Architecture.X32;
import static io.github.bonigarcia.wdm.config.Architecture.X64;
import static io.github.bonigarcia.wdm.config.Config.isNullOrEmpty;
import static io.github.bonigarcia.wdm.config.DriverManagerType.CHROME;
import static io.github.bonigarcia.wdm.config.DriverManagerType.CHROMIUM;
import static io.github.bonigarcia.wdm.config.DriverManagerType.EDGE;
import static io.github.bonigarcia.wdm.config.DriverManagerType.FIREFOX;
import static io.github.bonigarcia.wdm.config.DriverManagerType.IEXPLORER;
import static io.github.bonigarcia.wdm.config.DriverManagerType.OPERA;
import static io.github.bonigarcia.wdm.config.DriverManagerType.PHANTOMJS;
import static io.github.bonigarcia.wdm.config.DriverManagerType.SELENIUM_SERVER_STANDALONE;
import static io.github.bonigarcia.wdm.config.OperatingSystem.LINUX;
import static io.github.bonigarcia.wdm.config.OperatingSystem.MAC;
import static io.github.bonigarcia.wdm.config.OperatingSystem.WIN;
import static java.lang.Integer.parseInt;
import static java.lang.String.valueOf;
import static java.lang.invoke.MethodHandles.lookup;
import static java.nio.charset.Charset.defaultCharset;
import static java.util.Collections.singletonList;
import static java.util.Collections.sort;
import static java.util.Locale.ROOT;
import static java.util.Optional.empty;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.compile;
import static javax.xml.xpath.XPathConstants.NODESET;
import static javax.xml.xpath.XPathFactory.newInstance;
import static org.apache.commons.io.FileUtils.cleanDirectory;
import static org.apache.commons.io.FilenameUtils.removeExtension;
import static org.apache.commons.lang3.StringUtils.isNumeric;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import io.github.bonigarcia.wdm.cache.CacheHandler;
import io.github.bonigarcia.wdm.cache.ResolutionCache;
import io.github.bonigarcia.wdm.config.Architecture;
import io.github.bonigarcia.wdm.config.Config;
import io.github.bonigarcia.wdm.config.DriverManagerType;
import io.github.bonigarcia.wdm.config.OperatingSystem;
import io.github.bonigarcia.wdm.config.WebDriverManagerException;
import io.github.bonigarcia.wdm.managers.ChromeDriverManager;
import io.github.bonigarcia.wdm.managers.ChromiumDriverManager;
import io.github.bonigarcia.wdm.managers.EdgeDriverManager;
import io.github.bonigarcia.wdm.managers.FirefoxDriverManager;
import io.github.bonigarcia.wdm.managers.InternetExplorerDriverManager;
import io.github.bonigarcia.wdm.managers.OperaDriverManager;
import io.github.bonigarcia.wdm.managers.PhantomJsDriverManager;
import io.github.bonigarcia.wdm.managers.SeleniumServerStandaloneManager;
import io.github.bonigarcia.wdm.managers.VoidDriverManager;
import io.github.bonigarcia.wdm.online.BitBucketApi;
import io.github.bonigarcia.wdm.online.Downloader;
import io.github.bonigarcia.wdm.online.GitHubApi;
import io.github.bonigarcia.wdm.online.HttpClient;
import io.github.bonigarcia.wdm.online.S3NamespaceContext;
import io.github.bonigarcia.wdm.online.UrlHandler;
import io.github.bonigarcia.wdm.versions.VersionComparator;
import io.github.bonigarcia.wdm.versions.VersionDetector;
/**
* Parent driver manager.
*
* @author Boni Garcia (boni.gg@gmail.com)
* @since 2.1.0
*/
public abstract class WebDriverManager {
protected static final Logger log = getLogger(lookup().lookupClass());
protected static final String SLASH = "/";
protected static final String LATEST_RELEASE = "LATEST_RELEASE";
protected static final NamespaceContext S3_NAMESPACE_CONTEXT = new S3NamespaceContext();
protected abstract List<URL> getDriverUrls() throws IOException;
protected abstract String getDriverName();
protected abstract String getDriverVersion();
protected abstract void setDriverVersion(String driverVersion);
protected abstract String getBrowserVersion();
protected abstract void setBrowserVersion(String browserVersion);
protected abstract void setDriverUrl(URL url);
protected abstract URL getDriverUrl();
protected abstract Optional<URL> getMirrorUrl();
protected abstract Optional<String> getExportParameter();
protected static Map<DriverManagerType, WebDriverManager> instanceMap = new EnumMap<>(
DriverManagerType.class);
public abstract DriverManagerType getDriverManagerType();
protected HttpClient httpClient;
protected Downloader downloader;
protected String downloadedDriverVersion;
protected String downloadedDriverPath;
protected boolean mirrorLog;
protected boolean forcedArch;
protected boolean forcedOs;
protected int retryCount = 0;
protected Config config = new Config();
protected ResolutionCache resolutionCache;
protected CacheHandler cacheHandler;
protected VersionDetector versionDetector;
public static Config globalConfig() {
Config global = new Config();
global.setAvoidAutoReset(true);
for (DriverManagerType type : DriverManagerType.values()) {
WebDriverManager.getInstance(type).setConfig(global);
}
return global;
}
public Config config() {
return config;
}
public static synchronized WebDriverManager chromedriver() {
instanceMap.putIfAbsent(CHROME, new ChromeDriverManager());
return instanceMap.get(CHROME);
}
public static synchronized WebDriverManager chromiumdriver() {
instanceMap.putIfAbsent(CHROMIUM, new ChromiumDriverManager());
return instanceMap.get(CHROMIUM);
}
public static synchronized WebDriverManager firefoxdriver() {
instanceMap.putIfAbsent(FIREFOX, new FirefoxDriverManager());
return instanceMap.get(FIREFOX);
}
public static synchronized WebDriverManager operadriver() {
instanceMap.putIfAbsent(OPERA, new OperaDriverManager());
return instanceMap.get(OPERA);
}
public static synchronized WebDriverManager edgedriver() {
instanceMap.putIfAbsent(EDGE, new EdgeDriverManager());
return instanceMap.get(EDGE);
}
public static synchronized WebDriverManager iedriver() {
instanceMap.putIfAbsent(IEXPLORER, new InternetExplorerDriverManager());
return instanceMap.get(IEXPLORER);
}
public static synchronized WebDriverManager phantomjs() {
instanceMap.putIfAbsent(PHANTOMJS, new PhantomJsDriverManager());
return instanceMap.get(PHANTOMJS);
}
public static synchronized WebDriverManager seleniumServerStandalone() {
instanceMap.putIfAbsent(SELENIUM_SERVER_STANDALONE,
new SeleniumServerStandaloneManager());
return instanceMap.get(SELENIUM_SERVER_STANDALONE);
}
protected static synchronized WebDriverManager voiddriver() {
return new VoidDriverManager();
}
public static synchronized WebDriverManager getInstance(
DriverManagerType driverManagerType) {
if (driverManagerType == null) {
return voiddriver();
}
switch (driverManagerType) {
case CHROME:
return chromedriver();
case CHROMIUM:
return chromiumdriver();
case FIREFOX:
return firefoxdriver();
case OPERA:
return operadriver();
case IEXPLORER:
return iedriver();
case EDGE:
return edgedriver();
case PHANTOMJS:
return phantomjs();
case SELENIUM_SERVER_STANDALONE:
return seleniumServerStandalone();
default:
return voiddriver();
}
}
public static synchronized WebDriverManager getInstance(
Class<?> webDriverClass) {
switch (webDriverClass.getName()) {
case "org.openqa.selenium.chrome.ChromeDriver":
return chromedriver();
case "org.openqa.selenium.firefox.FirefoxDriver":
return firefoxdriver();
case "org.openqa.selenium.opera.OperaDriver":
return operadriver();
case "org.openqa.selenium.ie.InternetExplorerDriver":
return iedriver();
case "org.openqa.selenium.edge.EdgeDriver":
return edgedriver();
case "org.openqa.selenium.phantomjs.PhantomJSDriver":
return phantomjs();
default:
return voiddriver();
}
}
public synchronized void setup() {
DriverManagerType driverManagerType = getDriverManagerType();
initResolutionCache();
cacheHandler = new CacheHandler(config);
if (driverManagerType != null) {
try {
if (config().getClearingDriverCache()) {
clearDriverCache();
}
if (config().getClearingResolutionCache()) {
clearResolutionCache();
}
String driverVersion = getDriverVersion();
manage(driverVersion);
} finally {
if (!config().isAvoidAutoReset()) {
reset();
}
}
}
}
public WebDriverManager driverVersion(String driverVersion) {
setDriverVersion(driverVersion);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager browserVersion(String browserVersion) {
setBrowserVersion(browserVersion);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager architecture(Architecture architecture) {
config().setArchitecture(architecture);
forcedArch = true;
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager arch32() {
architecture(X32);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager arch64() {
architecture(X64);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager arm64() {
architecture(ARM64);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager win() {
operatingSystem(WIN);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager linux() {
operatingSystem(LINUX);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager mac() {
operatingSystem(MAC);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager operatingSystem(OperatingSystem os) {
config().setOs(os.name());
forcedOs = true;
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager forceDownload() {
config().setForceDownload(true);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager driverRepositoryUrl(URL url) {
setDriverUrl(url);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager useMirror() {
Optional<URL> mirrorUrl = getMirrorUrl();
if (!mirrorUrl.isPresent()) {
throw new WebDriverManagerException("Mirror URL not available");
}
config().setUseMirror(true);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager proxy(String proxy) {
config().setProxy(proxy);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager proxyUser(String proxyUser) {
config().setProxyUser(proxyUser);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager proxyPass(String proxyPass) {
config().setProxyPass(proxyPass);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager useBetaVersions() {
config().setUseBetaVersions(true);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager ignoreDriverVersions(String... driverVersions) {
config().setIgnoreVersions(driverVersions);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager gitHubToken(String gitHubToken) {
config().setGitHubToken(gitHubToken);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager localRepositoryUser(String localRepositoryUser) {
config().setLocalRepositoryUser(localRepositoryUser);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager localRepositoryPassword(
String localRepositoryPassword) {
config().setLocalRepositoryPassword(localRepositoryPassword);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager timeout(int timeout) {
config().setTimeout(timeout);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager properties(String properties) {
config().setProperties(properties);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager cachePath(String cachePath) {
config().setCachePath(cachePath);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager resolutionCachePath(String resolutionCachePath) {
config().setResolutionCachePath(resolutionCachePath);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager avoidExport() {
config().setAvoidExport(true);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager avoidOutputTree() {
config().setAvoidOutputTree(true);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager avoidBrowserDetection() {
config().setAvoidBrowserDetection(true);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager avoidResolutionCache() {
config().setAvoidResolutionCache(true);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager avoidFallback() {
config().setAvoidFallback(true);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager avoidReadReleaseFromRepository() {
config().setAvoidReadReleaseFromRepository(true);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager avoidTmpFolder() {
config().setAvoidTmpFolder(true);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager ttl(int seconds) {
config().setTtl(seconds);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager ttlBrowsers(int seconds) {
config().setTtlForBrowsers(seconds);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager browserVersionDetectionCommand(
String browserVersionCommand) {
config().setBrowserVersionDetectionCommand(browserVersionCommand);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager useLocalVersionsPropertiesFirst() {
config().setVersionsPropertiesOnlineFirst(false);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager useLocalCommandsPropertiesFirst() {
config().setCommandsPropertiesOnlineFirst(false);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager versionsPropertiesUrl(URL url) {
config().setVersionsPropertiesUrl(url);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager commandsPropertiesUrl(URL url) {
config().setCommandsPropertiesUrl(url);
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager clearResolutionCache() {
initResolutionCache();
instanceMap.get(getDriverManagerType()).resolutionCache.clear();
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager clearDriverCache() {
String cachePath = config().getCachePath();
try {
log.debug("Clearing driver cache at {}", cachePath);
cleanDirectory(new File(cachePath));
} catch (Exception e) {
log.warn("Exception deleting driver cache at {}", cachePath, e);
}
return instanceMap.get(getDriverManagerType());
}
public WebDriverManager browserVersionDetectionRegex(String regex) {
config().setBrowserVersionDetectionRegex(regex);
return instanceMap.get(getDriverManagerType());
}
// ------------
public String getDownloadedDriverPath() {
return instanceMap.get(getDriverManagerType()).downloadedDriverPath;
}
public String getDownloadedDriverVersion() {
return instanceMap.get(getDriverManagerType()).downloadedDriverVersion;
}
public List<String> getDriverVersions() {
httpClient = new HttpClient(config());
try {
List<URL> driverUrls = getDriverUrls();
List<String> driverVersionList = new ArrayList<>();
for (URL url : driverUrls) {
String driverVersion = getCurrentVersion(url);
if (driverVersion.isEmpty()
|| driverVersion.equalsIgnoreCase("icons")) {
continue;
}
if (!driverVersionList.contains(driverVersion)) {
driverVersionList.add(driverVersion);
}
}
log.trace("Driver version list before sorting {}",
driverVersionList);
sort(driverVersionList, new VersionComparator());
return driverVersionList;
} catch (IOException e) {
throw new WebDriverManagerException(e);
}
}
// ------------
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
versionDetector = new VersionDetector(config, httpClient);
downloader = new Downloader(httpClient, config(),
this::postDownload);
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
if (versionDetector.isSnap() && config.isUseChromiumDriverSnap()) {
String chromiumDriverSnapPath = config()
.getChromiumDriverSnapPath();
File snapChromiumDriverPath = new File(chromiumDriverSnapPath);
boolean existsSnap = snapChromiumDriverPath.exists();
if (existsSnap) {
log.debug("Found {} snap", getDriverManagerType());
exportDriver(chromiumDriverSnapPath);
}
return;
}
Optional<String> driverInCache = empty();
if (!isUnknown(driverVersion)) {
driverInCache = cacheHandler.getDriverFromCache(driverVersion,
getDriverName(), getDriverManagerType(),
config().getArchitecture(), config().getOs());
}
String exportValue;
if (driverInCache.isPresent() && !config().isForceDownload()) {
log.debug("Driver {} {} found in cache", getDriverName(),
getDriverVersionLabel(driverVersion));
exportValue = driverInCache.get();
downloadedDriverVersion = driverVersion;
} else {
exportValue = download(driverVersion);
}
exportDriver(exportValue);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
protected String resolveDriverVersion(String driverVersion) {
String preferenceKey = getKeyForResolutionCache();
Optional<String> optionalBrowserVersion = Optional
.ofNullable(getBrowserVersion())
.filter(StringUtils::isNotEmpty);
if (!optionalBrowserVersion.isPresent()) {
optionalBrowserVersion = getValueFromResolutionCache(preferenceKey);
}
if (!optionalBrowserVersion.isPresent()) {
optionalBrowserVersion = detectBrowserVersion();
}
if (optionalBrowserVersion.isPresent()) {
preferenceKey = getKeyForResolutionCache()
+ optionalBrowserVersion.get();
Optional<String> optionalDriverVersion = getValueFromResolutionCache(
preferenceKey);
if (!optionalDriverVersion.isPresent()) {
optionalDriverVersion = getDriverVersionFromRepository(
optionalBrowserVersion);
}
if (!optionalDriverVersion.isPresent()) {
optionalDriverVersion = versionDetector
.getDriverVersionFromProperties(preferenceKey);
}
if (optionalDriverVersion.isPresent()) {
driverVersion = optionalDriverVersion.get();
log.info("Using {} {} (resolved driver for {} {})",
getDriverName(), driverVersion,
getDriverManagerType().getBrowserName(),
optionalBrowserVersion.get());
if (config.getIgnoreVersions().contains(driverVersion)) {
String formerBrowserVersion = valueOf(
parseInt(optionalBrowserVersion.get()) - 1);
log.info(
"The driver {} {} is configured to be ignored ... trying again resolving driver for former version of {} (i.e. {})",
getDriverName(), driverVersion,
getDriverManagerType(), formerBrowserVersion);
setBrowserVersion(formerBrowserVersion);
return resolveDriverVersion("");
}
storeInResolutionCache(preferenceKey, driverVersion,
optionalBrowserVersion.get());
}
}
if (isUnknown(driverVersion)) {
String browserVersionStr = optionalBrowserVersion.isPresent()
? " " + optionalBrowserVersion.get()
: "";
log.debug(
"The driver version for {}{} is unknown ... trying with latest",
getDriverManagerType(), browserVersionStr);
Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository();
if (latestDriverVersionFromRepository.isPresent()) {
driverVersion = latestDriverVersionFromRepository.get();
}
}
return driverVersion;
}
protected void initResolutionCache() {
resolutionCache = new ResolutionCache(config);
}
protected String download(String driverVersion) throws IOException {
if (driverVersion.startsWith(".")) {
driverVersion = driverVersion.substring(1);
}
UrlHandler urlHandler = createUrlHandler(driverVersion);
URL url = urlHandler.getCandidateUrl();
downloadedDriverVersion = urlHandler.getDriverVersion();
return downloader.download(url, downloadedDriverVersion,
getDriverName(), getDriverManagerType());
}
protected void exportDriver(String variableValue) {
downloadedDriverPath = variableValue;
Optional<String> exportParameter = getExportParameter();
if (!config.isAvoidExport() && exportParameter.isPresent()) {
String variableName = exportParameter.get();
log.info("Exporting {} as {}", variableName, variableValue);
System.setProperty(variableName, variableValue);
} else {
log.info("Driver location: {}", variableValue);
}
}
protected void storeInResolutionCache(String preferenceKey,
String resolvedDriverVersion, String resolvedBrowserVersion) {
if (useResolutionCache()) {
resolutionCache.putValueInResolutionCacheIfEmpty(
getKeyForResolutionCache(), resolvedBrowserVersion,
config().getTtlForBrowsers());
resolutionCache.putValueInResolutionCacheIfEmpty(preferenceKey,
resolvedDriverVersion, config().getTtl());
}
}
protected Optional<String> getValueFromResolutionCache(
String preferenceKey) {
Optional<String> optionalBrowserVersion = empty();
if (useResolutionCacheWithKey(preferenceKey)) {
optionalBrowserVersion = Optional.of(
resolutionCache.getValueFromResolutionCache(preferenceKey));
}
return optionalBrowserVersion;
}
protected List<File> postDownload(File archive) {
File parentFolder = archive.getParentFile();
File[] ls = parentFolder.listFiles();
for (File f : ls) {
if (getDriverName().contains(removeExtension(f.getName()))) {
log.trace("Found driver in post-download: {}", f);
return singletonList(f);
}
}
throw new WebDriverManagerException("Driver " + getDriverName()
+ " not found (using temporal folder " + parentFolder + ")");
}
protected Optional<String> getBrowserVersionFromTheShell() {
return versionDetector.getBrowserVersionFromTheShell(
getDriverManagerType().getBrowserName().toLowerCase());
}
protected Optional<String> detectBrowserVersion() {
if (config().isAvoidBrowserDetection()) {
return empty();
}
String driverManagerTypeLowerCase = getDriverManagerType().name()
.toLowerCase(ROOT);
Optional<String> optionalBrowserVersion;
if (useResolutionCacheWithKey(driverManagerTypeLowerCase)) {
optionalBrowserVersion = Optional.of(resolutionCache
.getValueFromResolutionCache(driverManagerTypeLowerCase));
log.trace("Detected {} version {}", getDriverManagerType(),
optionalBrowserVersion);
} else {
optionalBrowserVersion = getBrowserVersionFromTheShell();
}
return optionalBrowserVersion;
}
protected boolean useResolutionCacheWithKey(String key) {
return useResolutionCache()
&& resolutionCache.checkKeyInResolutionCache(key);
}
protected boolean useResolutionCache() {
return !config().isAvoidingResolutionCache();
}
protected boolean isUnknown(String driverVersion) {
return isNullOrEmpty(driverVersion)
|| driverVersion.equalsIgnoreCase("latest");
}
protected String getCurrentVersion(URL url) {
String currentVersion = "";
String pattern = "/([^/]*?)/[^/]*?" + getShortDriverName();
Matcher matcher = compile(pattern, CASE_INSENSITIVE)
.matcher(url.getFile());
boolean find = matcher.find();
if (find) {
currentVersion = matcher.group(1);
} else {
log.trace("Version not found in URL {}", url);
}
return currentVersion;
}
protected void handleException(Exception e, String driverVersion) {
String driverVersionStr = getDriverVersionLabel(driverVersion);
String errorMessage = String.format(
"There was an error managing %s %s (%s)", getDriverName(),
driverVersionStr, e.getMessage());
if (retryCount == 0 && !config().isAvoidFallback()) {
retryCount++;
if (getDriverManagerType() == EDGE
|| getDriverManagerType() == CHROME) {
config().setAvoidReadReleaseFromRepository(true);
clearResolutionCache();
log.warn(
"{} ... trying again avoiding reading release from repository",
errorMessage);
manage("");
} else {
retryCount++;
fallback(e, errorMessage);
}
} else if (retryCount == 1 && !config().isAvoidFallback()) {
fallback(e, errorMessage);
} else {
log.error("{}", errorMessage, e);
throw new WebDriverManagerException(e);
}
}
protected void fallback(Exception e, String errorMessage) {
String driverVersion;
config().setAvoidBrowserDetection(true);
driverVersion = "";
setBrowserVersion("");
retryCount++;
log.warn("{} ... trying again using latest driver stored in cache",
errorMessage);
if (log.isTraceEnabled()) {
log.trace("Error trace: ", e);
}
manage(driverVersion);
}
protected UrlHandler createUrlHandler(String driverVersion)
throws IOException {
List<URL> candidateUrls = getDriverUrls();
String shortDriverName = getShortDriverName();
UrlHandler urlHandler = new UrlHandler(config(), candidateUrls,
driverVersion, shortDriverName, this::buildUrl);
log.trace("All driver URLs: {}", candidateUrls);
boolean getLatest = isUnknown(driverVersion);
boolean continueSearchingVersion;
do {
// Filter by driver name
urlHandler.filterByDriverName(shortDriverName);
// Filter for latest or concrete driver version
if (getLatest) {
urlHandler.filterByLatestVersion(this::getCurrentVersion);
} else {
urlHandler.filterByVersion(driverVersion);
}
if (urlHandler.getDriverVersion() == null) {
break;
}
log.debug("Driver to be downloaded {} {}", shortDriverName,
urlHandler.getDriverVersion());
log.trace("Driver URLs after filtering for version: {}",
urlHandler.getCandidateUrls());
String os = config().getOs();
Architecture architecture = config().getArchitecture();
// Filter by OS
if (architecture != ARM64 || getDriverManagerType() != EDGE) {
urlHandler.filterByOs(getDriverName(), os);
}
// Rest of filters
urlHandler.filterByArch(architecture, forcedArch);
urlHandler.filterByDistro(os, getDriverName());
urlHandler.filterByIgnoredVersions(config().getIgnoreVersions());
urlHandler.filterByBeta(config().isUseBetaVersions());
continueSearchingVersion = urlHandler.hasNoCandidateUrl()
&& getLatest;
if (continueSearchingVersion) {
log.info(
"No proper driver found for {} {} ... seeking another version",
getDriverName(), getDriverVersionLabel(driverVersion));
urlHandler.resetList(candidateUrls);
candidateUrls = urlHandler.getCandidateUrls();
}
} while (continueSearchingVersion);
return urlHandler;
}
/**
* This method works also for http://npm.taobao.org/ and
* https://bitbucket.org/ mirrors.
*/
protected List<URL> getDriversFromMirror(URL driverUrl) throws IOException {
if (!mirrorLog) {
log.debug("Crawling driver list from mirror {}", driverUrl);
mirrorLog = true;
} else {
log.trace("[Recursive call] Crawling driver list from mirror {}",
driverUrl);
}
String driverStr = driverUrl.toString();
String driverOrigin = String.format("%s://%s", driverUrl.getProtocol(),
driverUrl.getAuthority());
try (CloseableHttpResponse response = httpClient
.execute(httpClient.createHttpGet(driverUrl))) {
InputStream in = response.getEntity().getContent();
org.jsoup.nodes.Document doc = Jsoup.parse(in, null, driverStr);
Iterator<org.jsoup.nodes.Element> iterator = doc.select("a")
.iterator();
List<URL> urlList = new ArrayList<>();
while (iterator.hasNext()) {
String link = iterator.next().attr("abs:href");
if (link.startsWith(driverStr) && link.endsWith(SLASH)) {
urlList.addAll(getDriversFromMirror(new URL(link)));
} else if (link.startsWith(driverOrigin)
&& !link.contains("icons")
&& (link.toLowerCase(ROOT).endsWith(".bz2")
|| link.toLowerCase(ROOT).endsWith(".zip")
|| link.toLowerCase(ROOT).endsWith(".gz"))) {
urlList.add(new URL(link));
}
}
return urlList;
}
}
protected NamespaceContext getNamespaceContext() {
return null;
}
protected Optional<NamespaceContext> getS3NamespaceContext() {
return Optional.of(S3_NAMESPACE_CONTEXT);
}
protected List<URL> getDriversFromXml(URL driverUrl, String xpath,
Optional<NamespaceContext> namespaceContext) throws IOException {
logSeekRepo(driverUrl);
List<URL> urls = new ArrayList<>();
try {
try (CloseableHttpResponse response = httpClient
.execute(httpClient.createHttpGet(driverUrl))) {
Document xml = loadXML(response.getEntity().getContent());
XPath xPath = newInstance().newXPath();
if (namespaceContext.isPresent()) {
xPath.setNamespaceContext(namespaceContext.get());
}
NodeList nodes = (NodeList) xPath.evaluate(xpath,
xml.getDocumentElement(), NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
Element e = (Element) nodes.item(i);
urls.add(new URL(driverUrl.toURI().resolve(".")
+ e.getChildNodes().item(0).getNodeValue()));
}
}
} catch (Exception e) {
throw new WebDriverManagerException(e);
}
return urls;
}
protected void logSeekRepo(URL driverUrl) {
log.info("Reading {} to seek {}", driverUrl, getDriverName());
}
protected Document loadXML(InputStream inputStream)
throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(
new ByteArrayInputStream(IOUtils.toByteArray(inputStream))));
}
protected InputStream openGitHubConnection(URL driverUrl)
throws IOException {
HttpGet get = httpClient.createHttpGet(driverUrl);
String gitHubToken = config().getGitHubToken();
if (!isNullOrEmpty(gitHubToken)) {
get.addHeader("Authorization", "token " + gitHubToken);
}
return httpClient.execute(get).getEntity().getContent();
}
protected List<URL> getDriversFromGitHub() throws IOException {
List<URL> urls;
URL driverUrl = getDriverUrl();
logSeekRepo(driverUrl);
Optional<URL> mirrorUrl = getMirrorUrl();
if (mirrorUrl.isPresent() && config.isUseMirror()) {
urls = getDriversFromMirror(mirrorUrl.get());
} else {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(openGitHubConnection(driverUrl)))) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GitHubApi[] releaseArray = gson.fromJson(reader,
GitHubApi[].class);