1 /* 2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 package jdk.test.lib.util; 25 26 import java.lang.module.ModuleDescriptor; 27 import java.lang.module.ModuleFinder; 28 import java.lang.module.ModuleReader; 29 import java.lang.module.ModuleReference; 30 import java.net.URI; 31 import java.util.HashMap; 32 import java.util.HashSet; 33 import java.util.Map; 34 import java.util.Objects; 35 import java.util.Optional; 36 import java.util.Set; 37 38 39 /** 40 * This class consists exclusively of static utility methods that are useful 41 * for creating tests for modules. 42 */ 43 44 public final class ModuleUtils { ModuleUtils()45 private ModuleUtils() { } 46 47 48 /** 49 * Returns a ModuleFinder that finds modules with the given module 50 * descriptors. 51 */ finderOf(ModuleDescriptor... descriptors)52 public static ModuleFinder finderOf(ModuleDescriptor... descriptors) { 53 54 // Create a ModuleReference for each module 55 Map<String, ModuleReference> namesToReference = new HashMap<>(); 56 57 for (ModuleDescriptor descriptor : descriptors) { 58 String name = descriptor.name(); 59 60 URI uri = URI.create("module:/" + name); 61 62 ModuleReference mref = new ModuleReference(descriptor, uri) { 63 @Override 64 public ModuleReader open() { 65 throw new UnsupportedOperationException(); 66 } 67 }; 68 69 namesToReference.put(name, mref); 70 } 71 72 return new ModuleFinder() { 73 @Override 74 public Optional<ModuleReference> find(String name) { 75 Objects.requireNonNull(name); 76 return Optional.ofNullable(namesToReference.get(name)); 77 } 78 @Override 79 public Set<ModuleReference> findAll() { 80 return new HashSet<>(namesToReference.values()); 81 } 82 }; 83 } 84 85 } 86