1 /* 2 * Copyright 2020 The Android Open Source Project 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 17 package android.app.appsearch; 18 19 20 import android.annotation.NonNull; 21 22 import java.util.ArrayList; 23 import java.util.Arrays; 24 import java.util.Collection; 25 import java.util.Collections; 26 import java.util.List; 27 import java.util.Objects; 28 29 /** 30 * Encapsulates a request to index documents into an {@link AppSearchSession} database. 31 * 32 * @see AppSearchSession#put 33 */ 34 public final class PutDocumentsRequest { 35 private final List<GenericDocument> mDocuments; 36 PutDocumentsRequest(List<GenericDocument> documents)37 PutDocumentsRequest(List<GenericDocument> documents) { 38 mDocuments = documents; 39 } 40 41 /** Returns a list of {@link GenericDocument} objects that are part of this request. */ 42 @NonNull getGenericDocuments()43 public List<GenericDocument> getGenericDocuments() { 44 return Collections.unmodifiableList(mDocuments); 45 } 46 47 /** Builder for {@link PutDocumentsRequest} objects. */ 48 public static final class Builder { 49 private ArrayList<GenericDocument> mDocuments = new ArrayList<>(); 50 private boolean mBuilt = false; 51 52 /** Adds one or more {@link GenericDocument} objects to the request. */ 53 @NonNull addGenericDocuments(@onNull GenericDocument... documents)54 public Builder addGenericDocuments(@NonNull GenericDocument... documents) { 55 Objects.requireNonNull(documents); 56 resetIfBuilt(); 57 return addGenericDocuments(Arrays.asList(documents)); 58 } 59 60 /** Adds a collection of {@link GenericDocument} objects to the request. */ 61 @NonNull addGenericDocuments( @onNull Collection<? extends GenericDocument> documents)62 public Builder addGenericDocuments( 63 @NonNull Collection<? extends GenericDocument> documents) { 64 Objects.requireNonNull(documents); 65 resetIfBuilt(); 66 mDocuments.addAll(documents); 67 return this; 68 } 69 70 /** Creates a new {@link PutDocumentsRequest} object. */ 71 @NonNull build()72 public PutDocumentsRequest build() { 73 mBuilt = true; 74 return new PutDocumentsRequest(mDocuments); 75 } 76 resetIfBuilt()77 private void resetIfBuilt() { 78 if (mBuilt) { 79 mDocuments = new ArrayList<>(mDocuments); 80 mBuilt = false; 81 } 82 } 83 } 84 } 85