1 /* 2 * Copyright (C) 2016 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 com.android.printservice.recommendation.util; 18 19 import android.net.nsd.NsdServiceInfo; 20 import android.util.ArrayMap; 21 22 import java.net.InetAddress; 23 import java.util.ArrayList; 24 25 /** 26 * Map to store {@link NsdServiceInfo} belonging to printers. If two infos have the same 27 * {@link PrinterHashMap#getKey(NsdServiceInfo) key} they are considered the same. 28 */ 29 public class PrinterHashMap { 30 private final ArrayMap<String, NsdServiceInfo> mPrinters = new ArrayMap<>(); 31 32 /** 33 * Key uniquely identifying a printer. 34 * 35 * @param serviceInfo The service info describing the printer 36 * 37 * @return The key 38 */ getKey(NsdServiceInfo serviceInfo)39 public static String getKey(NsdServiceInfo serviceInfo) { 40 return serviceInfo.getServiceName(); 41 } 42 43 /** 44 * Add a printer. 45 * 46 * @param device The service info of the printer 47 * 48 * @return The service info of the printer that was previously registered for the same key 49 */ addPrinter(NsdServiceInfo device)50 public NsdServiceInfo addPrinter(NsdServiceInfo device) { 51 return mPrinters.put(getKey(device), device); 52 } 53 54 /** 55 * Remove a printer. 56 * 57 * @param device The service info of the printer 58 * 59 * @return The service info of the printer that was previously registered for the same key 60 */ removePrinter(NsdServiceInfo device)61 public NsdServiceInfo removePrinter(NsdServiceInfo device) { 62 return mPrinters.remove(getKey(device)); 63 } 64 65 /** 66 * @return the addresses of printers 67 */ getPrinterAddresses()68 public ArrayList<InetAddress> getPrinterAddresses() { 69 int numPrinters = mPrinters.size(); 70 ArrayList<InetAddress> printerAddressess = new ArrayList<>(numPrinters); 71 for (int i = 0; i < numPrinters; i++) { 72 printerAddressess.add(mPrinters.valueAt(i).getHost()); 73 } 74 75 return printerAddressess; 76 } 77 78 /** 79 * Remove all printers 80 */ clear()81 public void clear() { 82 mPrinters.clear(); 83 } 84 85 /** 86 * @return {@code} true iff the map is empty 87 */ isEmpty()88 public boolean isEmpty() { 89 return mPrinters.isEmpty(); 90 } 91 } 92