• 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.openers;
17 
18 import com.google.android.libraries.mobiledatadownload.file.Behavior;
19 import com.google.android.libraries.mobiledatadownload.file.OpenContext;
20 import com.google.android.libraries.mobiledatadownload.file.Opener;
21 import com.google.errorprone.annotations.CanIgnoreReturnValue;
22 import java.io.IOException;
23 import java.io.OutputStream;
24 import java.util.List;
25 
26 /**
27  * An opener that returns a simple OutputStream opened for write. Any existing content is truncated.
28  */
29 public final class WriteStreamOpener implements Opener<OutputStream> {
30 
31   private Behavior[] behaviors;
32 
WriteStreamOpener()33   private WriteStreamOpener() {}
34 
create()35   public static WriteStreamOpener create() {
36     return new WriteStreamOpener();
37   }
38 
39   @CanIgnoreReturnValue
withBehaviors(Behavior... behaviors)40   public WriteStreamOpener withBehaviors(Behavior... behaviors) {
41     this.behaviors = behaviors;
42     return this;
43   }
44 
45   @Override
open(OpenContext openContext)46   public OutputStream open(OpenContext openContext) throws IOException {
47     OutputStream backendOutput = openContext.backend().openForWrite(openContext.encodedUri());
48     List<OutputStream> chain = openContext.chainTransformsForWrite(backendOutput);
49     if (behaviors != null) {
50       for (Behavior behavior : behaviors) {
51         behavior.forOutputChain(chain);
52       }
53     }
54     return chain.get(0);
55   }
56 }
57