summaryrefslogtreecommitdiff
path: root/java/com/google/android/libraries/mobiledatadownload/downloader/inline/InlineFileDownloader.java
blob: 8f3d472e3620944611644a97103982250d11351b (plain)
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
/*
 * Copyright 2022 Google LLC
 *
 * 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 com.google.android.libraries.mobiledatadownload.downloader.inline;

import static com.google.android.libraries.mobiledatadownload.internal.MddConstants.INLINE_FILE_URL_SCHEME;

import com.google.android.libraries.mobiledatadownload.DownloadException;
import com.google.android.libraries.mobiledatadownload.DownloadException.DownloadResultCode;
import com.google.android.libraries.mobiledatadownload.downloader.DownloadRequest;
import com.google.android.libraries.mobiledatadownload.downloader.FileDownloader;
import com.google.android.libraries.mobiledatadownload.downloader.InlineDownloadParams;
import com.google.android.libraries.mobiledatadownload.file.SynchronousFileStorage;
import com.google.android.libraries.mobiledatadownload.file.openers.ReadStreamOpener;
import com.google.android.libraries.mobiledatadownload.file.openers.WriteStreamOpener;
import com.google.android.libraries.mobiledatadownload.internal.logging.LogUtil;
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Executor;

/**
 * An implementation of {@link FileDownloader} that supports copying in-memory data to disk.
 *
 * <p>This implementation only supports copying for "inlinefile:" url schemes. For more details see
 * <internal>.
 *
 * <p>NOTE: copying in-memory data can be thought of as "inline file downloading," hence the naming
 * of this class.
 */
public final class InlineFileDownloader implements FileDownloader {
  private static final String TAG = "InlineFileDownloader";

  private final SynchronousFileStorage fileStorage;
  private final Executor downloadExecutor;

  /**
   * Construct InlineFileDownloader instance.
   *
   * @param fileStorage a file storage instance used to perform I/O
   * @param downloadExecutor executor that will perfrom the download. This should be
   *     the @MddDownloadExecutor
   */
  public InlineFileDownloader(SynchronousFileStorage fileStorage, Executor downloadExecutor) {
    this.fileStorage = fileStorage;
    this.downloadExecutor = downloadExecutor;
  }

  @Override
  public ListenableFuture<Void> startDownloading(DownloadRequest downloadRequest) {
    if (!downloadRequest.urlToDownload().startsWith(INLINE_FILE_URL_SCHEME)) {
      LogUtil.e(
          "%s: Invalid url given, expected to start with 'inlinefile:', but was %s",
          TAG, downloadRequest.urlToDownload());
      return Futures.immediateFailedFuture(
          DownloadException.builder()
              .setDownloadResultCode(DownloadResultCode.INVALID_INLINE_FILE_URL_SCHEME)
              .setMessage("InlineFileDownloader only supports copying inlinefile: scheme")
              .build());
    }
    // DownloadRequest requires InlineDownloadParams to be present when building a request with
    // inlinefile scheme, so we can access it directly here.
    InlineDownloadParams inlineDownloadParams =
        downloadRequest.inlineDownloadParamsOptional().get();

    return Futures.submitAsync(
        () -> {
          try (InputStream inlineFileStream = getInputStream(inlineDownloadParams);
              OutputStream destinationStream =
                  fileStorage.open(downloadRequest.fileUri(), WriteStreamOpener.create())) {
            ByteStreams.copy(inlineFileStream, destinationStream);
            destinationStream.flush();
          } catch (IOException e) {
            LogUtil.e(e, "%s: Unable to copy file content.", TAG);
            return Futures.immediateFailedFuture(
                DownloadException.builder()
                    .setCause(e)
                    .setDownloadResultCode(DownloadResultCode.INLINE_FILE_IO_ERROR)
                    .build());
          }
          return Futures.immediateVoidFuture();
        },
        downloadExecutor);
  }

  private InputStream getInputStream(InlineDownloadParams params) throws IOException {
    switch (params.inlineFileContent().getKind()) {
      case URI:
        return fileStorage.open(params.inlineFileContent().uri(), ReadStreamOpener.create());
      case BYTESTRING:
        return params.inlineFileContent().byteString().newInput();
    }
    throw new IllegalStateException("unreachable");
  }
}