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.backends; 17 18 import android.net.Uri; 19 import com.google.android.libraries.mobiledatadownload.file.common.internal.LiteTransformFragments; 20 import com.google.android.libraries.mobiledatadownload.file.transforms.TransformProtos; 21 import com.google.common.collect.ImmutableList; 22 import com.google.errorprone.annotations.CanIgnoreReturnValue; 23 import com.google.mobiledatadownload.TransformProto; 24 import java.io.File; 25 26 /** Helper class for "file:" Uris. TODO(b/62106564) Rename to "localfile". */ 27 public final class FileUri { 28 29 static final String SCHEME_NAME = "file"; 30 31 /** Creates a file: scheme URI builder. */ builder()32 public static Builder builder() { 33 return new Builder(); 34 } 35 36 /** Builds a URI from a File. */ fromFile(File file)37 public static Uri fromFile(File file) { 38 return builder().fromFile(file).build(); 39 } 40 FileUri()41 private FileUri() {} 42 43 /** A builder for file: scheme URIs. */ 44 public static class Builder { 45 private Uri.Builder uri = new Uri.Builder().scheme("file").authority("").path("/"); 46 private final ImmutableList.Builder<String> encodedSpecs = ImmutableList.builder(); 47 Builder()48 private Builder() {} 49 50 @CanIgnoreReturnValue setPath(String path)51 public Builder setPath(String path) { 52 uri.path(path); 53 return this; 54 } 55 56 @CanIgnoreReturnValue fromFile(File file)57 public Builder fromFile(File file) { 58 uri.path(file.getAbsolutePath()); 59 return this; 60 } 61 62 @CanIgnoreReturnValue appendPath(String segment)63 public Builder appendPath(String segment) { 64 uri.appendPath(segment); 65 return this; 66 } 67 68 @CanIgnoreReturnValue withTransform(TransformProto.Transform spec)69 public Builder withTransform(TransformProto.Transform spec) { 70 encodedSpecs.add(TransformProtos.toEncodedSpec(spec)); 71 return this; 72 } 73 build()74 public Uri build() { 75 String fragment = LiteTransformFragments.joinTransformSpecs(encodedSpecs.build()); 76 return uri.encodedFragment(fragment).build(); 77 } 78 } 79 } 80