• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 Google LLC
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.google.android.libraries.mobiledatadownload.file.transforms;
17 
18 import android.net.Uri;
19 import com.google.android.libraries.mobiledatadownload.file.common.Fragment;
20 import com.google.android.libraries.mobiledatadownload.file.spi.Transform;
21 import java.io.BufferedOutputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 
26 /**
27  * BufferTransform takes writes and holds on to it until enough has been written to justify flushing
28  * to the disk. Reads are not affected by this transform.
29  *
30  * <p>A flush of the buffer can be performed using {@link OutputStream#flush()}.
31  *
32  * <p>It is configured using transform fragment int param {@code size}. For example: {@code
33  * file:///tmp/file#transform=buffer(size=1024)}.
34  */
35 public class BufferTransform implements Transform {
36 
37   private static final int DEFAULT_BUFFER_SIZE = 8192;
38 
39   private static final String TRANSFORM_NAME = "buffer";
40   private static final String SUBPARAM_SIZE = "size";
41 
42   @Override
name()43   public String name() {
44     return TRANSFORM_NAME;
45   }
46 
47   @Override
wrapForRead(Uri uri, InputStream wrapped)48   public InputStream wrapForRead(Uri uri, InputStream wrapped) throws IOException {
49     return wrapped;
50   }
51 
52   @Override
wrapForAppend(Uri uri, OutputStream wrapped)53   public OutputStream wrapForAppend(Uri uri, OutputStream wrapped) throws IOException {
54     return wrapForWrite(uri, wrapped);
55   }
56 
57   @Override
wrapForWrite(Uri uri, OutputStream wrapped)58   public OutputStream wrapForWrite(Uri uri, OutputStream wrapped) throws IOException {
59     String bufferSizeStr = Fragment.getTransformSubParam(uri, name(), SUBPARAM_SIZE);
60     int bufferSize = DEFAULT_BUFFER_SIZE;
61     if (bufferSizeStr != null) {
62       bufferSize = Integer.parseInt(bufferSizeStr);
63     }
64     return new BufferedOutputStream(wrapped, bufferSize);
65   }
66 }
67