Retrofit fails to download binary file in an Android app – end result is a corrupted file that is larger than expected

I am trying to download PDF files using Retrofit 2 on an Android app written in Kotlin. The snippet below is basically my entire code. Based on my log output, it appears that the file downloads successfully and saves to the intended location.

However, the downloaded file is larger than expected, and is corrupt. I can open it in a PDF reader, but the PDF is blank. In the example below, I tried downloading If I download this file through a browser, the result is a PDF that is 13,264 bytes. Downloaded with this code however, it is 22,503 bytes, about 70% larger than expected. I am getting a similar result for other binary files like JPEGs. However, downloading a TXT actually works fine, even a large one. So it seems like the problem is isolated to binary files.

package com.ebelinski.RetrofitTestApp  import import android.content.Context import android.os.Build import import android.os.Bundle import android.util.Log import import import okhttp3.OkHttpClient import okhttp3.ResponseBody import org.jetbrains.anko.doAsync import retrofit2.Call import retrofit2.http.* import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import* import java.util.concurrent.Executors import java.util.concurrent.TimeUnit  interface FileService {      @Streaming     @GET     @Headers("Content-Type: application/pdf", "Accept: application/pdf")     fun fileFromUrl(@Url url: String,                     @Header("Authorization") tokenTypeWithAuthorization: String): Call<ResponseBody>  }  class MainActivity : AppCompatActivity() {      val TAG = "MainActivity"      val RETROFIT_CONNECT_TIMEOUT_SECONDS = 60     private val RETROFIT_READ_TIMEOUT_SECONDS = 60     private val RETROFIT_WRITE_TIMEOUT_SECONDS = 60      private val retrofit: Retrofit         get() {             val gson = GsonBuilder()                 .setDateFormat("yyyyMMdd")                 .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)                 .create()              val converterFactory = GsonConverterFactory.create(gson)              val okHttpClient = OkHttpClient.Builder()                 .connectTimeout(RETROFIT_CONNECT_TIMEOUT_SECONDS.toLong(), TimeUnit.SECONDS)                 .readTimeout(RETROFIT_READ_TIMEOUT_SECONDS.toLong(), TimeUnit.SECONDS)                 .writeTimeout(RETROFIT_WRITE_TIMEOUT_SECONDS.toLong(), TimeUnit.SECONDS)                 .addInterceptor { chain ->                     val userAgentValue = "doesn't matter"                     val originalRequest = chain.request().newBuilder().addHeader("User-Agent", userAgentValue).build()                      var response = chain.proceed(originalRequest)                     if (BuildConfig.DEBUG) {                         val bodyString = response.body()!!.string()                         Log.d(TAG, String.format("Sending request %s with headers %s ", originalRequest.url(), originalRequest.headers()))                         Log.d(TAG, String.format("Got response HTTP %s %s \n\n with body %s \n\n with headers %s ", response.code(), response.message(), bodyString, response.headers()))                         response = response.newBuilder().body(ResponseBody.create(response.body()!!.contentType(), bodyString)).build()                     }                      response                 }                 .build()              return Retrofit.Builder()                 .callbackExecutor(Executors.newCachedThreadPool())                 .baseUrl("")                 .addConverterFactory(converterFactory)                 .client(okHttpClient)                 .build()         }      private val fileService: FileService = retrofit.create(      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          doAsync { downloadFile() }     }      fun downloadFile() {         val uri = ""         val auth = "doesn't matter"          val response = fileService.fileFromUrl(             uri,             auth         ).execute()          if (!response.isSuccessful) {             Log.e(TAG, "response was not successful: " +                     response.code() + " -- " + response.message())             throw Throwable(response.message())         }          Log.d(TAG, "Server has file for $  {uri}")         saveFileFromResponseBody(response.body()!!)     }        // Returns the name of what the file should be, whether or not it exists locally     private fun getFileName(): String? {         return "dummy.pdf"     }      fun saveFileFromResponseBody(body: ResponseBody): Boolean {         val fileName = getFileName()         val localFullFilePath = File(getFileFullDirectoryPath(), fileName)         var inputStream: InputStream? = null         var outputStream: OutputStream? = null         Log.d(TAG, "Attempting to download $  fileName")          try {             val fileReader = ByteArray(4096)             val fileSize = body.contentLength()             var fileSizeDownloaded: Long = 0              inputStream = body.byteStream()             outputStream = FileOutputStream(localFullFilePath)              while (true) {                 val read =                 if (read == -1) break                  outputStream.write(fileReader, 0, read)                 fileSizeDownloaded += read.toLong()                  Log.d(TAG, "$  fileName download progress: $  fileSizeDownloaded of $  fileSize")             }              outputStream.flush()             Log.d(TAG, "$  fileName downloaded successfully")             return true         } catch (e: IOException) {             Log.d(TAG, "$  fileName downloaded attempt failed")             return false         } finally {             inputStream?.close()             outputStream?.close()         }     }      fun getFileFullDirectoryPath(): String {         val directory = getDir("test_dir", Context.MODE_PRIVATE)         return directory.absolutePath     } } 

If it helps, here’s my build.gradle file:

apply plugin: ''  apply plugin: 'kotlin-android'  apply plugin: 'kotlin-android-extensions'  android {     compileSdkVersion 28     defaultConfig {         applicationId "com.ebelinski.RetrofitTestApp"         minSdkVersion 21         targetSdkVersion 28         versionCode 1         versionName "1.0"         testInstrumentationRunner ""     }     buildTypes {         release {             minifyEnabled false             proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), ''         }     } }  dependencies {     implementation fileTree(dir: 'libs', include: ['*.jar'])     implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$  kotlin_version"     implementation ''     implementation ''     implementation 'com.squareup.retrofit2:converter-gson:2.5.0'     implementation 'com.squareup.retrofit2:retrofit:2.5.0'     implementation 'com.squareup.okhttp3:okhttp:3.12.0'     implementation "org.jetbrains.anko:anko-commons:0.10.1"     testImplementation 'junit:junit:4.12'     androidTestImplementation ''     androidTestImplementation '' } 

PowerShell – Return doesn’t behave as expected

I’m using PowerShell v5.1. I have a question about “Return”. Shouldn’t “Return” stop script execution?

Get-CimInstance Win32_OperatingSystem | ForEach-Object {     "Exiting"     Return } "It doesn't"  ForEach ($  number in 1..2){     "Exiting"     Return } "It doesn't" 

Result is: Exiting => It doesn’t => Exiting

As you can see “Return” behaves differently inside “ForEach-Object” loop then inside “ForEach” loop. What am I missing? Thank you 🙂

Alerts for A View not working as expected

We have a library that includes a column with 3 choices. We have made a view that display all items where choice = Option2. We subsequently set alerts on new items added to that view and for testing alerts for the base library. Users will receive alerts set for all new docs and will not receive alerts for docs that fit a view.

I have verified that all web servers and app servers can send email. I checked logs and have verified that immediate alerts jobs run and are sent and received, just not for the alerts based on a view.

What else can I check? Is this a bug?

Bash if clause not working as expected

#!/bin/bash python3 -c "import numpy" if [ $  ? ]; then     echo Numpy needs to be installed     sudo apt-get python3-numpy fi echo Everything is properly installed 

This is what I’m trying to run.

Supposedly, it checks if numpy is already installed and if not, install it. However, it installs everytime, even though I already have it.

When I change import numpy to import asdfas it still installs numpy, so the if is not doing anything at all!

I’m sorry if this is already answered, but my google search didn’t find this specific error

Expected values of packing distance between vectors with Bernoulli trials?

Pick set $ \mathcal T$ of $ 2^k$ vectors in $ \{-1,+1\}^n$ with Bernoulli trials.

What are exact expected values or at least tight bounds of $ $ \min_{\substack {u,v\in\mathcal T\u\neq v}}\|u-v\|_2^2$ $ $ $ \min_{\substack {u,v\in\mathcal T\u\neq v}}\|u-v\|_1$ $ and their distributions?

Docker pull then start for running container – what is the expected behavior?

Let’s say I have a running Docker container X that is based on image foo.

If I pull a new version of foo, then stop and delete X, and then docker run foo – will it have the new version of the image?

Said differently – do I need to stop X before I can pull the new version of foo and then start it?

The context is Docker-EE on Windows Server 2016.

Random points on interval, expected lengths of pieces

Many years ago I came across the following task.

If we have the interval $ [0; 1]$ and we throw $ N$ uniformly distributed and mutually independent points on it, then we’ll get $ N+1$ segments. What is the expected length of the longest segment? The 2nd longest? Etc.

For $ N=1$ , the solution is trivial: $ 3/4$ and $ 1/4$ (since the longest segment is uniformly distributed in [1/2; 1] and the shorter one is uniformly distributed in $ [0; 1/2]$ ).

For $ N=2$ , the solution is not trivial, but possible. One just has to draw a quadrat 1 x 1. A point in it would mean that the longest segment has the x coordinate, and the 2nd longest segment has the y coordinate (and the shortest one is 1 – 1st – 2nd). One then has to carefully draw the possible area (this will be a triangle), and find its middle point.

But for $ N>2$ I have no clue how to solve it.

I remember, the book I saw the task in, had a general solution for arbitrary $ N$ , but I don’t know anymore what book it was.

Note that the task is somewhat similar to Average Distance Between Random Points on a Line Segment, but just somewhat.

Random walks – expected number of steps

Mouse and cat walk randomly (and independently) on the same consistent 8-regular graph with 20 vertices. At the beginning, they are in non-neighboring vertices. When they are in the same vertex, the cat eats the mouse. Explain that the expected number of steps at which the mouse will be eaten is less than 625 · 2^15

I know that average cover time for a random walk over any consistent G graph, for any state initial, is smaller than 2e(G)v(G)., where e(G) is number of edges in graph and v(G) is number verticles.

I also have a small hint that this number of steps should be smaller than 8*(e(G)^2)(v(G)^2), but don’t know how to use it and moreover prove it.

OpenVPN install – Missing expected CA file

Hey everyone it’s my first time installing a VPN on my Celeron powered Intel NUC with a clean install of Ubuntu mate 18.04. And I can’t get past this ca file requirement. I have followed the commands to input from digital ocean exactly the way they wanted. But for some reason I’m getting an EasyRSA error, and I’m not getting what’s pictured in their tutorial. Any help would be greatly appreciated, because I’m totally lost. Thanks.

Link to Guide I’m following

Screenshots of Terminal

noah@Ubuntu:~/EasyRSA-3.0.4$ ./easyrsa sign-req server server Note: using Easy-RSA configuration from: ./vars Easy-RSA error: Missing expected CA file: index.txt (perhaps you need to run build-ca?) Run easyrsa without commands for usage and command help.