11package com .browserstack .local ;
22
33import org .apache .commons .io .FileUtils ;
4+ import org .apache .commons .io .IOUtils ;
5+
46import java .io .IOException ;
7+ import java .io .InputStream ;
58import java .io .BufferedReader ;
69import java .io .InputStreamReader ;
710import java .io .File ;
11+ import java .io .FileOutputStream ;
812import java .net .URL ;
13+ import java .net .URLConnection ;
914import java .util .regex .Pattern ;
15+ import java .util .zip .GZIPInputStream ;
16+ import java .util .zip .ZipException ;
1017
1118class LocalBinary {
1219
@@ -58,7 +65,8 @@ private void initialize() throws LocalException {
5865 throw new LocalException ("Failed to detect OS type" );
5966 }
6067
61- httpPath = BIN_URL + binFileName ;
68+ String sourceURL = BIN_URL ;
69+ httpPath = sourceURL + binFileName ;
6270 }
6371
6472 private boolean isAlpine () {
@@ -174,7 +182,7 @@ private void downloadBinary(String destParentDir, Boolean custom) throws LocalEx
174182 URL url = new URL (httpPath );
175183
176184 File f = new File (source );
177- FileUtils . copyURLToFile (url , f );
185+ newCopyToFile (url , f );
178186
179187 changePermissions (binaryPath );
180188 } catch (Exception e ) {
@@ -192,4 +200,38 @@ private void changePermissions(String path) {
192200 public String getBinaryPath () {
193201 return binaryPath ;
194202 }
203+
204+ private static void newCopyToFile (URL url , File f ) throws IOException {
205+ URLConnection conn = url .openConnection ();
206+ conn .setRequestProperty ("User-Agent" , "browserstack-local-java/" + Local .getPackageVersion ());
207+ conn .setRequestProperty ("Accept-Encoding" , "gzip, *" );
208+ String contentEncoding = conn .getContentEncoding ();
209+
210+ if (contentEncoding == null || !contentEncoding .toLowerCase ().contains ("gzip" )) {
211+ customCopyInputStreamToFile (conn .getInputStream (), f , url );
212+ return ;
213+ }
214+
215+ try (InputStream stream = new GZIPInputStream (conn .getInputStream ())) {
216+ if (System .getenv ().containsKey ("BROWSERSTACK_LOCAL_DEBUG_GZIP" )) {
217+ System .out .println ("using gzip in " + conn .getRequestProperty ("User-Agent" ));
218+ }
219+
220+ customCopyInputStreamToFile (stream , f , url );
221+ } catch (ZipException e ) {
222+ FileUtils .copyURLToFile (url , f );
223+ }
224+ }
225+
226+ private static void customCopyInputStreamToFile (InputStream stream , File file , URL url ) throws IOException {
227+ try {
228+ FileUtils .copyInputStreamToFile (stream , file );
229+ } catch (Throwable e ) {
230+ try (FileOutputStream fos = new FileOutputStream (file )) {
231+ IOUtils .copy (stream , fos );
232+ } catch (Throwable th ) {
233+ FileUtils .copyURLToFile (url , file );
234+ }
235+ }
236+ }
195237}
0 commit comments